mirror of
https://github.com/Permissionless-Software-Foundation/psf-bch-api.git
synced 2026-09-22 09:02:01 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95ae06fada | ||
|
|
188dc939b3 | ||
|
|
7d566beea3 | ||
|
|
6c42f47e15 | ||
|
|
d19a9e64cd | ||
|
|
7c96d72f7b | ||
|
|
7f1770ab70 | ||
|
|
b25f55ce6a | ||
|
|
6e32723b29 | ||
|
|
3b08fc3b62 | ||
|
|
2c1f02d6c7 | ||
|
|
6cf03ca0fe | ||
|
|
5ea7bc9c29 | ||
|
|
39021aba46 | ||
|
|
de34547951 | ||
|
|
b8f34fb40e | ||
|
|
3778894ce2 | ||
|
|
02eb8afd21 | ||
|
|
e708fc1228 | ||
|
|
fed4b2da59 | ||
|
|
f30c2ede04 | ||
|
|
09e05d51e5 | ||
|
|
22cbc54dee | ||
|
|
6fe0e01e8b | ||
|
|
f33b39ef01 | ||
|
|
6d27630393 | ||
|
|
eac4916415 | ||
|
|
baa1170b89 | ||
|
|
23ce276e19 | ||
|
|
f28e2c6a1a | ||
|
|
50a1a83a82 | ||
|
|
eb2dda6955 | ||
|
|
fe8d2ab051 | ||
|
|
66123de679 | ||
|
|
e2860d08b1 | ||
|
|
fa14af624f | ||
|
|
1eb787e0d4 | ||
|
|
ea815868ab | ||
|
|
d17e3aa2d8 | ||
|
|
1cd57a8bd7 | ||
|
|
50db4be890 | ||
|
|
908911fba6 | ||
|
|
f6726c79bf | ||
|
|
8b12938e6c | ||
|
|
d204f78fa4 | ||
|
|
58e831b22c | ||
|
|
6451736f26 | ||
|
|
571acbec59 | ||
|
|
394ab73276 | ||
|
|
ca0fcdd60a | ||
|
|
98576e5ff2 |
@@ -19,10 +19,13 @@ LOCAL_RESTURL=http://localhost:5942/v6
|
||||
|
||||
# START ACCESS CONTROL
|
||||
|
||||
PORT=5942
|
||||
|
||||
# x402 payments required to access this API?
|
||||
X402_ENABLED=true
|
||||
SERVER_BCH_ADDRESS=bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d
|
||||
FACILITATOR_URL=http://localhost:4345/facilitator
|
||||
X402_PRICE_SAT=200
|
||||
|
||||
# Basic Authentication required to access this API?
|
||||
USE_BASIC_AUTH=true
|
||||
@@ -1,30 +1,247 @@
|
||||
# psf-bch-api
|
||||
|
||||
This is a REST API for communicating with Bitcoin Cash infrastructure. It replaces [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api), and it implements [x402-bch protocol](https://github.com/x402-bch/x402-bch) to handle payments to access the API.
|
||||
[](https://github.com/Permissionless-Software-Foundation/psf-bch-api/blob/master/LICENSE.md)
|
||||
[](https://github.com/feross/standard)
|
||||
|
||||
This is a REST API server for communicating with Bitcoin Cash (BCH) blockchain infrastructure. It is written in node.js JavaScript using the [Express.js](https://expressjs.com/) framework and follows the [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) design pattern. It replaces the legacy [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api) and implements the [x402-bch protocol](https://github.com/x402-bch/x402-bch) for optional per-call payments.
|
||||
|
||||
psf-bch-api is the heart of the [Cash Stack](https://cashstack.info), a full software stack for building blockchain-based applications. It creates a single web2 REST API interface that abstracts away the complexity of the underlying blockchain infrastructure, so that application developers can interact with the blockchain through simple HTTP calls.
|
||||
|
||||

|
||||
|
||||
psf-bch-api depends on three pieces of back end infrastructure:
|
||||
|
||||
- **[BCHN Full Node](https://cashstack.info/docs/back-end/bchn-full-node)** - the base blockchain node that validates transactions and blocks.
|
||||
- **[Fulcrum Indexer](https://cashstack.info/docs/back-end/fulcrum-indexer)** - an address indexer that tracks balances, transaction histories, and UTXOs.
|
||||
- **[SLP Token Indexer](https://cashstack.info/docs/back-end/slp-indexer/slp-indexer-software)** - tracks all SLP tokens on the blockchain.
|
||||
|
||||
Front-end applications interact with psf-bch-api through libraries such as [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js) or [bch-consumer](https://www.npmjs.com/package/bch-consumer).
|
||||
|
||||
High-level documentation about the full Cash Stack is available at [CashStack.info](https://cashstack.info). Interactive API reference documentation is served by the running server at its root URL (e.g. `http://localhost:5942/`), and a live version can be found at [bch.fullstack.cash](https://bch.fullstack.cash/).
|
||||
|
||||
## The .env File
|
||||
|
||||
All runtime configuration is driven by a `.env` file in the project root. An example is provided at `.env-example`. To get started:
|
||||
|
||||
`cp .env-example .env`
|
||||
|
||||
Then edit `.env` to match your environment. The file is organized into two sections:
|
||||
|
||||
### Infrastructure Setup
|
||||
|
||||
These variables tell psf-bch-api where to find the back end services it depends on:
|
||||
|
||||
- `RPC_BASEURL` - URL of the BCHN full node JSON-RPC interface. Default: `http://127.0.0.1:8332`
|
||||
- `RPC_USERNAME` - RPC username for the full node.
|
||||
- `RPC_PASSWORD` - RPC password for the full node.
|
||||
- `FULCRUM_API` - URL of the Fulcrum indexer REST API.
|
||||
- `SLP_INDEXER_API` - URL of the SLP Token Indexer REST API.
|
||||
- `LOCAL_RESTURL` - The REST API URL used internally for wallet operations. Default: `http://127.0.0.1:5942/v6/`
|
||||
|
||||
### Access Control Settings
|
||||
|
||||
These variables control who can access the API and how they pay for it. The three access-control use cases are described in detail in the [Access Control](#access-control) section below.
|
||||
|
||||
- `PORT` - Port the server listens on. Default: `5942`
|
||||
- `X402_ENABLED` - Enable x402-bch per-call payment middleware. Default: `true`
|
||||
- `SERVER_BCH_ADDRESS` - BCH address that receives x402 payments. Default: `bitcoincash:qqsrke9lh257tqen99dkyy2emh4uty0vky9y0z0lsr`
|
||||
- `FACILITATOR_URL` - URL of the x402-bch facilitator service. Default: `http://localhost:4345/facilitator`
|
||||
- `X402_PRICE_SAT` - Price in satoshis charged per API call via x402. Default: `200`
|
||||
- `USE_BASIC_AUTH` - Enable Bearer token authentication middleware. Default: `false`
|
||||
- `BASIC_AUTH_TOKEN` - The expected Bearer token value.
|
||||
|
||||
## Access Control
|
||||
|
||||
psf-bch-api supports three major access-control configurations. Which one you choose depends on your deployment scenario. The behavior is controlled entirely by the `X402_ENABLED` and `USE_BASIC_AUTH` environment variables.
|
||||
|
||||
### 1. No Rate Limits (Open Access)
|
||||
|
||||
Set both access-control flags to `false`:
|
||||
|
||||
```
|
||||
X402_ENABLED=false
|
||||
USE_BASIC_AUTH=false
|
||||
```
|
||||
|
||||
All API endpoints are publicly accessible without any authentication or payment. This is the simplest configuration, ideal for **local development** or **private, trusted networks** where access control is handled at the network level (e.g. behind a firewall or VPN).
|
||||
|
||||
### 2. Bearer Token Authentication
|
||||
|
||||
Set `USE_BASIC_AUTH=true` and `X402_ENABLED=false`:
|
||||
|
||||
```
|
||||
X402_ENABLED=false
|
||||
USE_BASIC_AUTH=true
|
||||
BASIC_AUTH_TOKEN=my-secret-token
|
||||
```
|
||||
|
||||
Every API request (except `/health` and `/`) must include an `Authorization` header with a valid Bearer token:
|
||||
|
||||
```
|
||||
Authorization: Bearer my-secret-token
|
||||
```
|
||||
|
||||
Requests without a valid token receive an HTTP `401 Unauthorized` response. This is the best option when you want to **restrict access to a known set of users or services** (e.g. an organization's internal apps) without requiring cryptocurrency payments.
|
||||
|
||||
### 3. x402-bch Per-Call Payments
|
||||
|
||||
Set `X402_ENABLED=true`:
|
||||
|
||||
```
|
||||
X402_ENABLED=true
|
||||
SERVER_BCH_ADDRESS=bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d
|
||||
FACILITATOR_URL=http://localhost:4345/facilitator
|
||||
X402_PRICE_SAT=200
|
||||
```
|
||||
|
||||
Every API call under the `/v6` prefix requires a BCH micro-payment. When a request arrives without a valid `X-PAYMENT` header, the server responds with HTTP `402 Payment Required` and includes the payment details. Client libraries that support the x402-bch protocol (like [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js)) can handle payments automatically.
|
||||
|
||||
This is the right choice for **public, monetized APIs** where you want to charge per call.
|
||||
|
||||
#### Combined: x402 + Bearer Token
|
||||
|
||||
You can enable both at the same time:
|
||||
|
||||
```
|
||||
X402_ENABLED=true
|
||||
USE_BASIC_AUTH=true
|
||||
BASIC_AUTH_TOKEN=my-secret-token
|
||||
```
|
||||
|
||||
In this mode, requests that present a valid Bearer token bypass the x402 payment requirement. All other requests must pay. This allows you to give **free access to trusted clients** (via the Bearer token) while still **monetizing public access** via x402.
|
||||
|
||||
## Development
|
||||
|
||||
This is a standard node.js project. To set up a development environment:
|
||||
|
||||
1. Clone the repository:
|
||||
|
||||
`git clone https://github.com/Permissionless-Software-Foundation/psf-bch-api && cd psf-bch-api`
|
||||
|
||||
2. Install dependencies:
|
||||
|
||||
`npm install`
|
||||
|
||||
3. Create your configuration file:
|
||||
|
||||
`cp .env-example .env`
|
||||
|
||||
4. Edit `.env` to point to your back end infrastructure (full node, Fulcrum, SLP indexer). For local development you will likely want to disable access control:
|
||||
|
||||
```
|
||||
X402_ENABLED=false
|
||||
USE_BASIC_AUTH=false
|
||||
```
|
||||
|
||||
5. Start the server:
|
||||
|
||||
`npm start`
|
||||
|
||||
The server will start on port `5942` by default (or whatever you set in `PORT`). API documentation is available at `http://localhost:5942/`.
|
||||
|
||||
### Generating API Docs
|
||||
|
||||
The API reference documentation is generated by [apiDoc](https://apidocjs.com/) from inline annotations in the source code. To regenerate:
|
||||
|
||||
`npm run docs`
|
||||
|
||||
The output is written to the `docs/` directory and served by the running server at its root URL.
|
||||
|
||||
A live version can be found at [bch.fullstack.cash](https://bch.fullstack.cash/).
|
||||
|
||||
## Production (Docker)
|
||||
|
||||
A Docker setup is provided in the `production/docker/` directory for production deployments. The target OS is Ubuntu Linux.
|
||||
|
||||
1. Install [Docker and Docker Compose](https://docs.docker.com/engine/install/ubuntu/).
|
||||
|
||||
2. Navigate to the Docker directory:
|
||||
|
||||
`cd production/docker`
|
||||
|
||||
3. Create and configure the `.env` file. An example is provided:
|
||||
|
||||
`cp .env-example .env`
|
||||
|
||||
Edit `.env` to match your production infrastructure. Note that inside a Docker container, `localhost` refers to the container itself. Use `172.17.0.1` (the default Docker bridge gateway) to reach services running on the host machine:
|
||||
|
||||
```
|
||||
RPC_BASEURL=http://172.17.0.1:8332
|
||||
FULCRUM_API=http://172.17.0.1:3001/v1
|
||||
SLP_INDEXER_API=http://172.17.0.1:5010
|
||||
```
|
||||
|
||||
4. Build the Docker image:
|
||||
|
||||
`docker-compose build --no-cache`
|
||||
|
||||
5. Start the container:
|
||||
|
||||
`docker-compose up -d`
|
||||
|
||||
The container maps host port `5942` to container port `5942`. The `.env` file is mounted into the container as a volume, so you can update configuration without rebuilding.
|
||||
|
||||
To view logs:
|
||||
|
||||
`docker logs -f psf-bch-api`
|
||||
|
||||
To stop the container:
|
||||
|
||||
`docker-compose down`
|
||||
|
||||
A helper script `cleanup-images.sh` is provided to remove dangling Docker images after rebuilds.
|
||||
|
||||
## Testing
|
||||
|
||||
The project includes both unit tests and integration tests. Tests use [Mocha](https://mochajs.org/) as the test runner, [Chai](https://www.chaijs.com/) for assertions, and [Sinon](https://sinonjs.org/) for mocking. Code coverage is provided by [c8](https://github.com/bcoe/c8).
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Unit tests are located in `test/unit/` and cover adapters, controllers, and use cases. They do not require any running infrastructure. To run:
|
||||
|
||||
`npm test`
|
||||
|
||||
This will first lint the code with [Standard](https://standardjs.com/), then execute all unit tests with code coverage.
|
||||
|
||||
To generate an HTML coverage report:
|
||||
|
||||
`npm run coverage`
|
||||
|
||||
The report is written to the `coverage/` directory.
|
||||
|
||||
### Integration Tests
|
||||
|
||||
Integration tests are located in `test/integration/` and require the back end infrastructure (full node, Fulcrum, SLP indexer) to be running. To run:
|
||||
|
||||
`npm run test:integration`
|
||||
|
||||
Integration tests have a 25-second timeout per test to accommodate network calls.
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
All configuration values are read from environment variables (via the `.env` file). The complete list:
|
||||
|
||||
- `PORT` - Server listen port. Default: `5942`
|
||||
- `NODE_ENV` - Environment (`development` or `production`). Default: `development`
|
||||
- `API_PREFIX` - URL prefix for all REST endpoints. Default: `/v6`
|
||||
- `LOG_LEVEL` - Winston logging level. Default: `info`
|
||||
- `RPC_BASEURL` - Full node JSON-RPC URL. Default: `http://127.0.0.1:8332`
|
||||
- `RPC_USERNAME` - Full node RPC username.
|
||||
- `RPC_PASSWORD` - Full node RPC password.
|
||||
- `RPC_TIMEOUT_MS` - Full node RPC request timeout in ms. Default: `15000`
|
||||
- `FULCRUM_API` - Fulcrum indexer REST API URL.
|
||||
- `FULCRUM_TIMEOUT_MS` - Fulcrum API request timeout in ms. Default: `15000`
|
||||
- `SLP_INDEXER_API` - SLP Token Indexer REST API URL.
|
||||
- `SLP_INDEXER_TIMEOUT_MS` - SLP Indexer API request timeout in ms. Default: `15000`
|
||||
- `LOCAL_RESTURL` - Internal REST URL for wallet operations. Default: `http://127.0.0.1:5942/v6/`
|
||||
- `IPFS_GATEWAY` - IPFS gateway hostname. Default: `p2wdb-gateway-678.fullstack.cash`
|
||||
- `X402_ENABLED` - Enable x402-bch payment middleware. Default: `true`
|
||||
- `SERVER_BCH_ADDRESS` - BCH address for x402 payments. Default: `bitcoincash:qqsrke9lh257tqen99dkyy2emh4uty0vky9y0z0lsr`
|
||||
- `FACILITATOR_URL` - x402-bch facilitator service URL. Default: `http://localhost:4345/facilitator`
|
||||
- `X402_PRICE_SAT` - Satoshis charged per API call via x402. Default: `200`
|
||||
- `USE_BASIC_AUTH` - Enable Bearer token authentication. Default: `false`
|
||||
- `BASIC_AUTH_TOKEN` - Expected Bearer token value.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE.md)
|
||||
|
||||
## x402-bch Payments
|
||||
|
||||
All REST endpoints exposed under the `/v6` prefix are protected by the [`x402-bch-express`](https://www.npmjs.com/package/x402-bch-express) middleware. Each API call requires a BCH payment authorization for **2000 satoshis**. The middleware advertises payment requirements via HTTP 402 responses and validates incoming `X-PAYMENT` headers with a configured Facilitator.
|
||||
|
||||
### Configuration
|
||||
|
||||
Environment variables control the payment flow:
|
||||
|
||||
- `X402_ENABLED` — set to `false` (case-insensitive) to disable the middleware. Defaults to enabled.
|
||||
- `SERVER_BCH_ADDRESS` — BCH cash address that receives funding transactions. Defaults to `bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d`.
|
||||
- `FACILITATOR_URL` — Root URL of the facilitator service (e.g., `http://localhost:4345/facilitator`).
|
||||
- `X402_PRICE_SAT` — Optional; override the satoshi price per call (defaults to `2000`).
|
||||
|
||||
When `X402_ENABLED=false`, the server continues to operate without payment headers for local development or trusted deployments.
|
||||
|
||||
### Manual Verification
|
||||
|
||||
1. Start or point to an `x402-bch` facilitator service (the example facilitator listens at `http://localhost:4345/facilitator`).
|
||||
2. Run the API server with the default configuration: `npm start`.
|
||||
3. Call a protected endpoint without an `X-PAYMENT` header, e.g. `curl -i http://localhost:5942/v6/full-node/control/getNetworkInfo`. The server will respond with HTTP `402` and include payment requirements.
|
||||
4. Restart the server with `X402_ENABLED=false npm start` to confirm that the same request now bypasses the middleware (useful for local development without payments).
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
+32
-2
@@ -74,6 +74,19 @@ class Server {
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
|
||||
}))
|
||||
|
||||
// URL normalization middleware - collapse multiple slashes
|
||||
app.use((req, res, next) => {
|
||||
if (req.url && req.url.includes('//')) {
|
||||
// Split URL into path and query string
|
||||
const [path, queryString] = req.url.split('?')
|
||||
// Collapse multiple consecutive slashes into a single slash
|
||||
const normalizedPath = path.replace(/\/+/g, '/')
|
||||
// Reconstruct req.url with normalized path (req.path is read-only and will auto-update)
|
||||
req.url = queryString ? `${normalizedPath}?${queryString}` : normalizedPath
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
// Apply basic auth middleware if enabled
|
||||
// This must run before x402 middleware to set req.locals.basicAuthValid
|
||||
if (basicAuthSettings.enabled) {
|
||||
@@ -83,8 +96,10 @@ class Server {
|
||||
|
||||
// Apply x402 middleware based on configuration
|
||||
// Logic:
|
||||
// - If X402_ENABLED=false OR USE_BASIC_AUTH=false: Don't apply x402 (no rate limits)
|
||||
// - If X402_ENABLED=true AND USE_BASIC_AUTH=true: Apply x402 conditionally (bypass if basic auth valid)
|
||||
// - If X402_ENABLED=true AND USE_BASIC_AUTH=false: Apply x402 unconditionally (no basic auth bypass)
|
||||
// - If X402_ENABLED=false AND USE_BASIC_AUTH=true: Require basic auth only
|
||||
// - If X402_ENABLED=false AND USE_BASIC_AUTH=false: No access control
|
||||
|
||||
// Apply access control middleware based on configuration
|
||||
if (x402Settings.enabled && basicAuthSettings.enabled) {
|
||||
@@ -112,6 +127,21 @@ class Server {
|
||||
}
|
||||
|
||||
app.use(conditionalX402Middleware)
|
||||
} else if (x402Settings.enabled && !basicAuthSettings.enabled) {
|
||||
// X402_ENABLED=true AND USE_BASIC_AUTH=false: Apply x402 unconditionally (no basic auth bypass)
|
||||
const routes = buildX402Routes(this.config.apiPrefix)
|
||||
const facilitatorOptions = x402Settings.facilitatorUrl
|
||||
? { url: x402Settings.facilitatorUrl }
|
||||
: undefined
|
||||
|
||||
wlogger.info(`x402 middleware enabled (basic auth disabled); enforcing ${x402Settings.priceSat} satoshis per request`)
|
||||
|
||||
// Apply x402 middleware unconditionally - no basic auth bypass
|
||||
app.use(x402PaymentMiddleware(
|
||||
x402Settings.serverAddress,
|
||||
routes,
|
||||
facilitatorOptions
|
||||
))
|
||||
} else if (basicAuthSettings.enabled && !x402Settings.enabled) {
|
||||
// USE_BASIC_AUTH=true AND X402_ENABLED=false: Require basic auth, reject unauthenticated requests
|
||||
wlogger.info('Basic auth enforcement enabled (x402 disabled)')
|
||||
@@ -144,7 +174,7 @@ class Server {
|
||||
|
||||
// Endpoint logging middleware
|
||||
app.use((req, res, next) => {
|
||||
console.log(`Endpoint called: ${req.method} ${req.path}`)
|
||||
console.log(`Endpoint called: ${req.method} ${req.path} by ${req.ip}`)
|
||||
res.on('finish', () => {
|
||||
console.log(`Endpoint responded: ${req.method} ${req.path} - ${res.statusCode}`)
|
||||
})
|
||||
|
||||
Generated
+1226
-578
File diff suppressed because it is too large
Load Diff
+4
-4
@@ -15,17 +15,17 @@
|
||||
"license": "MIT",
|
||||
"description": "REST API proxy to Bitcoin Cash infrastructure",
|
||||
"dependencies": {
|
||||
"@psf/bch-js": "6.8.3",
|
||||
"@psf/bch-js": "7.1.11",
|
||||
"axios": "1.7.7",
|
||||
"cors": "2.8.5",
|
||||
"dotenv": "16.3.1",
|
||||
"express": "5.1.0",
|
||||
"minimal-slp-wallet": "5.13.3",
|
||||
"psffpp": "1.2.0",
|
||||
"minimal-slp-wallet": "7.1.4",
|
||||
"psffpp": "1.2.1",
|
||||
"slp-token-media": "1.2.10",
|
||||
"winston": "3.11.0",
|
||||
"winston-daily-rotate-file": "4.7.1",
|
||||
"x402-bch-express": "1.1.1"
|
||||
"x402-bch-express": "2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"apidoc": "1.2.0",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# START INFRASTRUCTURE SETUP
|
||||
|
||||
# Full Node Connection
|
||||
RPC_BASEURL=http://172.17.0.1:8332
|
||||
RPC_USERNAME=bitcoin
|
||||
RPC_PASSWORD=password
|
||||
|
||||
# Fulcrum Indexer
|
||||
FULCRUM_API=http://172.17.0.1:3001/v1
|
||||
|
||||
# SLP Indexer
|
||||
SLP_INDEXER_API=http://172.17.0.1:5010
|
||||
|
||||
# REST API URL for wallet operations
|
||||
LOCAL_RESTURL=http://172.17.0.1:5942/v6
|
||||
|
||||
# END INFRASTRUCTURE SETUP
|
||||
|
||||
|
||||
# START ACCESS CONTROL
|
||||
|
||||
PORT=5942
|
||||
|
||||
# x402 payments required to access this API?
|
||||
X402_ENABLED=false
|
||||
#X402_ENABLED=true
|
||||
#SERVER_BCH_ADDRESS=bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d
|
||||
#FACILITATOR_URL=http://localhost:4345/facilitator
|
||||
#X402_PRICE_SAT=200
|
||||
|
||||
# Basic Authentication required to access this API?
|
||||
USE_BASIC_AUTH=false
|
||||
#USE_BASIC_AUTH=true
|
||||
#BASIC_AUTH_TOKEN=some-random-token
|
||||
|
||||
# END ACCESS CONTROL
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
#
|
||||
|
||||
#IMAGE BUILD COMMANDS
|
||||
# ct-base-ubuntu = ubuntu 18.04 + nodejs v10 LTS
|
||||
#FROM christroutner/ct-base-ubuntu
|
||||
FROM ubuntu:22.04
|
||||
MAINTAINER Chris Troutner <chris.troutner@gmail.com>
|
||||
|
||||
@@ -47,39 +45,26 @@ RUN runuser -l safeuser -c "npm config set prefix '~/.npm-global'"
|
||||
|
||||
# Clone the rest.bitcoin.com repository
|
||||
WORKDIR /home/safeuser
|
||||
RUN git clone https://github.com/christroutner/REST2NOSTR
|
||||
RUN git clone https://github.com/Permissionless-Software-Foundation/psf-bch-api
|
||||
|
||||
# Switch to the desired branch. `master` is usually stable,
|
||||
# and `stage` has the most up-to-date changes.
|
||||
WORKDIR /home/safeuser/REST2NOSTR
|
||||
WORKDIR /home/safeuser/psf-bch-api
|
||||
|
||||
# For development: switch to unstable branch
|
||||
#RUN git checkout pin-ipfs
|
||||
RUN git checkout ct-unstable
|
||||
|
||||
# Install dependencies
|
||||
RUN npm install
|
||||
RUN npm install minimal-slp-wallet
|
||||
|
||||
# Generate the API docs
|
||||
RUN npm run docs
|
||||
|
||||
#VOLUME /home/safeuser/keys
|
||||
COPY .env .env
|
||||
|
||||
# Make leveldb folders
|
||||
#RUN mkdir leveldb
|
||||
#WORKDIR /home/safeuser/psf-slp-indexer/leveldb
|
||||
#RUN mkdir current
|
||||
#RUN mkdir zips
|
||||
#RUN mkdir backup
|
||||
#WORKDIR /home/safeuser/psf-slp-indexer/leveldb/zips
|
||||
#COPY restore-auto.sh restore-auto.sh
|
||||
#WORKDIR /home/safeuser/psf-slp-indexer
|
||||
|
||||
# Expose the port the API will be served on.
|
||||
#EXPOSE 5011
|
||||
CMD ["npm", "start"]
|
||||
|
||||
# Start the application.
|
||||
#COPY start-production.sh start-production.sh
|
||||
VOLUME start-rest2nostr.sh
|
||||
CMD ["./start-rest2nostr.sh"]
|
||||
|
||||
#CMD ["npm", "start"]
|
||||
# Used to debug the container.
|
||||
#COPY temp.js temp.js
|
||||
#CMD ["node", "temp.js"]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Start the service with the command 'docker-compose up -d'
|
||||
|
||||
services:
|
||||
rest2nostr:
|
||||
psf-bch-api:
|
||||
build: .
|
||||
container_name: rest2nostr
|
||||
container_name: psf-bch-api
|
||||
logging:
|
||||
driver: 'json-file'
|
||||
options:
|
||||
@@ -15,5 +15,6 @@ services:
|
||||
ports:
|
||||
- '5942:5942' # <host port>:<container port>
|
||||
volumes:
|
||||
- ./start-rest2nostr.sh:/home/safeuser/REST2NOSTR/start-rest2nostr.sh
|
||||
#- ./start-rest2nostr.sh:/home/safeuser/REST2NOSTR/start-rest2nostr.sh
|
||||
- ./.env:/home/safeuser/.env
|
||||
restart: always
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
npm start
|
||||
Vendored
+3
-3
@@ -26,10 +26,10 @@ const normalizeBoolean = (value, defaultValue) => {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// By default, the price per API call is 2000 satoshis.
|
||||
// By default, the price per API call is 200 satoshis.
|
||||
// But the user can override this value by setting the X402_PRICE_SAT environment variable.
|
||||
const parsedPriceSat = Number(process.env.X402_PRICE_SAT)
|
||||
const priceSat = Number.isFinite(parsedPriceSat) && parsedPriceSat > 0 ? parsedPriceSat : 2000
|
||||
const priceSat = Number.isFinite(parsedPriceSat) && parsedPriceSat > 0 ? parsedPriceSat : 200
|
||||
|
||||
const x402Defaults = {
|
||||
enabled: normalizeBoolean(process.env.X402_ENABLED, true),
|
||||
@@ -45,7 +45,7 @@ const basicAuthDefaults = {
|
||||
|
||||
export default {
|
||||
// Server port
|
||||
port: process.env.PORT || 5942,
|
||||
port: parseInt(process.env.PORT, 10) || 5942,
|
||||
|
||||
// Environment
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ export function buildX402Routes (apiPrefix = '/v6') {
|
||||
price: config.x402.priceSat,
|
||||
network: NETWORK,
|
||||
config: {
|
||||
description: `${DEFAULT_DESCRIPTION} (2000 satoshis)`,
|
||||
description: `${DEFAULT_DESCRIPTION} (${config.x402.priceSat} satoshis)`,
|
||||
maxTimeoutSeconds: DEFAULT_TIMEOUT_SECONDS
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
REST API Controller for the /encryption routes.
|
||||
*/
|
||||
|
||||
import wlogger from '../../../adapters/wlogger.js'
|
||||
|
||||
class EncryptionRESTController {
|
||||
constructor (localConfig = {}) {
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error(
|
||||
'Instance of Adapters library required when instantiating Encryption REST Controller.'
|
||||
)
|
||||
}
|
||||
|
||||
this.useCases = localConfig.useCases
|
||||
if (!this.useCases || !this.useCases.encryption) {
|
||||
throw new Error(
|
||||
'Instance of Encryption use cases required when instantiating Encryption REST Controller.'
|
||||
)
|
||||
}
|
||||
|
||||
this.encryptionUseCases = this.useCases.encryption
|
||||
|
||||
// Bind functions
|
||||
this.root = this.root.bind(this)
|
||||
this.getPublicKey = this.getPublicKey.bind(this)
|
||||
this.handleError = this.handleError.bind(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /v6/encryption/ Service status
|
||||
* @apiName EncryptionRoot
|
||||
* @apiGroup Encryption
|
||||
*
|
||||
* @apiDescription Returns the status of the encryption service.
|
||||
*
|
||||
* @apiSuccess {String} status Service identifier
|
||||
*/
|
||||
async root (req, res) {
|
||||
return res.status(200).json({ status: 'encryption' })
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /v6/encryption/publickey/:address Get public key for a BCH address
|
||||
* @apiName GetPublicKey
|
||||
* @apiGroup Encryption
|
||||
* @apiDescription Searches the blockchain for a public key associated with a
|
||||
* BCH address. Returns an object. If successful, the publicKey property will
|
||||
* contain a hexadecimal representation of the public key.
|
||||
*
|
||||
* @apiParam {String} address BCH address (cash address or legacy format)
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -X GET "https://api.fullstack.cash/v6/encryption/publickey/bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" -H "accept: application/json"
|
||||
*
|
||||
* @apiSuccess {Boolean} success Indicates if the operation was successful
|
||||
* @apiSuccess {String} publicKey The public key in hexadecimal format, or "not found"
|
||||
*/
|
||||
async getPublicKey (req, res) {
|
||||
try {
|
||||
const address = req.params.address
|
||||
|
||||
// Reject if address is an array
|
||||
if (Array.isArray(address)) {
|
||||
res.status(400)
|
||||
return res.json({
|
||||
success: false,
|
||||
error: 'address can not be an array.'
|
||||
})
|
||||
}
|
||||
|
||||
// Reject if address is missing
|
||||
if (!address) {
|
||||
res.status(400)
|
||||
return res.json({
|
||||
success: false,
|
||||
error: 'address is required.'
|
||||
})
|
||||
}
|
||||
|
||||
const result = await this.encryptionUseCases.getPublicKey({ address })
|
||||
|
||||
return res.status(200).json(result)
|
||||
} catch (err) {
|
||||
return this.handleError(err, res)
|
||||
}
|
||||
}
|
||||
|
||||
handleError (err, res) {
|
||||
wlogger.error('Error in EncryptionRESTController:', err)
|
||||
|
||||
const status = err.status || 500
|
||||
const message = err.message || 'Internal server error'
|
||||
|
||||
return res.status(status).json({ success: false, error: message })
|
||||
}
|
||||
}
|
||||
|
||||
export default EncryptionRESTController
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
REST API router for /encryption routes.
|
||||
*/
|
||||
|
||||
import express from 'express'
|
||||
import EncryptionRESTController from './controller.js'
|
||||
|
||||
class EncryptionRouter {
|
||||
constructor (localConfig = {}) {
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error(
|
||||
'Instance of Adapters library required when instantiating Encryption REST Router.'
|
||||
)
|
||||
}
|
||||
|
||||
this.useCases = localConfig.useCases
|
||||
if (!this.useCases) {
|
||||
throw new Error(
|
||||
'Instance of Use Cases library required when instantiating Encryption REST Router.'
|
||||
)
|
||||
}
|
||||
|
||||
const dependencies = {
|
||||
adapters: this.adapters,
|
||||
useCases: this.useCases
|
||||
}
|
||||
|
||||
this.encryptionController = new EncryptionRESTController(dependencies)
|
||||
|
||||
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
|
||||
this.baseUrl = `${this.apiPrefix}/encryption`
|
||||
if (!this.baseUrl.startsWith('/')) {
|
||||
this.baseUrl = `/${this.baseUrl}`
|
||||
}
|
||||
this.router = express.Router()
|
||||
}
|
||||
|
||||
attach (app) {
|
||||
if (!app) {
|
||||
throw new Error('Must pass app object when attaching REST API controllers.')
|
||||
}
|
||||
|
||||
this.router.get('/', this.encryptionController.root)
|
||||
this.router.get('/publickey/:address', this.encryptionController.getPublicKey)
|
||||
|
||||
app.use(this.baseUrl, this.router)
|
||||
}
|
||||
}
|
||||
|
||||
export default EncryptionRouter
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
import wlogger from '../../../adapters/wlogger.js'
|
||||
import BCHJS from '@psf/bch-js'
|
||||
import config from '../../../config/index.js'
|
||||
|
||||
const bchjs = new BCHJS()
|
||||
const bchjs = new BCHJS({ restURL: config.restURL })
|
||||
|
||||
class FulcrumRESTController {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -423,7 +424,20 @@ class FulcrumRESTController {
|
||||
|
||||
const cashAddr = this._validateAndConvertAddress(address)
|
||||
|
||||
const result = await this.fulcrumUseCases.getTransactions({ address: cashAddr, allTxs })
|
||||
// Extract bearer token from request header if present
|
||||
let bearerToken = null
|
||||
if (req.headers && req.headers.authorization) {
|
||||
const parts = req.headers.authorization.split(' ')
|
||||
if (parts.length === 2 && parts[0] === 'Bearer') {
|
||||
bearerToken = parts[1]
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.fulcrumUseCases.getTransactions({
|
||||
address: cashAddr,
|
||||
allTxs,
|
||||
bearerToken
|
||||
})
|
||||
return res.status(200).json(result)
|
||||
} catch (err) {
|
||||
return this.handleError(err, res)
|
||||
@@ -469,9 +483,19 @@ class FulcrumRESTController {
|
||||
}
|
||||
}
|
||||
|
||||
// Extract bearer token from request header if present
|
||||
let bearerToken = null
|
||||
if (req.headers && req.headers.authorization) {
|
||||
const parts = req.headers.authorization.split(' ')
|
||||
if (parts.length === 2 && parts[0] === 'Bearer') {
|
||||
bearerToken = parts[1]
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.fulcrumUseCases.getTransactionsBulk({
|
||||
addresses: validatedAddresses,
|
||||
allTxs
|
||||
allTxs,
|
||||
bearerToken
|
||||
})
|
||||
return res.status(200).json(result)
|
||||
} catch (err) {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import BlockchainRouter from './full-node/blockchain/router.js'
|
||||
import ControlRouter from './full-node/control/router.js'
|
||||
import DSProofRouter from './full-node/dsproof/router.js'
|
||||
import EncryptionRouter from './encryption/router.js'
|
||||
import FulcrumRouter from './fulcrum/router.js'
|
||||
import MiningRouter from './full-node/mining/router.js'
|
||||
import PriceRouter from './price/router.js'
|
||||
@@ -70,6 +71,9 @@ class RESTControllers {
|
||||
const dsproofRouter = new DSProofRouter(dependencies)
|
||||
dsproofRouter.attach(app)
|
||||
|
||||
const encryptionRouter = new EncryptionRouter(dependencies)
|
||||
encryptionRouter.attach(app)
|
||||
|
||||
const fulcrumRouter = new FulcrumRouter(dependencies)
|
||||
fulcrumRouter.attach(app)
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
import wlogger from '../../../adapters/wlogger.js'
|
||||
import BCHJS from '@psf/bch-js'
|
||||
import config from '../../../config/index.js'
|
||||
|
||||
const bchjs = new BCHJS()
|
||||
const bchjs = new BCHJS({ restURL: config.restURL })
|
||||
|
||||
class SlpRESTController {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -201,6 +202,7 @@ class SlpRESTController {
|
||||
const result = await this.slpUseCases.getTokenData({ tokenId, withTxHistory })
|
||||
return res.status(200).json(result)
|
||||
} catch (err) {
|
||||
console.log('Error in /v6/slp/token/data getTokenData(): ', err)
|
||||
return this.handleError(err, res)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
Use cases for encryption-related operations.
|
||||
Retrieves public keys from the blockchain for BCH addresses.
|
||||
*/
|
||||
|
||||
// Global npm libraries
|
||||
import BCHJS from '@psf/bch-js'
|
||||
|
||||
// Local libraries
|
||||
import wlogger from '../adapters/wlogger.js'
|
||||
import config from '../config/index.js'
|
||||
|
||||
const bchjs = new BCHJS({ restURL: config.restURL })
|
||||
|
||||
class EncryptionUseCases {
|
||||
constructor (localConfig = {}) {
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error('Adapters instance required when instantiating Encryption use cases.')
|
||||
}
|
||||
|
||||
this.useCases = localConfig.useCases
|
||||
if (!this.useCases) {
|
||||
throw new Error('UseCases instance required when instantiating Encryption use cases.')
|
||||
}
|
||||
|
||||
// Allow bchjs to be injected for testing
|
||||
this.bchjs = localConfig.bchjs || bchjs
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the public key for a BCH address by searching the blockchain.
|
||||
* Searches the transaction history of the address for a transaction input
|
||||
* that contains the public key.
|
||||
*
|
||||
* @param {Object} params - Parameters object
|
||||
* @param {string} params.address - BCH address (cash address or legacy format)
|
||||
* @returns {Promise<Object>} Object with success status and publicKey if found
|
||||
*/
|
||||
async getPublicKey ({ address }) {
|
||||
try {
|
||||
// Convert to cash address format
|
||||
const cashAddr = this.bchjs.Address.toCashAddress(address)
|
||||
|
||||
// Get transaction history for the address
|
||||
const txHistory = await this.useCases.fulcrum.getTransactions({ address: cashAddr })
|
||||
|
||||
// Extract just the TXIDs
|
||||
const txids = txHistory.transactions.map((elem) => elem.tx_hash)
|
||||
|
||||
// Throw error if there is no transaction history
|
||||
if (!txids || txids.length === 0) {
|
||||
throw new Error('No transaction history.')
|
||||
}
|
||||
|
||||
// Loop through the transaction history and search for the public key
|
||||
for (let i = 0; i < txids.length; i++) {
|
||||
const thisTx = txids[i]
|
||||
|
||||
// Get verbose transaction details
|
||||
const txDetails = await this.useCases.rawtransactions.getRawTransaction({
|
||||
txid: thisTx,
|
||||
verbose: true
|
||||
})
|
||||
|
||||
const vin = txDetails.vin
|
||||
|
||||
// Loop through each input
|
||||
for (let j = 0; j < vin.length; j++) {
|
||||
const thisVin = vin[j]
|
||||
|
||||
// Skip if no scriptSig (e.g., coinbase transactions)
|
||||
if (!thisVin.scriptSig || !thisVin.scriptSig.asm) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Extract the script signature
|
||||
const scriptSig = thisVin.scriptSig.asm.split(' ')
|
||||
|
||||
// Extract the public key from the script signature (last element)
|
||||
const pubKey = scriptSig[scriptSig.length - 1]
|
||||
|
||||
// Skip if pubKey is not a valid hex string (basic validation)
|
||||
if (!pubKey || !/^[0-9a-fA-F]+$/.test(pubKey)) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate cash address from public key
|
||||
const keyBuf = Buffer.from(pubKey, 'hex')
|
||||
const ec = this.bchjs.ECPair.fromPublicKey(keyBuf)
|
||||
const cashAddr2 = this.bchjs.ECPair.toCashAddress(ec)
|
||||
|
||||
// If public keys match, this is the correct public key
|
||||
if (cashAddr === cashAddr2) {
|
||||
return {
|
||||
success: true,
|
||||
publicKey: pubKey
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Skip invalid public keys - continue searching
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Public key not found in any transaction
|
||||
return {
|
||||
success: false,
|
||||
publicKey: 'not found'
|
||||
}
|
||||
} catch (err) {
|
||||
wlogger.error('Error in EncryptionUseCases.getPublicKey()', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default EncryptionUseCases
|
||||
@@ -4,8 +4,17 @@
|
||||
|
||||
import wlogger from '../adapters/wlogger.js'
|
||||
import BCHJS from '@psf/bch-js'
|
||||
import config from '../config/index.js'
|
||||
|
||||
const bchjs = new BCHJS()
|
||||
// Use RESTURL (from test) or REST_URL (from psf-bch-api config) or fallback to config
|
||||
const restURL = process.env.RESTURL || process.env.REST_URL || process.env.LOCAL_RESTURL || config.restURL
|
||||
// Use BCHJSBEARERTOKEN (from test) or BASIC_AUTH_TOKEN (from psf-bch-api config) or fallback to config
|
||||
const bearerToken = process.env.BCHJSBEARERTOKEN || process.env.BASIC_AUTH_TOKEN || config.basicAuth.token
|
||||
|
||||
const bchjs = new BCHJS({
|
||||
restURL,
|
||||
bearerToken
|
||||
})
|
||||
|
||||
class FulcrumUseCases {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -53,7 +62,14 @@ class FulcrumUseCases {
|
||||
}
|
||||
|
||||
async getTransactionDetails ({ txid }) {
|
||||
return this.fulcrum.get(`electrumx/tx/data/${txid}`)
|
||||
try {
|
||||
const response = await this.fulcrum.get(`electrumx/tx/data/${txid}`)
|
||||
// console.log(`getTransactionDetails() TXID ${txid}: ${JSON.stringify(response, null, 2)}`)
|
||||
return response
|
||||
} catch (err) {
|
||||
wlogger.error('Error in FulcrumUseCases.getTransactionDetails()', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async getTransactionDetailsBulk ({ txids, verbose }) {
|
||||
@@ -90,13 +106,24 @@ class FulcrumUseCases {
|
||||
}
|
||||
}
|
||||
|
||||
async getTransactions ({ address, allTxs }) {
|
||||
async getTransactions ({ address, allTxs, bearerToken = null }) {
|
||||
try {
|
||||
const response = await this.fulcrum.get(`electrumx/transactions/${address}`)
|
||||
|
||||
// Sort transactions in descending order, so that newest transactions are first.
|
||||
if (response.transactions && Array.isArray(response.transactions)) {
|
||||
response.transactions = await this.bchjs.Electrumx.sortAllTxs(response.transactions, 'DESCENDING')
|
||||
// Use bearer token from request if provided, otherwise use the default bchjs instance
|
||||
let bchjsInstance = this.bchjs
|
||||
if (bearerToken) {
|
||||
// Create a temporary bchjs instance with the bearer token from the request
|
||||
const restURL = process.env.RESTURL || process.env.REST_URL || process.env.LOCAL_RESTURL || config.restURL
|
||||
bchjsInstance = new BCHJS({
|
||||
restURL,
|
||||
bearerToken
|
||||
})
|
||||
}
|
||||
|
||||
response.transactions = await bchjsInstance.Electrumx.sortAllTxs(response.transactions, 'DESCENDING')
|
||||
|
||||
if (!allTxs) {
|
||||
// Return only the first 100 transactions of the history.
|
||||
@@ -111,16 +138,31 @@ class FulcrumUseCases {
|
||||
}
|
||||
}
|
||||
|
||||
async getTransactionsBulk ({ addresses, allTxs }) {
|
||||
async getTransactionsBulk ({ addresses, allTxs, bearerToken = null }) {
|
||||
try {
|
||||
const response = await this.fulcrum.post('electrumx/transactions/', { addresses })
|
||||
|
||||
// Sort transactions in descending order for each address entry.
|
||||
if (response.transactions && Array.isArray(response.transactions)) {
|
||||
// Use bearer token from request if provided, otherwise use the default bchjs instance
|
||||
let bchjsInstance = this.bchjs
|
||||
|
||||
// console.log('getTransactionsBulk() bearerToken: ', bearerToken)
|
||||
if (bearerToken) {
|
||||
// Create a temporary bchjs instance with the bearer token from the request
|
||||
const restURL = config.restURL
|
||||
|
||||
// console.log('getTransactionsBulk() restURL: ', restURL)
|
||||
bchjsInstance = new BCHJS({
|
||||
restURL,
|
||||
bearerToken
|
||||
})
|
||||
}
|
||||
|
||||
for (let i = 0; i < response.transactions.length; i++) {
|
||||
const thisEntry = response.transactions[i]
|
||||
if (thisEntry.transactions && Array.isArray(thisEntry.transactions)) {
|
||||
thisEntry.transactions = await this.bchjs.Electrumx.sortAllTxs(thisEntry.transactions, 'DESCENDING')
|
||||
thisEntry.transactions = await bchjsInstance.Electrumx.sortAllTxs(thisEntry.transactions, 'DESCENDING')
|
||||
|
||||
if (!allTxs && thisEntry.transactions.length > 100) {
|
||||
// Extract only the first 100 transactions.
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import BlockchainUseCases from './full-node-blockchain-use-cases.js'
|
||||
import ControlUseCases from './full-node-control-use-cases.js'
|
||||
import DSProofUseCases from './full-node-dsproof-use-cases.js'
|
||||
import EncryptionUseCases from './encryption-use-cases.js'
|
||||
import FulcrumUseCases from './fulcrum-use-cases.js'
|
||||
import MiningUseCases from './full-node-mining-use-cases.js'
|
||||
import PriceUseCases from './price-use-cases.js'
|
||||
@@ -31,6 +32,12 @@ class UseCases {
|
||||
this.price = new PriceUseCases({ adapters: this.adapters })
|
||||
this.rawtransactions = new RawTransactionsUseCases({ adapters: this.adapters })
|
||||
this.slp = new SlpUseCases({ adapters: this.adapters })
|
||||
|
||||
// Encryption use cases require access to other use cases (fulcrum, rawtransactions)
|
||||
this.encryption = new EncryptionUseCases({
|
||||
adapters: this.adapters,
|
||||
useCases: this
|
||||
})
|
||||
}
|
||||
|
||||
// Run any startup Use Cases at the start of the app.
|
||||
|
||||
@@ -9,7 +9,7 @@ import SlpTokenMedia from 'slp-token-media'
|
||||
import axios from 'axios'
|
||||
import config from '../config/index.js'
|
||||
|
||||
const bchjs = new BCHJS()
|
||||
const bchjs = new BCHJS({ restURL: config.restURL })
|
||||
|
||||
class SlpUseCases {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -259,6 +259,7 @@ class SlpUseCases {
|
||||
|
||||
return mutableCid
|
||||
} catch (err) {
|
||||
console.log('Error in SlpUseCases.getMutableCid()', err)
|
||||
wlogger.error('Error in SlpUseCases.getMutableCid()', err)
|
||||
return false
|
||||
}
|
||||
@@ -271,7 +272,9 @@ class SlpUseCases {
|
||||
}
|
||||
|
||||
// Get transaction data
|
||||
console.log('Decoding OP_RETURN for TXID: ', txid)
|
||||
const txData = await this.bchjs.Electrumx.txData(txid)
|
||||
// console.log(`TXID ${txid}: ${JSON.stringify(txData, null, 2)}`)
|
||||
let data = false
|
||||
|
||||
// Map the vout of the transaction in search of an OP_RETURN
|
||||
@@ -291,6 +294,7 @@ class SlpUseCases {
|
||||
|
||||
return data
|
||||
} catch (error) {
|
||||
console.log('Error in SlpUseCases.decodeOpReturn()', error)
|
||||
wlogger.error('Error in SlpUseCases.decodeOpReturn()', error)
|
||||
throw error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
Unit tests for EncryptionRESTController.
|
||||
*/
|
||||
|
||||
import { assert } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
|
||||
import EncryptionRESTController from '../../../src/controllers/rest-api/encryption/controller.js'
|
||||
import { createMockRequest, createMockResponse, createMockRequestWithParams } from '../mocks/controller-mocks.js'
|
||||
|
||||
describe('#encryption-controller.js', () => {
|
||||
let sandbox
|
||||
let mockAdapters
|
||||
let mockUseCases
|
||||
let uut
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = sinon.createSandbox()
|
||||
mockAdapters = {}
|
||||
mockUseCases = {
|
||||
encryption: {
|
||||
getPublicKey: sandbox.stub().resolves({
|
||||
success: true,
|
||||
publicKey: '02abc123def456789'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
uut = new EncryptionRESTController({
|
||||
adapters: mockAdapters,
|
||||
useCases: mockUseCases
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sandbox.restore()
|
||||
})
|
||||
|
||||
describe('#constructor()', () => {
|
||||
it('should require adapters', () => {
|
||||
assert.throws(() => {
|
||||
// eslint-disable-next-line no-new
|
||||
new EncryptionRESTController({ useCases: mockUseCases })
|
||||
}, /Adapters library required/)
|
||||
})
|
||||
|
||||
it('should require encryption use cases', () => {
|
||||
assert.throws(() => {
|
||||
// eslint-disable-next-line no-new
|
||||
new EncryptionRESTController({ adapters: mockAdapters, useCases: {} })
|
||||
}, /Encryption use cases required/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#root()', () => {
|
||||
it('should return encryption status', async () => {
|
||||
const req = createMockRequest()
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.root(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 200)
|
||||
assert.deepEqual(res.jsonData, { status: 'encryption' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('#getPublicKey()', () => {
|
||||
it('should return public key on success', async () => {
|
||||
const req = createMockRequestWithParams({
|
||||
address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
|
||||
})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 200)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: true,
|
||||
publicKey: '02abc123def456789'
|
||||
})
|
||||
assert.isTrue(mockUseCases.encryption.getPublicKey.calledOnce)
|
||||
assert.isTrue(mockUseCases.encryption.getPublicKey.calledWith({
|
||||
address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
|
||||
}))
|
||||
})
|
||||
|
||||
it('should return not found when public key is not found', async () => {
|
||||
mockUseCases.encryption.getPublicKey.resolves({
|
||||
success: false,
|
||||
publicKey: 'not found'
|
||||
})
|
||||
|
||||
const req = createMockRequestWithParams({
|
||||
address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
|
||||
})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 200)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
publicKey: 'not found'
|
||||
})
|
||||
})
|
||||
|
||||
it('should reject array addresses', async () => {
|
||||
const req = createMockRequestWithParams({
|
||||
address: ['addr1', 'addr2']
|
||||
})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 400)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'address can not be an array.'
|
||||
})
|
||||
assert.isFalse(mockUseCases.encryption.getPublicKey.called)
|
||||
})
|
||||
|
||||
it('should reject missing address', async () => {
|
||||
const req = createMockRequestWithParams({})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 400)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'address is required.'
|
||||
})
|
||||
assert.isFalse(mockUseCases.encryption.getPublicKey.called)
|
||||
})
|
||||
|
||||
it('should handle errors via handleError', async () => {
|
||||
const error = new Error('No transaction history.')
|
||||
error.status = 400
|
||||
mockUseCases.encryption.getPublicKey.rejects(error)
|
||||
|
||||
const req = createMockRequestWithParams({
|
||||
address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
|
||||
})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 400)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'No transaction history.'
|
||||
})
|
||||
})
|
||||
|
||||
it('should default to 500 status for errors without status', async () => {
|
||||
const error = new Error('Internal error')
|
||||
mockUseCases.encryption.getPublicKey.rejects(error)
|
||||
|
||||
const req = createMockRequestWithParams({
|
||||
address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
|
||||
})
|
||||
const res = createMockResponse()
|
||||
|
||||
await uut.getPublicKey(req, res)
|
||||
|
||||
assert.equal(res.statusValue, 500)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'Internal error'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('#handleError()', () => {
|
||||
it('should use error status and message when provided', () => {
|
||||
const error = new Error('Custom error')
|
||||
error.status = 422
|
||||
const res = createMockResponse()
|
||||
|
||||
uut.handleError(error, res)
|
||||
|
||||
assert.equal(res.statusValue, 422)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'Custom error'
|
||||
})
|
||||
})
|
||||
|
||||
it('should default to 500 and Internal server error', () => {
|
||||
const error = {}
|
||||
const res = createMockResponse()
|
||||
|
||||
uut.handleError(error, res)
|
||||
|
||||
assert.equal(res.statusValue, 500)
|
||||
assert.deepEqual(res.jsonData, {
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import RESTControllers from '../../../src/controllers/rest-api/index.js'
|
||||
import BlockchainRouter from '../../../src/controllers/rest-api/full-node/blockchain/router.js'
|
||||
import ControlRouter from '../../../src/controllers/rest-api/full-node/control/router.js'
|
||||
import DSProofRouter from '../../../src/controllers/rest-api/full-node/dsproof/router.js'
|
||||
import EncryptionRouter from '../../../src/controllers/rest-api/encryption/router.js'
|
||||
import MiningRouter from '../../../src/controllers/rest-api/full-node/mining/router.js'
|
||||
import PriceRouter from '../../../src/controllers/rest-api/price/router.js'
|
||||
import RawTransactionsRouter from '../../../src/controllers/rest-api/full-node/rawtransactions/router.js'
|
||||
@@ -100,6 +101,9 @@ describe('#controllers/rest-api/index.js', () => {
|
||||
getMutableCid: () => {},
|
||||
decodeOpReturn: () => {},
|
||||
getCIDData: () => {}
|
||||
},
|
||||
encryption: {
|
||||
getPublicKey: () => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -129,6 +133,7 @@ describe('#controllers/rest-api/index.js', () => {
|
||||
const blockchainAttachStub = sandbox.stub(BlockchainRouter.prototype, 'attach')
|
||||
const controlAttachStub = sandbox.stub(ControlRouter.prototype, 'attach')
|
||||
const dsproofAttachStub = sandbox.stub(DSProofRouter.prototype, 'attach')
|
||||
const encryptionAttachStub = sandbox.stub(EncryptionRouter.prototype, 'attach')
|
||||
const fulcrumAttachStub = sandbox.stub(FulcrumRouter.prototype, 'attach')
|
||||
const miningAttachStub = sandbox.stub(MiningRouter.prototype, 'attach')
|
||||
const priceAttachStub = sandbox.stub(PriceRouter.prototype, 'attach')
|
||||
@@ -148,6 +153,8 @@ describe('#controllers/rest-api/index.js', () => {
|
||||
assert.equal(controlAttachStub.getCall(0).args[0], app)
|
||||
assert.isTrue(dsproofAttachStub.calledOnce)
|
||||
assert.equal(dsproofAttachStub.getCall(0).args[0], app)
|
||||
assert.isTrue(encryptionAttachStub.calledOnce)
|
||||
assert.equal(encryptionAttachStub.getCall(0).args[0], app)
|
||||
assert.isTrue(fulcrumAttachStub.calledOnce)
|
||||
assert.equal(fulcrumAttachStub.getCall(0).args[0], app)
|
||||
assert.isTrue(miningAttachStub.calledOnce)
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
Unit tests for EncryptionUseCases.
|
||||
*/
|
||||
|
||||
import { assert } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
|
||||
import EncryptionUseCases from '../../../src/use-cases/encryption-use-cases.js'
|
||||
|
||||
describe('#encryption-use-cases.js', () => {
|
||||
let sandbox
|
||||
let mockAdapters
|
||||
let mockUseCases
|
||||
let mockBchjs
|
||||
let uut
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = sinon.createSandbox()
|
||||
mockAdapters = {}
|
||||
|
||||
// Mock bchjs
|
||||
mockBchjs = {
|
||||
Address: {
|
||||
toCashAddress: sandbox.stub().returns('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf')
|
||||
},
|
||||
ECPair: {
|
||||
fromPublicKey: sandbox.stub().returns({}),
|
||||
toCashAddress: sandbox.stub().returns('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf')
|
||||
}
|
||||
}
|
||||
|
||||
// Mock use cases
|
||||
mockUseCases = {
|
||||
fulcrum: {
|
||||
getTransactions: sandbox.stub().resolves({
|
||||
transactions: [
|
||||
{ tx_hash: 'abc123def456' }
|
||||
]
|
||||
})
|
||||
},
|
||||
rawtransactions: {
|
||||
getRawTransaction: sandbox.stub().resolves({
|
||||
vin: [
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'signature 02abc123def456789'
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
uut = new EncryptionUseCases({
|
||||
adapters: mockAdapters,
|
||||
useCases: mockUseCases,
|
||||
bchjs: mockBchjs
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sandbox.restore()
|
||||
})
|
||||
|
||||
describe('#constructor()', () => {
|
||||
it('should require adapters', () => {
|
||||
assert.throws(() => {
|
||||
// eslint-disable-next-line no-new
|
||||
new EncryptionUseCases({ useCases: mockUseCases })
|
||||
}, /Adapters instance required/)
|
||||
})
|
||||
|
||||
it('should require useCases', () => {
|
||||
assert.throws(() => {
|
||||
// eslint-disable-next-line no-new
|
||||
new EncryptionUseCases({ adapters: mockAdapters })
|
||||
}, /UseCases instance required/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#getPublicKey()', () => {
|
||||
it('should return public key when found', async () => {
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isTrue(result.success)
|
||||
assert.equal(result.publicKey, '02abc123def456789')
|
||||
assert.isTrue(mockBchjs.Address.toCashAddress.calledOnce)
|
||||
assert.isTrue(mockUseCases.fulcrum.getTransactions.calledOnce)
|
||||
assert.isTrue(mockUseCases.rawtransactions.getRawTransaction.calledOnce)
|
||||
})
|
||||
|
||||
it('should return not found when public key does not match', async () => {
|
||||
// Make the ECPair.toCashAddress return a different address
|
||||
mockBchjs.ECPair.toCashAddress.returns('bitcoincash:qqq000000000000000000000000000000000000000')
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isFalse(result.success)
|
||||
assert.equal(result.publicKey, 'not found')
|
||||
})
|
||||
|
||||
it('should throw error when no transaction history', async () => {
|
||||
mockUseCases.fulcrum.getTransactions.resolves({
|
||||
transactions: []
|
||||
})
|
||||
|
||||
try {
|
||||
await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
assert.fail('Should have thrown an error')
|
||||
} catch (err) {
|
||||
assert.equal(err.message, 'No transaction history.')
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle transactions without scriptSig', async () => {
|
||||
mockUseCases.rawtransactions.getRawTransaction.resolves({
|
||||
vin: [
|
||||
{ txid: 'coinbase' } // No scriptSig
|
||||
]
|
||||
})
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isFalse(result.success)
|
||||
assert.equal(result.publicKey, 'not found')
|
||||
})
|
||||
|
||||
it('should handle invalid public key hex gracefully', async () => {
|
||||
mockUseCases.rawtransactions.getRawTransaction.resolves({
|
||||
vin: [
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'signature NOT_VALID_HEX'
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isFalse(result.success)
|
||||
assert.equal(result.publicKey, 'not found')
|
||||
})
|
||||
|
||||
it('should handle ECPair.fromPublicKey throwing error', async () => {
|
||||
mockBchjs.ECPair.fromPublicKey.throws(new Error('Invalid public key'))
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isFalse(result.success)
|
||||
assert.equal(result.publicKey, 'not found')
|
||||
})
|
||||
|
||||
it('should search through multiple transactions', async () => {
|
||||
// First transaction has no matching public key
|
||||
mockUseCases.fulcrum.getTransactions.resolves({
|
||||
transactions: [
|
||||
{ tx_hash: 'tx1' },
|
||||
{ tx_hash: 'tx2' }
|
||||
]
|
||||
})
|
||||
|
||||
// Return different data for each tx - first tx has input with non-matching key
|
||||
mockUseCases.rawtransactions.getRawTransaction
|
||||
.onFirstCall().resolves({
|
||||
vin: [
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'sig 02aaa111bbb222ccc'
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
.onSecondCall().resolves({
|
||||
vin: [
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'sig 02abc123def456789'
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
// First tx doesn't match, second tx matches
|
||||
mockBchjs.ECPair.toCashAddress
|
||||
.onFirstCall().returns('bitcoincash:qqq000000000000000000000000000000000000000')
|
||||
.onSecondCall().returns('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf')
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isTrue(result.success)
|
||||
assert.equal(result.publicKey, '02abc123def456789')
|
||||
assert.equal(mockUseCases.rawtransactions.getRawTransaction.callCount, 2)
|
||||
})
|
||||
|
||||
it('should search through multiple inputs in a transaction', async () => {
|
||||
mockUseCases.rawtransactions.getRawTransaction.resolves({
|
||||
vin: [
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'sig 02aaa111bbb222ccc'
|
||||
}
|
||||
},
|
||||
{
|
||||
scriptSig: {
|
||||
asm: 'sig 02abc123def456789'
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
// First input doesn't match, second input matches
|
||||
mockBchjs.ECPair.toCashAddress
|
||||
.onFirstCall().returns('bitcoincash:qqq000000000000000000000000000000000000000')
|
||||
.onSecondCall().returns('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf')
|
||||
|
||||
const result = await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
|
||||
assert.isTrue(result.success)
|
||||
assert.equal(result.publicKey, '02abc123def456789')
|
||||
})
|
||||
|
||||
it('should propagate fulcrum errors', async () => {
|
||||
const error = new Error('Fulcrum API error')
|
||||
mockUseCases.fulcrum.getTransactions.rejects(error)
|
||||
|
||||
try {
|
||||
await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
assert.fail('Should have thrown an error')
|
||||
} catch (err) {
|
||||
assert.equal(err.message, 'Fulcrum API error')
|
||||
}
|
||||
})
|
||||
|
||||
it('should propagate rawtransactions errors', async () => {
|
||||
const error = new Error('RawTransactions API error')
|
||||
mockUseCases.rawtransactions.getRawTransaction.rejects(error)
|
||||
|
||||
try {
|
||||
await uut.getPublicKey({ address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf' })
|
||||
assert.fail('Should have thrown an error')
|
||||
} catch (err) {
|
||||
assert.equal(err.message, 'RawTransactions API error')
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -24,7 +24,7 @@ describe('#fulcrum-use-cases.js', () => {
|
||||
}
|
||||
|
||||
// Create a mock BCHJS instance with stubbed sortAllTxs method
|
||||
const mockBchjs = new BCHJS()
|
||||
const mockBchjs = new BCHJS({ restURL: 'http://localhost:5942/v6/' })
|
||||
if (!mockBchjs.Electrumx) {
|
||||
mockBchjs.Electrumx = {}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('#slp-use-cases.js', () => {
|
||||
}
|
||||
|
||||
// Create mock BCHJS
|
||||
mockBchjs = new BCHJS()
|
||||
mockBchjs = new BCHJS({ restURL: 'http://localhost:5942/v6/' })
|
||||
mockBchjs.Electrumx = {
|
||||
txData: sandbox.stub().resolves({
|
||||
details: {
|
||||
|
||||
Reference in New Issue
Block a user