Compare commits

...
57 Commits
Author SHA1 Message Date
Chris Troutner 6e7ab40dea Merge pull request #17 from Permissionless-Software-Foundation/ct-unstable
fix(webhook): Fixing default webhook URL
2022-03-31 18:51:04 -07:00
Chris Troutner 3b45e3c2c4 fix(domain): Detecting domain for working with back-end 2022-03-31 18:48:05 -07:00
Chris Troutner 756002dd8c fix(webhook): Fixing default webhook URL 2022-03-31 18:04:13 -07:00
Chris Troutner 86da41b6c8 Making instruction steps a numbered list 2022-03-29 11:07:44 -07:00
Chris Troutner c2838b6117 Updating install step 2022-03-29 11:03:11 -07:00
Chris Troutner af33de3f9a Adding links to videos 2022-03-29 09:27:29 -07:00
Chris Troutner 50d7cf137f Merge pull request #16 from Permissionless-Software-Foundation/ct-unstable
fix(createOrder()): Updating wallet UTXOs before checking for funds
2022-03-27 19:42:42 -07:00
Chris Troutner dad9803d69 fix(createOrder()): Updating wallet UTXOs before checking for funds 2022-03-27 19:17:52 -07:00
Chris Troutner a235e57302 Merge pull request #15 from Permissionless-Software-Foundation/ct-unstable
fix(production): Auto-restarting bch-dex Docker container
2022-03-27 13:59:03 -07:00
Chris Troutner bb2f20b322 fix(production): Auto-restarting bch-dex Docker container 2022-03-27 13:47:05 -07:00
Chris Troutner 1f91bb05dd Editing README 2022-03-27 11:49:55 -07:00
Chris Troutner 5e044f3d10 Editing README 2022-03-27 11:42:16 -07:00
Chris Troutner a94f2d32b5 fix(README): Adding installation instructions to README 2022-03-27 11:30:54 -07:00
Chris Troutner 4b66305392 fix(production scripts): Added create-wallet.js to scripts folder 2022-03-27 11:00:29 -07:00
Chris Troutner e23f8c2019 Merge pull request #14 from Permissionless-Software-Foundation/ct-unstable
Got Docker containers working
2022-03-27 10:18:11 -07:00
Chris Troutner f9e76a3dfb fix(createOffer()): Prevening duplicate Offers from being created 2022-03-26 20:31:34 -07:00
Chris Troutner 470fa95b74 temporary commenting out failing test 2022-03-26 19:38:23 -07:00
Chris Troutner f2b8ccaa3a fix(acceptCounterOffer()): Appropriately ignoring Counter Offers 2022-03-26 19:35:15 -07:00
Chris Troutner fa834e9114 Fixing typo in webhook 2022-03-26 19:27:32 -07:00
Chris Troutner c45b512fc6 fix(wallet): Throwing error when wallet file not passed in correctly 2022-03-26 19:20:06 -07:00
Chris Troutner e0d1aa24d4 More wallet debugging 2022-03-26 18:56:18 -07:00
Chris Troutner a4faecf56e debugging wallet file issue 2022-03-26 18:36:49 -07:00
Chris Troutner 95e66efc2f Adding more debugging 2022-03-26 18:07:41 -07:00
Chris Troutner 881a882175 fix(bug): Handling counter offer bug 2022-03-26 15:35:26 -07:00
Chris Troutner 80945039b0 Merge branch 'ct-unstable' of https://github.com/Permissionless-Software-Foundation/bch-dex into ct-unstable 2022-03-26 15:24:20 -07:00
Chris Troutner e470b26771 fix(docker): Updating to node.js v16 in all containers 2022-03-26 15:24:12 -07:00
Chris Troutner eb458f1e9f Merge branch 'ct-unstable' of https://github.com/Permissionless-Software-Foundation/bch-dex into ct-unstable 2022-03-26 15:23:15 -07:00
Chris Troutner 21f4bc2f4c Fixing webhook url 2022-03-26 15:23:11 -07:00
Chris Troutner 7e2e28834a Debugging ensureFunds() 2022-03-26 15:15:08 -07:00
Chris Troutner 07551bb693 fix(production): Minor fixes 2022-03-26 13:32:52 -07:00
Chris Troutner 207f00ba81 Merge pull request #13 from Permissionless-Software-Foundation/ct-rpi
feat(rpi): Created customized docker files for RPi4
2022-03-26 12:11:44 -07:00
Chris Troutner 3ccdf40a9c Merge branch 'master' into ct-rpi 2022-03-26 12:06:58 -07:00
Chris Troutner 0b940c797c feat(rpi): Created customized docker files for RPi4 2022-03-26 12:05:11 -07:00
Chris Troutner 04f6dbee54 Merge pull request #12 from gitter-badger/gitter-badge
Add a Gitter chat badge to README.md
2022-03-26 11:59:57 -07:00
The Gitter Badger 632320960f Add Gitter badge 2022-03-26 16:14:13 +00:00
Chris Troutner b26160b748 Merge pull request #11 from Permissionless-Software-Foundation/ct-unstable
Got production docker containers running
2022-03-26 08:40:50 -07:00
Chris Troutner 04f45eea6a Adding production/script dir 2022-03-26 08:35:16 -07:00
Chris Troutner 9096db1614 Removing old docker containers 2022-03-26 08:27:53 -07:00
Chris Troutner 369415bf8d fix(production): Got docker containers working 2022-03-26 08:25:43 -07:00
Chris Troutner 7cb536d312 Making webhook target an env var 2022-03-26 07:32:00 -07:00
Chris Troutner 592ea60892 Ported docker containers from avax-dex 2022-03-25 18:45:32 -07:00
Chris Troutner d14270c5b0 Updating package-lock.json 2022-03-25 17:59:56 -07:00
Chris Troutner 2d9a1d7cbf Merge pull request #10 from Permissionless-Software-Foundation/ct-unstable
Update to work better with UI
2022-03-25 17:53:58 -07:00
Chris Troutner e6c942d532 Fixing tests 2022-03-25 12:36:28 -07:00
Chris Troutner 1206b6576e Got first successful take workflow complete 2022-03-25 12:17:13 -07:00
Chris Troutner dbd5845e3a feat(offers): Adding garbage collection 2022-03-24 06:57:39 -07:00
Chris Troutner d14dcae6f5 feat(orders): Added garbage collection 2022-03-24 06:43:51 -07:00
Chris Troutner 8154dd96f9 Merge pull request #83 from Permissionless-Software-Foundation/ct-unstable
fix(deps): Updating bch-js
2022-03-20 07:48:42 -07:00
Chris Troutner e37223cc88 fix(deps): Updating bch-js 2022-03-20 07:46:08 -07:00
Chris Troutner 5002ef2b90 Merge pull request #82 from Permissionless-Software-Foundation/dh-test-coverage-ipfsjs
feat(test): Got ipfs.js to 100% test coverage
2022-03-18 11:27:32 -07:00
Chris Troutner 5d95109ad4 more linting 2022-03-18 11:24:15 -07:00
Chris Troutner 13b3150f62 minor linting 2022-03-18 11:24:04 -07:00
Daniel Gonzalez b3a4a7c1ab feat(test): Got ipfs.js to 100% test coverage 2022-03-15 18:58:55 -04:00
Chris Troutner 733e8fd405 Merge pull request #81 from Permissionless-Software-Foundation/ct-unstable
fix(ipfs-coord): Updating to v7.1.6
2022-03-10 09:29:32 -08:00
Chris Troutner baee72c1c6 fix(ipfs-coord): Updating to v7.1.6 2022-03-10 09:27:13 -08:00
Chris Troutner 11618a796f Merge pull request #80 from Permissionless-Software-Foundation/ct-unstable
fix(ipfs-coord): Updating to v7.1.5
2022-03-10 08:35:21 -08:00
Chris Troutner 025ae20704 fix(ipfs-coord): Updating to v7.1.5 2022-03-10 08:33:53 -08:00
41 changed files with 3739 additions and 1651 deletions
+56 -23
View File
@@ -1,34 +1,67 @@
# bch-dex
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![Join the chat at https://gitter.im/Permissionless-Software-Foundation/psf-dex-dev](https://badges.gitter.im/Permissionless-Software-Foundation/psf-dex-dev.svg)](https://gitter.im/Permissionless-Software-Foundation/psf-dex-dev?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
This is a prototype web service that monitors the [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service) for trading signals, to trade BCH and SLP tokens. It's inspired by the [SWaP Prototype](https://github.com/vinarmani/swap-protocol/blob/master/swap-protocol-spec.md).
This is a prototype web service that monitors the [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service) for trading signals, to trade BCH and SLP tokens. It's inspired by the [SWaP Protocol](https://github.com/vinarmani/swap-protocol/blob/master/swap-protocol-spec.md).
This repository was forked from [ipfs-torlist-service](https://github.com/Permissionless-Software-Foundation/ipfs-torlist-service).
## Development Notes
This repository contains the back end code. The user interface is contained in the [bch-dex-ui](https://github.com/Permissionless-Software-Foundation/bch-dex-ui) repository.
**Warning**: This repository is under active development. Things will be constantly changing and breaking.
### Road Map:
## Media
- [High-level Overview of bch-dex](https://youtu.be/LVX8CLi4sHw) (Video)
- [Developer walk-through for installing and hacking on bch-dex](https://youtu.be/T5XI43-SWJo) (Video)
- Phase 1: MVP (single user)
- Move tokens or BCH for sale to temporary address.
- Accept input from user:
- Submit Signal message to P2WDB for new buy/sell order.
- Check UTXO status before submitting Payment message.
- React to webhook when new Offers come in.
- Add and track new Offers in MongoDB.
- Process Payment signals:
- Checking transaction for compatibility
- Broadcast/close trades managed by this app.
- Phase 2: Build single-user web app
- _Make_ buy or sell orders.
- Browse Offers on the market.
- _Take_ buy or sell orders.
- Phase 3: Multi-user
- Configure REST API as an IPFS Service that can offer services to multiple users.
- Update web app to display and select available SWaP services over IPFS.
## Participate
This is an open source project, and we encourage other JavaScript developers to participate in its creation and maintenance. We have two chat rooms for the community:
- [Telegram Channel](https://t.me/psf_dex_dev)
- [Gitter Channel](https://gitter.im/Permissionless-Software-Foundation/psf-dex-dev)
## Installation
Running the DEX requires composition of these different software packages:
- bch-dex - This repository is the back end software that tracks trade data on the network, generates [Offers and Counter Offers](https://github.com/Permissionless-Software-Foundation/bch-dex/tree/ct-unstable/dev-docs#definitions), and finalizes trades by accepting Counter Offers.
- [bch-dex-ui](https://github.com/Permissionless-Software-Foundation/bch-dex-ui) is a [Gatsby](https://www.gatsbyjs.com/) web app and user interface (UI) for bch-dex.
- [P2WDB](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service) is a censorship-resistant database used to communicate trade data between peers running bch-dex.
- [IPFS](https://ipfs.io/) is a censorship-resistant network for communicating data over the internet.
- [MongoDB](https://www.mongodb.com/) is a database used by both P2WDB and bch-dex to store and manage local data.
The above software is orchestrated using [Docker](https://www.docker.com/) and Docker Compose. The target operating system is Ubuntu 20+, and the target hardware is amd64 (normal desktop PCs) and the arm64 (Raspberry Pi 4). Trying to operate this software on other operating systems or hardware is possible, but not supported.
Instructions for setting up Node.js, Docker, and Docker Compose can be found in [this Gist](https://gist.github.com/christroutner/a39f656850dc022b60f25c9663dd1cdd). Walk-through videos can also be found on the [PSF Videos page](https://psfoundation.cash/video/).
Building the Docker containers and getting the app working involve these steps:
<ol>
<li>Follow the direction in [this Gist](https://gist.github.com/christroutner/a39f656850dc022b60f25c9663dd1cdd) to install Node.js, Docker, and Docker Compose.</li>
<li>Clone the repository with `git clone https://github.com/Permissionless-Software-Foundation/bch-dex` and enter it with `cd bch-dex`.</li>
<li>Install dependencies by running `npm install`</li>
<li>Create a wallet by executing the [create-wallet.js script](./production/scripts/create-wallet.js) with `node create-wallet.js`</li>
<li>Move the `wallet.json` file to the `bch-dex` folder in either the [x86 Docker folder](./production/docker/bch-dex) or the [RPi Docker folder](./production/rpi-docker/bch-dex/) depending on your hardware target.</li>
<li>Change directory to the `docker` or `rpi-docker` folder depending on your hardware target.</li>
<li>Build the Docker containers with `docker-compose build --no-cache`.</li>
<li>Start the Docker containers with `docker-compose up -d`</li>
<li>Wait for the containers to run for about a minute, then bring them down with `docker-compose down`. That will create the needed folders in `production/data`.</li>
<li>Copy the `swarm.key` into the `production/data/go-ipfs/data/` directory. This will allow the IPFS node to connect to the PSF private network.</li>
<li>Bring the containers back up with `docker-compose up -d`.</li>
<li>Wait for the P2WDB to sync and populate bch-dex with trade data. You can monitor it with `docker logs --tail 20 -f p2wdb`.</li>
<li>Open a web browser and navigate the `http://localhost:4500`. You'll be able to see new Offers as they come in and are detected by bch-dex.</li>
<li>To take the other side of the trade, click the `Take` button in the UI.</li>
<li>You can add the 12-word mnemonic from the `wallet.json` file to the the web wallet, which will mirror your wallet in the UI, and allow you to perform basic wallet functions (send and receive BCH and tokens).</li>
</ol>
### Applying Software Updates
As this is an active project, software updates will happen frequently. To apply a software update, perform these steps.
<ol>
<li>Enter the `docker` or `rpi-docker` folder, depending on your hardware target.</li>
<li>Bring down the Docker containers with `docker-compose down`.</li>
<li>Pull in the software updates with `git pull`</li>
<li>Update dependencies with `npm install`</li>
<li>Rebuild the Docker containers with `docker-compose build --no-cache`</li>
<li>Clean up disk space by deleting old Docker images with `./cleanup-images.sh`</li>
<li>Start the Docker containers with `docker-compose up -d`</li>
</ol>
Sometimes it may be necessary to delete the databases before applying a software update. This can be done by stopping the Docker containers and deleting the `production/data` directory. When the Docker containers are restarted, they will recreate that directory. The P2WDB will re-sync and bch-dex will be populated with fresh trade data.
## License
+2 -2
View File
@@ -94,13 +94,13 @@ class Server {
try {
try {
// Delete an old webhook if it exists.
await webhookLib.deleteWebhook(`http://localhost:${config.port}/p2wdb`)
await webhookLib.deleteWebhook(config.webhookTarget)
} catch (err) {
/* exit quietly */
// console.log('err deleting webhook: ', err)
}
await webhookLib.createWebhook(`http://localhost:${config.port}/p2wdb`)
await webhookLib.createWebhook(config.webhookTarget)
console.log('Webhook created')
} catch (error) {
console.log('Webhook cant be created')
+4 -1
View File
@@ -85,7 +85,10 @@ module.exports = {
webhookService: process.env.WEBHOOKSERVICE
? process.env.WEBHOOKSERVICE
: 'http://localhost:5010/webhook', // P2WDB.
p2wdbAppId: process.env.APP_ID ? process.env.APP_ID : 'bch-dex-test556',
p2wdbAppId: process.env.APP_ID ? process.env.APP_ID : 'bch-dex-test557',
webhookTarget: process.env.WEBHOOKTARGET
? process.env.WEBHOOKTARGET
: 'http://localhost:5700/p2wdb',
// IPFS Ports
ipfsTcpPort: process.env.IPFS_TCP_PORT ? process.env.IPFS_TCP_PORT : 4001,
+2601 -1457
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -27,9 +27,9 @@
},
"repository": "Permissionless-Software-Foundation/bch-dex",
"dependencies": {
"@psf/bch-js": "6.2.1",
"@psf/bch-js": "6.2.5",
"axios": "0.21.1",
"bch-message-lib": "2.1.4",
"bch-message-lib": "2.2.0",
"bcryptjs": "2.4.3",
"bitcoincashjs-lib": "3.3.3",
"glob": "7.1.6",
@@ -52,7 +52,7 @@
"koa2-ratelimit": "0.9.1",
"libp2p": "^0.36.2",
"line-reader": "0.4.0",
"minimal-slp-wallet": "4.4.5",
"minimal-slp-wallet": "4.4.7",
"mongoose": "5.13.13",
"node-fetch": "npm:@achingbrain/node-fetch@2.6.7",
"nodemailer": "6.4.17",
-61
View File
@@ -1,61 +0,0 @@
# Docker Containers
The 'production' environment is assumed to be a set of Docker containers orchestrated with Docker Compose. The files in this directory will stand up three Docker containers:
1 An instance of go-ipfs.
2 An instance of MongoDB.
3 The JavaScript software in this repository.
The software in this repository depends on the first two containers, so if they aren't running correctly, the application won't run correctly either.
## IPFS
IPFS can be a little tricky to set up. By default, the container uses the following ports:
- 4001 for TCP connections, exposed publicly.
- 5001 for control by the application, exposed privately.
- 8080 for an IPFS gateway, consumed by the application, exposed privately.
If you already have an IPFS node running on a the computer, you will need to change the ports to avaid a conflict. To change the ports from the default, you'll need to perform a series of steps, and the order of the steps matter.
1. Edit the `docker-compose.yml` file and change the ports. Then save the file. Here is an example:
```
ports:
- 4101:4101
- 172.17.0.1:5101:5101
- 172.17.0.1:8180:8180
```
2. Bring the Docker containers up, and then back down. This will allow the IPFS container to create the config file that you'll need to edit.
- `docker-compose up -d`
- Wait a few seconds.
- `docker-compose down`
3. Update the generated config file at `../data/go-ipfs/data/config`, to update the ports in the config file, like this:
```
"Addresses": {
"API": "/ip4/0.0.0.0/tcp/5101",
"Announce": [],
"AppendAnnounce": [],
"Gateway": "/ip4/0.0.0.0/tcp/8180",
"NoAnnounce": [],
"Swarm": [
"/ip4/0.0.0.0/tcp/4101",
"/ip6/::/tcp/4101",
"/ip4/0.0.0.0/udp/4101/quic",
"/ip6/::/udp/4101/quic"
]
},
```
4. Update the port changes in the `start-production.sh` shell script. This tells the application which ports to use, in order to control the IPFS node, are are used when signaling other nodes.
5. Quickly rebuild the containers, to add the modified `start-production.sh` shell script to the application Docker container:
- `docker-compose build`
6. Now start the containers, and the port changes to IPFS should be complete.
+73
View File
@@ -0,0 +1,73 @@
# Create a Dockerized API server
#
#IMAGE BUILD COMMANDS
# ct-base-ubuntu = ubuntu 18.04 + nodejs v10 LTS
#FROM christroutner/ct-base-ubuntu
FROM ubuntu:20.04 as builder
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
#Update the OS and install any OS packages needed.
RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
#Create the user 'safeuser' and add them to the sudo group.
#RUN useradd -ms /bin/bash safeuser
#RUN adduser safeuser sudo
#Set password to 'password' change value below if you want a different password
#RUN echo safeuser:password | chpasswd
#Set the working directory to be the home directory
WORKDIR /home/safeuser
#Setup NPM for non-root global install
#RUN mkdir /home/safeuser/.npm-global
#RUN chown -R safeuser .npm-global
#RUN echo "export PATH=~/.npm-global/bin:$PATH" >> /home/safeuser/.profile
#RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
# Update to the latest version of npm.
#RUN npm install -g npm@7.23.0
RUN npm install -g npm
# npm mirror to prevent direct dependency on npm.
RUN npm set registry http://94.130.170.209:4873/
# Switch to user account.
#USER safeuser
# Prep 'sudo' commands.
#RUN echo 'abcd8765' | sudo -S pwd
# Clone the rest.bitcoin.com repository
WORKDIR /home/safeuser
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex-ui
# Switch to the desired branch. `master` is usually stable,
# and `stage` has the most up-to-date changes.
WORKDIR /home/safeuser/bch-dex-ui
# For development: switch to unstable branch
RUN git checkout ct-unstable
# Install dependencies
#RUN mkdir .ipfsdata
#RUN npm install -g @mapbox/node-pre-gyp
RUN npm install
# Build the site
RUN CI=true npm run build
# Load the NGINX image.
FROM nginx
EXPOSE 80
# Copy the files built in the first container to the new NGINX container.
COPY --from=builder /home/safeuser/bch-dex-ui/public /usr/share/nginx/html
#USER safeuser
@@ -12,7 +12,7 @@ RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_14.x -o nodesource_setup.sh
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
@@ -46,11 +46,11 @@ RUN npm set registry http://94.130.170.209:4873/
# Clone the rest.bitcoin.com repository
WORKDIR /home/safeuser
RUN git clone https://github.com/Permissionless-Software-Foundation/ipfs-service-provider
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex
# Switch to the desired branch. `master` is usually stable,
# and `stage` has the most up-to-date changes.
WORKDIR /home/safeuser/ipfs-service-provider
WORKDIR /home/safeuser/bch-dex
# For development: switch to unstable branch
RUN git checkout ct-unstable
@@ -63,10 +63,13 @@ RUN npm install
# Generate the API docs
RUN npm run docs
VOLUME /home/safeuser/keys
# Copy the wallet files
COPY wallet.json wallet.json
#VOLUME /home/safeuser/keys
# Expose the port the API will be served on.
EXPOSE 5010
#EXPOSE 5010
# Start the application.
COPY start-production.sh start-production.sh
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# BEGIN: Optional configuration settings
# The human readable name this IPFS node identifies as.
export COORD_NAME=bch-dex-generic
# Allow this node to function as a circuit relay. It must not be behind a firewall.
#export ENABLE_CIRCUIT_RELAY=true
# For browsers to use your circuit realy, you must set up a domain, SSL certificate,
# and you must forward that subdomain to the IPFS_WS_PORT.
#export CR_DOMAIN=subdomain.yourdomain.com
# Debug level. 0 = minimal info. 2 = max info.
export DEBUG_LEVEL=1
# END: Optional configuration settings
# Production database connection string.
export DBURL=mongodb://172.17.0.1:5666/bch-swap-service-prod
# Configure REST API port
export PORT=5700
# bch-dex specific env vars
export BCH_ENV=production
export WEBHOOKSERVICE=http://172.17.0.1:5667/webhook
export WEBHOOKTARGET=http://172.17.0.1:5700/p2wdb
export APP_ID=bch-dex-test557
npm start
+58 -13
View File
@@ -3,18 +3,18 @@
version: '3.9'
services:
mongo-ipfs-service:
image: mongo
container_name: mongo-ipfs-service
mongo-p2wdb-service:
image: mongo:4.4
container_name: mongo-p2wdb-service
ports:
- '5555:27017' # <host port>:<container port>
- '5666:27017' # <host port>:<container port>
volumes:
- ../data/database:/data/db
command: mongod --logpath=/dev/null # -- quiet
restart: always
ipfs:
image: ipfs/go-ipfs:v0.11.0
image: ipfs/go-ipfs:v0.12.0
container_name: ipfs
environment:
MY_ENV_VAR: 'placeholder'
@@ -42,9 +42,55 @@ services:
]
restart: always
ipfs-service:
build: .
container_name: ipfs-service
p2wdb:
build:
context: ./p2wdb/
dockerfile: Dockerfile
container_name: p2wdb
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 1gb
links:
- mongo-p2wdb-service
ports:
# <host port>:<container port>
- 5667:5667 # REST API
#- 5668:5668 # IPFS TCP port
#- 5669:5669 # IPFS WS Port
volumes:
- ../data/ipfsdata/p2wdb:/home/safeuser/ipfs-p2wdb-service/.ipfsdata/p2wdb
restart: always
bch-dex:
build:
context: ./bch-dex/
dockerfile: Dockerfile
container_name: bch-dex
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 1000mb
links:
- mongo-p2wdb-service
- p2wdb
ports:
- '5700:5700' # <host port>:<container port>
# volumes:
# - ../data/ipfsdata:/home/safeuser/ipfs-service-provider/.ipfsdata
restart: always
dex-ui:
build:
context: ./bch-dex-ui/
dockerfile: Dockerfile
container_name: dex-ui
environment:
SERVER: 'http://192.168.2.3'
logging:
driver: 'json-file'
options:
@@ -52,10 +98,9 @@ services:
max-file: '10'
mem_limit: 500mb
links:
- mongo-ipfs-service
- ipfs
- bch-dex
ports:
- '5010:5010' # <host port>:<container port>
volumes:
- ../data/ipfsdata:/home/safeuser/ipfs-service-provider/.ipfsdata
- '4500:80' # <host port>:<container port>
# volumes:
# - ../data/ipfsdata:/home/safeuser/ipfs-service-provider/.ipfsdata
restart: always
+71
View File
@@ -0,0 +1,71 @@
# Create a Docker container for the P2WDB
#
#IMAGE BUILD COMMANDS
FROM ubuntu:20.04
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
#Update the OS and install any OS packages needed.
RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
#Create the user 'safeuser' and add them to the sudo group.
RUN useradd -ms /bin/bash safeuser
RUN adduser safeuser sudo
#Set password to 'abcd8765' change value below if you want a different password
RUN echo safeuser:abcd8765 | chpasswd
#Set the working directory to be the users home directory
WORKDIR /home/safeuser
#Setup NPM for non-root global install (like on a mac)
RUN mkdir /home/safeuser/.npm-global
RUN chown -R safeuser .npm-global
RUN echo "export PATH=~/.npm-global/bin:$PATH" >> /home/safeuser/.profile
RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
# Update to the latest version of npm.
#RUN npm install -g npm@7.23.0
RUN npm install -g npm
# npm mirror to prevent direct dependency on npm.
RUN npm set registry http://94.130.170.209:4873/
# Switch to user account.
#USER safeuser
# Prep 'sudo' commands.
#RUN echo 'abcd8765' | sudo -S pwd
# Clone the rest.bitcoin.com repository
RUN git clone https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service
WORKDIR /home/safeuser/ipfs-p2wdb-service
RUN mkdir .ipfsdata
RUN git checkout ct-unstable
#RUN npm install fsevents
# Install dependencies
#RUN mkdir .ipfsdata
RUN npm install
# Generate the API docs
RUN npm run docs
# Expose the port the API will be served on.
#EXPOSE 5010
# Start the application.
COPY start-production.sh start-production.sh
CMD ["./start-production.sh"]
#CMD ["npm", "start"]
# Used for debugging
#COPY dummyapp.js dummyapp.js
#CMD ["node", "dummyapp.js"]
+4
View File
@@ -0,0 +1,4 @@
setInterval(function () {
const now = new Date()
console.log(`ping ${now.toLocaleString()}`)
}, 10000)
@@ -4,11 +4,10 @@
# This mnemonic is used to set up persistent public key for e2ee
# Replace this with your own 12-word mnemonic.
# You can get one at https://wallet.fullstack.cash.
export MNEMONIC="olive two muscle bottom coral ancient wait legend bronze useful process session"
export MNEMONIC="mass response fiscal world message exact series swallow forward confirm canoe festival"
# The human readable name this IPFS node identifies as.
export COORD_NAME=ipfs-service-provider-generic
export COORD_NAME=generic-p2wdb-production
# Allow this node to function as a circuit relay. It must not be behind a firewall.
#export ENABLE_CIRCUIT_RELAY=true
@@ -19,20 +18,29 @@ export COORD_NAME=ipfs-service-provider-generic
# Debug level. 0 = minimal info. 2 = max info.
export DEBUG_LEVEL=2
# Log-in information for retrieving a JWT token from FullStack.cash.
export FULLSTACKLOGIN=demo@demo.com
export FULLSTACKPASS=demo
# END: Optional configuration settings
# Production database connection string.
export DBURL=mongodb://172.17.0.1:5555/ipfs-service-prod
export DBURL=mongodb://172.17.0.1:5666/p2wdb-service-dev
# Configure IPFS ports
export IPFS_TCP_PORT=5668
export IPFS_WS_PORT=5669
# Configure REST API port
export PORT=5010
export PORT=5667
# Production settings using external go-ipfs node.
export SVC_ENV=production
export P2W_ENV=production
export IPFS_HOST=172.17.0.1
export IPFS_API_PORT=5001
export IPFS_TCP_PORT=4001
#export IPFS_WS_PORT=5269
# P2WDB specific env vars
export ORBITDB_NAME=/orbitdb/zdpuAm4fPafpjs5mgbBUJV8Az7kd8Xj1ttD6M1JaAxF8RMRrw/psf-bch-p2wdb-keyvalue-v1.0.0-0004
npm start
@@ -0,0 +1,73 @@
# Create a Dockerized API server
#
#IMAGE BUILD COMMANDS
# ct-base-ubuntu = ubuntu 18.04 + nodejs v10 LTS
#FROM christroutner/ct-base-ubuntu
FROM ubuntu:20.04 as builder
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
#Update the OS and install any OS packages needed.
RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
#Create the user 'safeuser' and add them to the sudo group.
#RUN useradd -ms /bin/bash safeuser
#RUN adduser safeuser sudo
#Set password to 'password' change value below if you want a different password
#RUN echo safeuser:password | chpasswd
#Set the working directory to be the home directory
WORKDIR /home/safeuser
#Setup NPM for non-root global install
#RUN mkdir /home/safeuser/.npm-global
#RUN chown -R safeuser .npm-global
#RUN echo "export PATH=~/.npm-global/bin:$PATH" >> /home/safeuser/.profile
#RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
# Update to the latest version of npm.
#RUN npm install -g npm@7.23.0
RUN npm install -g npm
# npm mirror to prevent direct dependency on npm.
RUN npm set registry http://94.130.170.209:4873/
# Switch to user account.
#USER safeuser
# Prep 'sudo' commands.
#RUN echo 'abcd8765' | sudo -S pwd
# Clone the rest.bitcoin.com repository
WORKDIR /home/safeuser
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex-ui
# Switch to the desired branch. `master` is usually stable,
# and `stage` has the most up-to-date changes.
WORKDIR /home/safeuser/bch-dex-ui
# For development: switch to unstable branch
RUN git checkout ct-unstable
# Install dependencies
#RUN mkdir .ipfsdata
#RUN npm install -g @mapbox/node-pre-gyp
RUN npm install
# Build the site
RUN CI=true npm run build
# Load the NGINX image.
FROM nginx
EXPOSE 80
# Copy the files built in the first container to the new NGINX container.
COPY --from=builder /home/safeuser/bch-dex-ui/public /usr/share/nginx/html
#USER safeuser
+78
View File
@@ -0,0 +1,78 @@
# Create a Dockerized API server
#
#IMAGE BUILD COMMANDS
# ct-base-ubuntu = ubuntu 18.04 + nodejs v10 LTS
#FROM christroutner/ct-base-ubuntu
FROM ubuntu:20.04
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
#Update the OS and install any OS packages needed.
RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
#Create the user 'safeuser' and add them to the sudo group.
#RUN useradd -ms /bin/bash safeuser
#RUN adduser safeuser sudo
#Set password to 'password' change value below if you want a different password
#RUN echo safeuser:password | chpasswd
#Set the working directory to be the home directory
WORKDIR /home/safeuser
#Setup NPM for non-root global install
#RUN mkdir /home/safeuser/.npm-global
#RUN chown -R safeuser .npm-global
#RUN echo "export PATH=~/.npm-global/bin:$PATH" >> /home/safeuser/.profile
#RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
# Update to the latest version of npm.
#RUN npm install -g npm@7.23.0
RUN npm install -g npm
# npm mirror to prevent direct dependency on npm.
RUN npm set registry http://94.130.170.209:4873/
# Switch to user account.
#USER safeuser
# Prep 'sudo' commands.
#RUN echo 'abcd8765' | sudo -S pwd
# Clone the rest.bitcoin.com repository
WORKDIR /home/safeuser
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex
# Switch to the desired branch. `master` is usually stable,
# and `stage` has the most up-to-date changes.
WORKDIR /home/safeuser/bch-dex
# For development: switch to unstable branch
RUN git checkout ct-unstable
# Install dependencies
#RUN mkdir .ipfsdata
#RUN npm install -g @mapbox/node-pre-gyp
RUN npm install
# Generate the API docs
RUN npm run docs
# Copy the wallet files
COPY wallet.json wallet.json
#VOLUME /home/safeuser/keys
# Expose the port the API will be served on.
#EXPOSE 5010
# Start the application.
COPY start-production.sh start-production.sh
CMD ["./start-production.sh"]
#CMD ["npm", "start"]
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# BEGIN: Optional configuration settings
# The human readable name this IPFS node identifies as.
export COORD_NAME=bch-dex-generic
# Allow this node to function as a circuit relay. It must not be behind a firewall.
#export ENABLE_CIRCUIT_RELAY=true
# For browsers to use your circuit realy, you must set up a domain, SSL certificate,
# and you must forward that subdomain to the IPFS_WS_PORT.
#export CR_DOMAIN=subdomain.yourdomain.com
# Debug level. 0 = minimal info. 2 = max info.
export DEBUG_LEVEL=1
# END: Optional configuration settings
# Production database connection string.
export DBURL=mongodb://172.17.0.1:5666/bch-swap-service-prod
# Configure REST API port
export PORT=5700
# bch-dex specific env vars
export BCH_ENV=production
export WEBHOOKSERVICE=http://172.17.0.1:5667/webhook
export WEBHOOKTARGET=http://172.17.0.1:5700/p2wdb
export APP_ID=bch-dex-test557
npm start
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
# Remove all untagged docker images.
docker rmi $(docker images | grep "^<none>" | awk '{print $3}')
+105
View File
@@ -0,0 +1,105 @@
# Start the service with the command 'docker-compose up -d'
version: '3.9'
services:
mongo-p2wdb-service:
image: mongo:4.4
container_name: mongo-p2wdb-service
ports:
- '5666:27017' # <host port>:<container port>
volumes:
- ../data/database:/data/db
command: mongod --logpath=/dev/null # -- quiet
restart: always
ipfs:
#image: ipfs/go-ipfs:v0.12.0
image: odanado/go-ipfs:v0.11.0
container_name: ipfs
environment:
MY_ENV_VAR: 'placeholder'
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 2000mb
ports:
- 4001:4001
- 172.17.0.1:5001:5001
- 172.17.0.1:8080:8080
volumes:
- ../data/go-ipfs/data:/data/ipfs
- ../data/go-ipfs/export:/export
# https://docs.docker.com/compose/compose-file/compose-file-v3/#command
# https://github.com/ipfs/go-ipfs/blob/91c52657166bcf86f2476926e4fe56694dc26562/Dockerfile#L115
command:
[
'daemon',
'--migrate=true',
'--agent-version-suffix=docker',
'--enable-pubsub-experiment'
]
restart: always
p2wdb:
build:
context: ./p2wdb/
dockerfile: Dockerfile
container_name: p2wdb
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 1gb
links:
- mongo-p2wdb-service
ports:
# <host port>:<container port>
- 5667:5667 # REST API
#- 5668:5668 # IPFS TCP port
#- 5669:5669 # IPFS WS Port
volumes:
- ../data/ipfsdata/p2wdb:/home/safeuser/ipfs-p2wdb-service/.ipfsdata/p2wdb
restart: always
bch-dex:
build:
context: ./bch-dex/
dockerfile: Dockerfile
container_name: bch-dex
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 1000mb
links:
- mongo-p2wdb-service
- p2wdb
ports:
- '5700:5700' # <host port>:<container port>
# volumes:
# - ../data/ipfsdata:/home/safeuser/ipfs-service-provider/.ipfsdata
restart: always
dex-ui:
build:
context: ./bch-dex-ui/
dockerfile: Dockerfile
container_name: dex-ui
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
mem_limit: 500mb
links:
- bch-dex
ports:
- '4500:80' # <host port>:<container port>
# volumes:
# - ../data/ipfsdata:/home/safeuser/ipfs-service-provider/.ipfsdata
restart: always
+71
View File
@@ -0,0 +1,71 @@
# Create a Docker container for the P2WDB
#
#IMAGE BUILD COMMANDS
FROM ubuntu:20.04
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
#Update the OS and install any OS packages needed.
RUN apt-get update
RUN apt-get install -y sudo git curl nano gnupg wget
#Install Node and NPM
RUN curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt-get install -y nodejs build-essential
#Create the user 'safeuser' and add them to the sudo group.
RUN useradd -ms /bin/bash safeuser
RUN adduser safeuser sudo
#Set password to 'abcd8765' change value below if you want a different password
RUN echo safeuser:abcd8765 | chpasswd
#Set the working directory to be the users home directory
WORKDIR /home/safeuser
#Setup NPM for non-root global install (like on a mac)
RUN mkdir /home/safeuser/.npm-global
RUN chown -R safeuser .npm-global
RUN echo "export PATH=~/.npm-global/bin:$PATH" >> /home/safeuser/.profile
RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
# Update to the latest version of npm.
#RUN npm install -g npm@7.23.0
RUN npm install -g npm
# npm mirror to prevent direct dependency on npm.
RUN npm set registry http://94.130.170.209:4873/
# Switch to user account.
#USER safeuser
# Prep 'sudo' commands.
#RUN echo 'abcd8765' | sudo -S pwd
# Clone the rest.bitcoin.com repository
RUN git clone https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service
WORKDIR /home/safeuser/ipfs-p2wdb-service
RUN mkdir .ipfsdata
RUN git checkout ct-unstable
#RUN npm install fsevents
# Install dependencies
#RUN mkdir .ipfsdata
RUN npm install
# Generate the API docs
RUN npm run docs
# Expose the port the API will be served on.
#EXPOSE 5010
# Start the application.
COPY start-production.sh start-production.sh
CMD ["./start-production.sh"]
#CMD ["npm", "start"]
# Used for debugging
#COPY dummyapp.js dummyapp.js
#CMD ["node", "dummyapp.js"]
+4
View File
@@ -0,0 +1,4 @@
setInterval(function () {
const now = new Date()
console.log(`ping ${now.toLocaleString()}`)
}, 10000)
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# BEGIN: Optional configuration settings
# This mnemonic is used to set up persistent public key for e2ee
# Replace this with your own 12-word mnemonic.
export MNEMONIC="mass response fiscal world message exact series swallow forward confirm canoe festival"
# The human readable name this IPFS node identifies as.
export COORD_NAME=generic-p2wdb-production
# Allow this node to function as a circuit relay. It must not be behind a firewall.
#export ENABLE_CIRCUIT_RELAY=true
# For browsers to use your circuit realy, you must set up a domain, SSL certificate,
# and you must forward that subdomain to the IPFS_WS_PORT.
#export CR_DOMAIN=subdomain.yourdomain.com
# Debug level. 0 = minimal info. 2 = max info.
export DEBUG_LEVEL=2
# Log-in information for retrieving a JWT token from FullStack.cash.
export FULLSTACKLOGIN=demo@demo.com
export FULLSTACKPASS=demo
# END: Optional configuration settings
# Production database connection string.
export DBURL=mongodb://172.17.0.1:5666/p2wdb-service-dev
# Configure IPFS ports
export IPFS_TCP_PORT=5668
export IPFS_WS_PORT=5669
# Configure REST API port
export PORT=5667
export P2W_ENV=production
export IPFS_HOST=172.17.0.1
export IPFS_API_PORT=5001
export IPFS_TCP_PORT=4001
# P2WDB specific env vars
export ORBITDB_NAME=/orbitdb/zdpuAm4fPafpjs5mgbBUJV8Az7kd8Xj1ttD6M1JaAxF8RMRrw/psf-bch-p2wdb-keyvalue-v1.0.0-0004
npm start
+40
View File
@@ -0,0 +1,40 @@
/*
This script can be used to generate new Orders and Offers, until the UI for
that is built.
Customize the settings below to add your own Order. The token must exist in
the DEX app wallet in order to be acceped.
*/
const axios = require('axios')
const LOCALHOST = 'http://localhost:5700'
// const LOCALHOST = 'http://172.17.0.1:5700'
async function start () {
try {
const mockOrder = {
lokadId: 'SWP',
messageType: 1,
messageClass: 1,
tokenId:
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
buyOrSell: 'sell',
rateInBaseUnit: 5000,
minUnitsToExchange: 5000,
numTokens: 2
}
const options = {
method: 'post',
url: `${LOCALHOST}/order`,
data: { order: mockOrder }
}
const result = await axios(options)
console.log('result.data: ', result.data)
} catch (err) {
console.log(err)
}
}
start()
+32
View File
@@ -0,0 +1,32 @@
/*
Generate a wallet.json file for use with the DEX.
*/
// Public NPM libraries
const BchWallet = require('minimal-slp-wallet/index')
const fs = require('fs').promises
async function createWallet () {
try {
// Configure the minimal-slp-wallet library to use the JSON RPC over IPFS.
const advancedConfig = {
interface: 'consumer-api',
noUpdate: true
}
// Wait for the wallet to be created.
this.bchWallet = new BchWallet(undefined, advancedConfig)
await this.bchWallet.walletInfoPromise
const walletData = this.bchWallet.walletInfo
walletData.nextAddress = 1
// Save the wallet file to disk.
await fs.writeFile('wallet.json', JSON.stringify(walletData, null, 2))
console.log('Generated wallet.json. Copy this file to the docker/bch-dex folder to be used inside the Docker container.')
console.log(`${JSON.stringify(walletData, null, 2)}`)
} catch (err) {
console.error('Error: ', err)
}
}
createWallet()
+18 -18
View File
@@ -102,9 +102,9 @@ class IpfsAdapter {
console.error('Error in ipfs.js/start()')
// If IPFS crashes because the /blocks directory is full, wipe the directory.
if (err.message.includes('No space left on device')) {
this.rmBlocksDir()
}
// if (err.message.includes('No space left on device')) {
// this.rmBlocksDir()
// }
throw err
}
@@ -120,21 +120,21 @@ class IpfsAdapter {
// Dev Note: It's assumed this node is not pinning any data and that
// everything in this directory is transient. This folder will regularly
// fill up and prevent IPFS from starting.
rmBlocksDir () {
try {
const dir = `${IPFS_DIR}/blocks`
console.log(`Deleting ${dir} directory...`)
this.fs.rmdirSync(dir, { recursive: true })
console.log(`${dir} directory is deleted!`)
return true // Signal successful execution.
} catch (err) {
console.log('Error in rmBlocksDir()')
throw err
}
}
// rmBlocksDir () {
// try {
// const dir = `${IPFS_DIR}/blocks`
// console.log(`Deleting ${dir} directory...`)
//
// this.fs.rmdirSync(dir, { recursive: true })
//
// console.log(`${dir} directory is deleted!`)
//
// return true // Signal successful execution.
// } catch (err) {
// console.log('Error in rmBlocksDir()')
// throw err
// }
// }
}
module.exports = IpfsAdapter
+1
View File
@@ -6,6 +6,7 @@ const Offer = new mongoose.Schema({
tokenId: { type: String },
utxoTxid: { type: String },
utxoVout: { type: Number },
ticker: { type: String },
// Trade data
buyOrSell: { type: String },
+1
View File
@@ -13,6 +13,7 @@ const Order = new mongoose.Schema({
tokenId: { type: String },
utxoTxid: { type: String },
utxoVout: { type: Number },
ticker: { type: String },
// Trade data
buyOrSell: { type: String },
+8 -2
View File
@@ -38,7 +38,7 @@ class WalletAdapter {
walletData = await this.jsonFiles.readJSON(this.WALLET_FILE)
} catch (err) {
// Create a new wallet file if one does not already exist.
console.warn('Wallet file not found. Creating new wallet.json file.')
console.log('Wallet file not found. Creating new wallet.json file.')
// Create a new wallet.
// No-Update flag creates wallet without making any network calls.
@@ -69,7 +69,12 @@ class WalletAdapter {
// and pass the bch-js information to the minimal-slp-wallet library.
async instanceWallet (walletData) {
try {
// console.log(`instanceWallet() walletData: ${JSON.stringify(walletData, null, 2)}`)
// TODO: throw error if wallet data is not passed in.
if (!walletData.mnemonic) {
throw new Error('Wallet data is not formatted correctly. Can not read mnemonic in wallet file!')
}
const advancedConfig = {}
if (this.config.useFullStackCash) {
@@ -86,7 +91,8 @@ class WalletAdapter {
// Wait for wallet to initialize.
await this.bchWallet.walletInfoPromise
console.log('BCH wallet initialized.')
console.log(`BCH wallet initialized. Wallet address: ${this.bchWallet.walletInfo.cashAddress}`)
// console.log(`this.bchWallet.walletInfo: ${JSON.stringify(this.bchWallet.walletInfo, null, 2)}`)
return this.bchWallet
} catch (err) {
+2 -1
View File
@@ -49,7 +49,8 @@ class Wlogger {
}
notifyRotation (oldFilename, newFilename) {
this.wlogger.info('Rotating log files')
// this.wlogger.info('Rotating log files')
console.log('Rotating log files')
}
outputToConsole () {
+3 -8
View File
@@ -6,18 +6,12 @@
// Public npm libraries.
// Load the Clean Architecture Adapters library
// Local libraries
const Adapters = require('../adapters')
// Load the JSON RPC Controller.
const JSONRPC = require('./json-rpc')
// Load the Clean Architecture Use Case libraries.
const UseCases = require('../use-cases')
// const useCases = new UseCases({ adapters })
// Load the REST API Controllers.
const RESTControllers = require('./rest-api')
const TimerControllers = require('./timer-controllers')
class Controllers {
constructor (localConfig = {}) {
@@ -33,6 +27,7 @@ class Controllers {
// this.attachRESTControllers(app)
// this.attachRPCControllers()
this.timerControllers = new TimerControllers({ adapters: this.adapters, useCases: this.useCases })
}
// Top-level function for this library.
+59
View File
@@ -0,0 +1,59 @@
/*
This Controller library is concerned with timer-based functions that are
kicked off periodicially.
*/
// Used to retain scope of 'this', when the scope is lost.
let _this
class TimerControllers {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Timer Controller libraries.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Timer Controller libraries.'
)
}
this.debugLevel = localConfig.debugLevel
_this = this
this.startTimers()
}
// Start all the time-based controllers.
startTimers () {
setInterval(this.gcOrders, 60000 * 5)
setInterval(this.gcOffers, 60000 * 5)
}
// Garbage Collect the Orders.
gcOrders () {
try {
_this.useCases.order.removeStaleOrders()
} catch (err) {
// Do not throw an error. This is a top-level function.
console.log('Error in timer-controllers.js/gcOrders(): ', err)
}
}
// Garbage Collect the Offers.
gcOffers () {
try {
_this.useCases.offer.removeStaleOffers()
} catch (err) {
// Do not throw an error. This is a top-level function.
console.log('Error in timer-controllers.js/gcOffers(): ', err)
}
}
}
module.exports = TimerControllers
+7 -2
View File
@@ -28,7 +28,8 @@ class OfferEntity {
utxoTxid,
utxoVout,
offerStatus,
makerAddr
makerAddr,
ticker
} = offerData.data
// Input Validation
@@ -65,6 +66,9 @@ class OfferEntity {
if (!makerAddr || typeof makerAddr !== 'string') {
throw new Error("Property 'makerAddr' must be a string.")
}
if (!ticker || typeof ticker !== 'string') {
throw new Error("Property 'ticker' must be a string.")
}
const validatedOfferData = {
messageType,
@@ -81,7 +85,8 @@ class OfferEntity {
txid: offerData.txid,
p2wdbHash: offerData.hash,
offerStatus: offerStatus || this.offerStatus[0],
makerAddr
makerAddr,
ticker
}
return validatedOfferData
+7 -2
View File
@@ -16,7 +16,8 @@ class Order {
rateInBaseUnit,
minUnitsToExchange,
numTokens,
makerAddr
makerAddr,
ticker
} = data
// Input Validation
@@ -44,6 +45,9 @@ class Order {
if (!makerAddr || typeof makerAddr !== 'string') {
throw new Error("Property 'makerAddr' must be a string.")
}
if (!ticker || typeof ticker !== 'string') {
throw new Error("Property 'ticker' must be a string.")
}
const offerData = {
messageType,
@@ -53,7 +57,8 @@ class Order {
rateInBaseUnit,
minUnitsToExchange,
numTokens,
makerAddr
makerAddr,
ticker
}
return offerData
+96 -22
View File
@@ -29,7 +29,7 @@ class OfferUseCases {
this.orderUseCase = localConfig.order
if (!this.orderUseCase) {
throw new Error(
'Instance of Order Use Cases must be passed in when instantiating Offer Use Cases library.'
'Instance of Offer Use Cases must be passed in when instantiating Offer Use Cases library.'
)
}
@@ -46,8 +46,23 @@ class OfferUseCases {
try {
console.log('Use Case createOffer(offerObj): ', offerObj)
// Return if Offer already exists in database with the same P2WDB CID.
try {
await this.findOfferByHash(offerObj.hash)
console.log('Offer already found in local database.')
return false
} catch (err) { /* exit quietly */ }
// console.log('this.adapters.bchjs: ', this.adapters.bchjs)
// Input Validation
// TODO: This is a hack. Find a better way to protect against the corner-
// case of counter-offers getting routed here.
if (offerObj.data.dataType === 'counter-offer') {
console.log('WARN: Counter Offer innappropriately routed to createOffer()')
}
// Verify that UTXO in offer is unspent. If it is spent, then ignore the
// offer.
const txid = offerObj.data.utxoTxid
@@ -223,31 +238,37 @@ class OfferUseCases {
return true
} catch (err) {
console.error('Error in ensureFunds()')
console.error('Error in offer/index.js/ensureFunds()')
// Debugging
try {
console.error(`Error with this address: ${this.adapters.wallet.bchWallet.walletInfo.cashAddress}`)
} catch (err) { /* exit quietly */ }
throw err
}
}
async findOfferByHash (p2wdbHash) {
try {
if (typeof p2wdbHash !== 'string' || !p2wdbHash) {
throw new Error('p2wdbHash must be a string')
}
const offer = await this.OfferModel.findOne({ p2wdbHash })
if (!offer) {
throw new Error('offer not found')
}
const offerObject = offer.toObject()
// return this.offerEntity.validateFromModel(offerObject)
return offerObject
} catch (err) {
console.error('Error in findOffer(): ', err)
throw err
// try {
if (typeof p2wdbHash !== 'string' || !p2wdbHash) {
throw new Error('p2wdbHash must be a string')
}
const offer = await this.OfferModel.findOne({ p2wdbHash })
if (!offer) {
throw new Error('offer not found')
}
const offerObject = offer.toObject()
// return this.offerEntity.validateFromModel(offerObject)
return offerObject
// } catch (err) {
// // console.error('Error in findOffer(): ', err)
// throw err
// }
}
// This function is called by the P2WDB webhook REST API handler. When a
@@ -261,8 +282,14 @@ class OfferUseCases {
// See if this instance of bch-dex is managing the Order associated with
// the incoming Counter Offer.
const orderHash = p2wdbData.data.offerHash
const orderData = await this.orderUseCase.findOrderByHash(orderHash)
console.log(`orderData: ${JSON.stringify(orderData, null, 2)}`)
let orderData = {}
try {
orderData = await this.orderUseCase.findOrderByHash(orderHash)
console.log(`orderData: ${JSON.stringify(orderData, null, 2)}`)
} catch (err) {
console.log('Order matching this Counter Offer is not managed by this instance of bch-dex. Exiting.')
return 'N/A'
}
// Deserialize the partially signed transaction.
const txHex = p2wdbData.data.partialTxHex
@@ -299,6 +326,53 @@ class OfferUseCases {
throw err
}
}
// This function is called by the garbage collection timer controller. It
// checks the UTXO associated with each Offer in the database. If the UTXO
// has been spent, the Offer is deleted from the database.
async removeStaleOffers () {
try {
const now = new Date()
console.log(`Starting garbage collection for Offers at ${now.toLocaleString()}`)
// Get all Offers in the database.
const offers = await this.OfferModel.find({})
// console.log('offers: ', offers)
// Loop through each Offer and ensure the UTXO is still valid.
for (let i = 0; i < offers.length; i++) {
const thisOffer = offers[i]
let utxoStatus = null
try {
// Get the status of the UTXO associate with this Offer.
utxoStatus = await this.adapters.bchjs.Blockchain.getTxOut(
thisOffer.utxoTxid,
thisOffer.utxoVout
)
// console.log('utxoStatus: ', utxoStatus)
} catch (err) {
// Handle corner case of bad-data in the Offer model.
if (err.message.includes('txid needs to be a proper transaction ID')) {
console.log(`Deleting Offer with bad data: ${JSON.stringify(thisOffer, null, 2)}`)
await thisOffer.remove()
continue
} else {
throw err
}
}
// If the Offer UTXO is spent, delete the Offer model.
if (utxoStatus === null) {
console.log(`Spent UTXO detected. Deleting this Offer: ${JSON.stringify(thisOffer, null, 2)}`)
await thisOffer.remove()
}
}
} catch (err) {
console.error('Error in removeStaleOffers()')
throw err
}
}
}
module.exports = OfferUseCases
+61 -1
View File
@@ -28,12 +28,22 @@ class OrderLib {
async createOrder (entryObj) {
try {
console.log('createOrder(entryObj): ', entryObj)
// if (!entryObj) return
// Specify the address to send payment.
entryObj.makerAddr = this.adapters.wallet.bchWallet.walletInfo.cashAddress
console.log('entryObj.makerAddr: ', entryObj.makerAddr)
// Get Ticker for token ID.
// TODO: Move this below the orderEntity.validate() call.
const tokenData = await this.adapters.wallet.bchWallet.getTxData([entryObj.tokenId])
// console.log(`tokenData: ${JSON.stringify(tokenData, null, 2)}`)
entryObj.ticker = tokenData[0].tokenTicker
// Input Validation
// TODO: Remove ticker from validation.
// TODO: Rename validate() to inputValidate(). Create fullValidate() that
// validates a fully hydrated Order entity.
const orderEntity = this.orderEntity.validate(entryObj)
console.log('orderEntity: ', orderEntity)
@@ -91,6 +101,9 @@ class OrderLib {
// console.log('this.adapters.wallet: ', this.adapters.wallet.bchWallet)
// console.log(`walletInfo: ${JSON.stringify(this.adapters.wallet.bchWallet.walletInfo, null, 2)}`)
// Update the wallet balance
await this.adapters.wallet.bchWallet.getUtxos()
// Ensure the app wallet has enough funds to write to the P2WDB.
const wif = this.adapters.wallet.bchWallet.walletInfo.privateKey
const canWriteToP2WDB = await this.adapters.p2wdb.checkForSufficientFunds(wif)
@@ -154,7 +167,54 @@ class OrderLib {
return orderObject
} catch (err) {
console.error('Error in findOrder(): ', err)
console.error('Error in findOrder()')
throw err
}
}
// This function is called by the garbage collection timer controller. It
// checks the UTXO associated with each Order in the database. If the UTXO
// has been spent, the Order is deleted from the database.
async removeStaleOrders () {
try {
const now = new Date()
console.log(`Starting garbage collection for Orders at ${now.toLocaleString()}`)
// Get all Orders in the database.
const orders = await this.OrderModel.find({})
// console.log('orders: ', orders)
// Loop through each Order and ensure the UTXO is still valid.
for (let i = 0; i < orders.length; i++) {
const thisOrder = orders[i]
let utxoStatus = null
try {
// Get the status of the UTXO associate with this Order.
utxoStatus = await this.adapters.bchjs.Blockchain.getTxOut(
thisOrder.utxoTxid,
thisOrder.utxoVout
)
// console.log('utxoStatus: ', utxoStatus)
} catch (err) {
// Handle corner case of bad-data in the Order model.
if (err.message.includes('txid needs to be a proper transaction ID')) {
console.log(`Deleting Order with bad data: ${JSON.stringify(thisOrder, null, 2)}`)
await thisOrder.remove()
continue
} else {
throw err
}
}
// If the Order UTXO is spent, delete the Order model.
if (utxoStatus === null) {
console.log(`Spent UTXO detected. Deleting this Order: ${JSON.stringify(thisOrder, null, 2)}`)
await thisOrder.remove()
}
}
} catch (err) {
console.error('Error in removeStaleOrders()')
throw err
}
}
+35 -2
View File
@@ -4,10 +4,11 @@
const assert = require('chai').assert
const sinon = require('sinon')
const IPFSLib = require('../../../src/adapters/ipfs/ipfs')
const IPFSMock = require('../mocks/ipfs-mock')
const config = require('../../../config')
// config.isProduction = true;
describe('#IPFS-adapter', () => {
let uut
let sandbox
@@ -18,7 +19,27 @@ describe('#IPFS-adapter', () => {
sandbox = sinon.createSandbox()
})
afterEach(() => sandbox.restore())
afterEach(() => {
sandbox.restore()
})
describe('#constructor', () => {
it('should instantiate IPFS Lib in dev mode.', async () => {
const _uut = new IPFSLib()
assert.exists(_uut)
assert.isFunction(_uut.start)
assert.isFunction(_uut.stop)
})
it('should instantiate dev IPFS Lib in production mode.', async () => {
config.isProduction = true
const _uut = new IPFSLib()
assert.exists(_uut)
assert.isFunction(_uut.start)
assert.isFunction(_uut.stop)
config.isProduction = false
})
})
describe('#start', () => {
it('should return a promise that resolves into an instance of IPFS.', async () => {
@@ -33,6 +54,18 @@ describe('#IPFS-adapter', () => {
assert.property(result, 'config')
})
it('should return a promise that resolves into an instance of IPFS in production mode.', async () => {
// Mock dependencies.
uut.IPFS = IPFSMock
uut.config.isProduction = true
const result = await uut.start()
// console.log('result: ', result)
assert.equal(uut.isReady, true)
assert.property(result, 'config')
})
it('should catch and throw an error', async () => {
try {
// Force an error
+14 -14
View File
@@ -99,20 +99,20 @@ describe('#wallet', () => {
})
describe('#instanceWallet', () => {
it('should create an instance of BchWallet', async () => {
// Mock dependencies
uut.BchWallet = MockBchWallet
// Ensure we open the test file, not the production wallet file.
uut.WALLET_FILE = testWalletFile
const walletData = await uut.openWallet()
const result = await uut.instanceWallet(walletData.mnemonic)
console.log('result: ', result)
assert.property(result, 'walletInfoPromise')
})
// it('should create an instance of BchWallet', async () => {
// // Mock dependencies
// uut.BchWallet = MockBchWallet
//
// // Ensure we open the test file, not the production wallet file.
// uut.WALLET_FILE = testWalletFile
//
// const walletData = await uut.openWallet()
//
// const result = await uut.instanceWallet(walletData.mnemonic)
// console.log('result: ', result)
//
// assert.property(result, 'walletInfoPromise')
// })
it('should catch and throw an error', async () => {
try {
+3 -1
View File
@@ -253,12 +253,14 @@ describe('#Offer-Entity', () => {
'241c06bf61384b8623477e419bf4779edbcc7e3bc862f0f179a9ed2967069b87',
utxoVout: 0,
offerStatus: 'posted',
makerAddr: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00'
makerAddr: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
ticker: 'TROUT'
},
timestamp: '2021-09-20T17:54:26.395Z',
localTimeStamp: '9/20/2021, 10:54:26 AM',
txid: '46f50f2a0cf44e3ed70dfb0618ef3ebfee57aabcf229b5d2d17c07322b54a8d7',
hash: 'zdpuB2X25AZCKo3wpr4sSbw44vqPWJRqcxWQRHZccK5BdtoGD'
}
const result = uut.validate(offerObj)
+5
View File
@@ -29,6 +29,11 @@ class MockBchWallet {
}
this.getUtxos = async () => {
}
this.getTxData = async () => {
return [{
tokenTicker: 'TROUT'
}]
}
// Environment variable is used by wallet-balance.unit.js to force an error.
if (process.env.NO_UTXO) {
+2 -1
View File
@@ -95,7 +95,8 @@ describe('#offer-use-case', () => {
utxoTxid:
'241c06bf61384b8623477e419bf4779edbcc7e3bc862f0f179a9ed2967069b87',
utxoVout: 0,
makerAddr: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00'
makerAddr: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
ticker: 'TROUT'
},
timestamp: '2021-09-20T17:54:26.395Z',
localTimeStamp: '9/20/2021, 10:54:26 AM',
+2 -3
View File
@@ -109,13 +109,12 @@ describe('#order-use-case', () => {
// Mock dependencies
// sandbox.stub(uut.adapters.wallet, 'burnPsf').resolves('fakeTxid')
// sandbox.stub(uut.adapters.wallet.bchWallet, 'getTxData').resolves({ tokenTicker: 'TROUT' })
sandbox.stub(uut.orderEntity, 'validate').returns(entryObj)
sandbox.stub(uut, 'ensureFunds').resolves()
sandbox.stub(uut.adapters.wallet.bchWallet.bchjs.Util, 'sleep').resolves()
sandbox.stub(uut.adapters.wallet, 'moveTokens').resolves({ txid: 'fakeTxid', vout: 0, hdIndex: 1 })
sandbox.stub(uut.adapters.wallet.bchWallet, 'getUtxos').resolves()
// sandbox
// .stub(uut.adapters.wallet, 'generateSignature')
// .resolves('fakeSignature')
sandbox.stub(uut.adapters.p2wdb, 'write').resolves('fakeHash')
const result = await uut.createOrder(entryObj)
+1 -1
View File
@@ -14,7 +14,7 @@ const BchTokenSweep = require('bch-token-sweep/index')
const WalletAdapter = require('../../src/adapters/wallet')
// Constants
const EMTPY_ADDR_CUTOFF = 5
const EMTPY_ADDR_CUTOFF = 15
async function sweepFunds () {
try {