103 Commits
Author SHA1 Message Date
Chris Troutner 300ef91aa1 Merge pull request #27 from Permissionless-Software-Foundation/ct-unstable
fix(full node): Debugging config settings
2026-05-15 13:33:16 -07:00
Chris Troutner a37cad7138 fixing tests 2026-05-15 13:31:37 -07:00
Chris Troutner 58ff8ef650 fix(full node): Debugging config settings 2026-05-15 13:20:00 -07:00
Chris Troutner 6a100d243a Merge pull request #26 from Permissionless-Software-Foundation/ct-unstable
Updates to x402 docs and api docs in Docker
2026-04-01 08:58:12 -07:00
Chris Troutner 67b141fc03 fix(Docker): Can change URL in api docs 2026-04-01 08:57:10 -07:00
Chris Troutner 5d77880a0e fix(x402 docs): Adding common LLM discovery documentation 2026-04-01 08:36:47 -07:00
Chris Troutner 3950560989 Merge pull request #25 from Permissionless-Software-Foundation/ct-unstable
feat(PSF Liquidity): Off by default, new endpoint reports PSF token p…
2026-03-28 19:26:22 -07:00
Chris Troutner aade1c58f5 feat(PSF Liquidity): Off by default, new endpoint reports PSF token price in BCH 2026-03-28 19:23:10 -07:00
Chris Troutner 2bbec7bc05 Merge pull request #24 from Permissionless-Software-Foundation/ct-unstable
Reducing logging noise for common errors
2026-03-17 16:20:34 -07:00
Chris Troutner cff0e89b0d Reducing logging noise for common errors 2026-03-17 16:19:36 -07:00
Chris Troutner 03caa3cd67 Merge pull request #23 from Permissionless-Software-Foundation/ct-unstable
fix(logging): Improved logging
2026-03-17 15:34:43 -07:00
Chris Troutner 6c8d512d1a fix(logging): Improved logging 2026-03-17 15:33:25 -07:00
Chris Troutner cc78aad785 Merge pull request #22 from Permissionless-Software-Foundation/ct-unstable
fix(logs): Reducing log noise
2026-03-16 20:52:28 -07:00
Chris Troutner 91f99405c1 fix(logs): Reducing log noise 2026-03-16 20:51:33 -07:00
Chris Troutner a959416b10 Merge pull request #21 from Permissionless-Software-Foundation/ct-unstable
fix(Docker): Persisting winston logs
2026-03-16 20:08:46 -07:00
Chris Troutner 562a196998 fix(Docker): Persisting winston logs 2026-03-16 20:08:04 -07:00
Chris Troutner e006a7ad86 Merge pull request #20 from Permissionless-Software-Foundation/ct-unstable
fix(timouts): Adjusting network timeout settings
2026-03-12 12:46:21 -07:00
Chris Troutner f36cd2a8aa fix(timouts): Adjusting network timeout settings 2026-03-12 12:45:33 -07:00
Chris Troutner 8b2cf64f1b Using ports for new slp indexer 2026-02-08 13:27:19 -08:00
Chris Troutner 95ae06fada Merge pull request #19 from Permissionless-Software-Foundation/ct-unstable
Updating README
2026-02-08 13:14:00 -07:00
Chris Troutner 188dc939b3 Adding link to live API documentation 2026-02-08 13:13:19 -07:00
Chris Troutner 7d566beea3 Adding link to live API documentation 2026-02-08 13:12:41 -07:00
Chris Troutner 6c42f47e15 fix(README): Expanding README 2026-02-08 13:07:23 -07:00
Chris Troutner d19a9e64cd Adding stack image to README 2026-02-08 12:57:06 -07:00
Chris Troutner 7c96d72f7b Removing debug settings 2026-02-04 15:12:24 -07:00
Chris Troutner 7f1770ab70 Refining URL lookup 2026-02-04 15:06:55 -07:00
Chris Troutner b25f55ce6a Adding more debugging 2026-02-04 14:58:20 -07:00
Chris Troutner 6e32723b29 fix(getTransactionsBulk()): Adding bearer token debugging 2026-02-04 14:47:12 -07:00
Chris Troutner 3b08fc3b62 Merge pull request #18 from Permissionless-Software-Foundation/ct-unstable
fix(auth token): Passing auth token to internal bch-js
2026-02-04 14:32:04 -07:00
Chris Troutner 2c1f02d6c7 fix(auth token): Passing auth token to internal bch-js 2026-02-04 14:31:06 -07:00
Chris Troutner 6cf03ca0fe Merge pull request #17 from Permissionless-Software-Foundation/ct-unstable
fix(Fulcrum): Handling different URL and auth tokens
2026-02-04 14:10:58 -07:00
Chris Troutner 5ea7bc9c29 fix(Fulcrum): Handling different URL and auth tokens 2026-02-04 14:09:12 -07:00
Chris Troutner 39021aba46 Merge pull request #16 from Permissionless-Software-Foundation/ct-unstable
fix(node v22): Updating dependencies & testing node.js v22
2026-01-16 11:10:38 -07:00
Chris Troutner de34547951 fix(node v22): Updating dependencies & testing node.js v22 2026-01-16 11:09:54 -07:00
Chris Troutner b8f34fb40e Merge pull request #15 from Permissionless-Software-Foundation/ct-unstable
fix(forward slashes): Fixing express specific issue
2025-12-29 18:16:13 -07:00
Chris Troutner 3778894ce2 Merge branch 'master' into ct-unstable 2025-12-29 18:15:16 -07:00
Chris Troutner 02eb8afd21 fix(forward slashes): Fixing express specific issue 2025-12-29 18:14:59 -07:00
Chris Troutner e708fc1228 Merge pull request #14 from Permissionless-Software-Foundation/ct-unstable
Adding middleware to detect multiple forward slashes in URL and automatically fix it.
2025-12-29 18:07:43 -07:00
Chris Troutner fed4b2da59 fix(forward slashes): Adding middleware to detect multiple forward slashes in the URL 2025-12-29 18:06:43 -07:00
Chris Troutner f30c2ede04 fix(deps): Updating dependencies 2025-12-29 18:01:30 -07:00
Chris Troutner 09e05d51e5 Merge pull request #13 from Permissionless-Software-Foundation/ct-unstable
feat(x402-bch): Updating to v2 protocol
2025-12-24 14:26:30 -07:00
Chris Troutner 22cbc54dee feat(x402-bch): Updating to v2 protocol 2025-12-24 14:25:44 -07:00
Chris Troutner 6fe0e01e8b Merge pull request #12 from Permissionless-Software-Foundation/ct-unstable
Improved debugging of interaction with x402 Facilitator
2025-12-22 06:48:35 -07:00
Chris Troutner f33b39ef01 fix(x402-bch-express): Updating to latest version 2025-12-22 06:35:47 -07:00
Chris Troutner 6d27630393 fix(debug): Debugging networking issues 2025-12-22 06:03:28 -07:00
Chris Troutner eac4916415 Updating .env-example for docker 2025-12-22 05:13:07 -07:00
Chris Troutner baa1170b89 Removing unneeded files 2025-12-22 05:10:59 -07:00
Chris Troutner 23ce276e19 fix(docker): Using .env rather than .env-example in docker file 2025-12-22 05:10:37 -07:00
Chris Troutner f28e2c6a1a Fixing bug in dockerfile 2025-12-21 16:38:43 -07:00
Chris Troutner 50a1a83a82 Merge pull request #11 from Permissionless-Software-Foundation/ct-unstable
Working towards x402 production
2025-12-21 16:34:26 -07:00
Chris Troutner eb2dda6955 fix(deps): Updating dependencies 2025-12-21 16:33:42 -07:00
Chris Troutner fe8d2ab051 Updating .env-example for docker container 2025-12-21 16:31:37 -07:00
Chris Troutner 66123de679 fix(fulcrum): Using basic auth token when psf-bch-api calls itself 2025-12-21 15:14:48 -07:00
Chris Troutner e2860d08b1 Changing default cost to 200 sats per call 2025-12-21 11:22:44 -07:00
Chris Troutner fa14af624f Merge pull request #10 from Permissionless-Software-Foundation/ct-unstable
fix(console.logs()): Removing terminal noise
2025-12-17 13:47:03 -07:00
Chris Troutner 1eb787e0d4 fix(console.logs()): Removing terminal noise 2025-12-17 13:46:08 -07:00
Chris Troutner ea815868ab Merge pull request #9 from Permissionless-Software-Foundation/ct-unstable
fix(psffpp): Updating lib to override IPFS gateway
2025-12-09 12:13:37 -07:00
Chris Troutner d17e3aa2d8 fix(psffpp): Updating lib to override IPFS gateway 2025-12-09 12:08:09 -07:00
Chris Troutner 1cd57a8bd7 Merge pull request #8 from Permissionless-Software-Foundation/ct-unstable
minimal-slp-wallet: updating to v7.0.1
2025-12-09 11:35:54 -07:00
Chris Troutner 50db4be890 fix(minimal-slp-wallet): Updating to v7.0.1 2025-12-09 11:35:15 -07:00
Chris Troutner 908911fba6 Copying .env-local to docker 2025-11-28 06:02:05 -08:00
Chris Troutner f6726c79bf Merge pull request #7 from Permissionless-Software-Foundation/ct-unstable
fix(port): Adding port config to .env-local file
2025-11-28 06:01:01 -08:00
Chris Troutner 8b12938e6c fix(port): Adding port config to .env-local file 2025-11-28 06:00:02 -08:00
Chris Troutner d204f78fa4 Merge pull request #6 from Permissionless-Software-Foundation/ct-unstable
fix(Docker): Creating docker container
2025-11-27 05:59:36 -08:00
Chris Troutner 58e831b22c fix(Docker): Creating docker container 2025-11-27 05:58:44 -08:00
Chris Troutner 6451736f26 Merge pull request #5 from Permissionless-Software-Foundation/ct-unstable
v7 bch-js & minimal-slp-wallet
2025-11-26 15:07:44 -08:00
Chris Troutner 571acbec59 fix(deps): Updating bch-js and minimal-slp-wallet 2025-11-26 15:06:07 -08:00
Chris Troutner 394ab73276 feat(encryption): Adding encryption REST API route 2025-11-26 14:30:41 -08:00
Chris Troutner ca0fcdd60a fixing broken tests 2025-11-26 11:09:40 -08:00
Chris Troutner 98576e5ff2 fix(startup): Ensuring REST URL is passed correctly to bch-js on startup 2025-11-26 11:00:08 -08:00
Chris Troutner 39144116a9 Merge pull request #4 from Permissionless-Software-Foundation/ct-unstable
Authentication - basic & x402
2025-11-25 14:31:17 -08:00
Chris Troutner 3aeb23ba17 fix(x402): Setting default server address to PSF burn addr 2025-11-25 08:57:23 -08:00
Chris Troutner c79c3fa59d fix(basic auth): Rejecting API calls that do not include basic auth header 2025-11-25 08:27:35 -08:00
Chris Troutner 0461db96c1 fix(.env): Updating .env-local example 2025-11-23 10:16:21 -08:00
Chris Troutner ca666f7c56 feat(basic auth): Allowing basic authentication for API access 2025-11-23 09:58:08 -08:00
Chris Troutner a23c4d9328 Updating config 2025-11-17 10:43:09 -08:00
Chris Troutner b5ed86e914 Adding psffpp dependency 2025-11-17 10:05:23 -08:00
Chris Troutner 6b09a3a172 feat(price): Adding price endpoints 2025-11-17 09:42:42 -08:00
Chris Troutner 73d94f6d82 Changing to v7.0.0 to keep in sync with bch-js 2025-11-16 10:28:40 -08:00
Chris Troutner 550c763df6 fix(app name): Changing index.js to psf-bch-api.js 2025-11-16 10:25:55 -08:00
Chris Troutner 8fe5a0b22d Merge pull request #3 from Permissionless-Software-Foundation/ct-unstable
Adding Fulcrum and SLP endpoints
2025-11-16 07:40:44 -08:00
Chris Troutner 5cd2e9fa2d Merge branch 'master' into ct-unstable 2025-11-16 07:39:55 -08:00
Chris Troutner c338fd38ea fix(slp): Removing the data2 path as it never worked well 2025-11-16 07:38:35 -08:00
Chris Troutner f59ca87f1e Converting /full-node/fulcrum endpoints to just /fulcrum 2025-11-15 17:55:56 -08:00
Chris Troutner 1914e6f985 fixing route name for fulcrum 2025-11-15 17:15:46 -08:00
Chris Troutner 5a5119716a feat(slp): Ported SLP endpoints from bch-api 2025-11-15 17:03:02 -08:00
Chris Troutner a37d088b52 Removing entities placeholder 2025-11-15 07:07:00 -08:00
Chris Troutner 81a1241b5d Renaming fulcrum libraries 2025-11-15 07:03:13 -08:00
Chris Troutner d104405f17 Moving fulcrum rest api libs 2025-11-14 08:46:34 -08:00
Chris Troutner ca25e33517 feat(fulcrum): Ported fulcrum endpoints from bch-api 2025-11-14 07:25:23 -08:00
Chris Troutner 2af4b0a943 Converted router index.js files to router.js 2025-11-14 06:56:59 -08:00
Chris Troutner e5c8fa9321 feat(rawtransactions): Adding full node raw transaction endpoints 2025-11-14 06:28:15 -08:00
Chris Troutner 4f89335768 feat(mining): Ported mining endpoints from bch-api 2025-11-14 05:22:59 -08:00
Chris Troutner f2e61fde35 Removing integration tests from old repository 2025-11-14 05:03:15 -08:00
Chris Troutner 5ab5547bf3 Adding code comments 2025-11-10 06:01:07 -08:00
Chris Troutner e794685981 Merge pull request #2 from Permissionless-Software-Foundation/ct-unstable
Added x402 payments for endpoint access
2025-11-09 21:43:20 -08:00
Chris Troutner eb57a7c773 feat(x402): Added x402 protection for each endpoint 2025-11-09 21:42:00 -08:00
Chris Troutner b41fa29c36 fix(v6/ prefix): Added prefix to URL 2025-11-09 21:17:22 -08:00
Chris Troutner 865993c1a9 fix(control): Added control and DS Proof endpoints 2025-11-09 19:48:13 -08:00
Chris Troutner 230853ed11 Merge pull request #1 from Permissionless-Software-Foundation/ct-unstable
Added full-node blockchain API endpoints
2025-11-09 19:41:03 -08:00
Chris Troutner 6096d52f84 fix(tests): Updating unit tests 2025-11-09 19:39:21 -08:00
Chris Troutner 78197762e4 Getting rid of placeholder controller libs 2025-11-09 19:24:48 -08:00
Chris Troutner 3fff9000bf feat(blockchain): Adding blockchain full-node endpoints 2025-11-09 19:18:39 -08:00
107 changed files with 13147 additions and 4206 deletions
+44
View File
@@ -0,0 +1,44 @@
# 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://localhost:5010
# REST API URL for wallet operations
LOCAL_RESTURL=http://localhost:5942/v6
# END INFRASTRUCTURE SETUP
# Public base URL for apiDoc HTML (optional; used by Docker entrypoint before `npm run docs`).
#APIDOC_URL=https://api.example.com
# START ACCESS CONTROL
PORT=5942
# x402 payments required to access this API?
X402_ENABLED=true
# Also gates discovery endpoints:
# /.well-known/x402, /openapi.json, /swagger.json, /llms.txt, /.well-known/agent.json
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
BASIC_AUTH_TOKEN=some-random-token
# END ACCESS CONTROL
# PSF token liquidity price proxy (GET /v6/price/psf). Off by default.
#PSF_LIQUIDITY_PROXY_ENABLED=true
#PSF_LIQUIDITY_URL=http://192.168.0.126:5000
+259 -2
View File
@@ -1,8 +1,265 @@
# 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.
[![License](https://img.shields.io/npm/l/@psf/bch-js)](https://github.com/Permissionless-Software-Foundation/psf-bch-api/blob/master/LICENSE.md)
[![js-standard-style](https://img.shields.io/badge/javascript-standard%20code%20style-green.svg?style=flat-square)](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 software stack](./bch-api-dependency-graph.png)
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.
When `X402_ENABLED=true`, the server also exposes machine-discovery endpoints:
- `/.well-known/x402` - x402-bch v2 payment discovery manifest
- `/openapi.json` - OpenAPI 3 projection generated from apiDoc annotations
- `/swagger.json` - Swagger 2.0 compatibility projection
- `/llms.txt` - LLM-oriented markdown index of service metadata
- `/.well-known/agent.json` - draft agent manifest describing API actions
When `X402_ENABLED=false`, these discovery endpoints return `404`.
#### 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.
To regenerate API docs plus discovery artifacts (`openapi.json`, `swagger.json`, `llms.txt`, and `agent.json` payload source):
`npm run docs:all`
This runs apiDoc first, then generates `docs/discovery-artifacts.json` from the same annotation source.
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
```
Set `APIDOC_URL` to the public base URL for your deployment (for example `https://api.example.com` or your subdomain). The container entrypoint applies this value to `apidoc.json` and the `apidoc` section of `package.json`, then runs `npm run docs` before starting the server so generated HTML matches each instance. The compose file mounts `./.env` to `/home/safeuser/psf-bch-api/.env` so it matches `dotenv.config()` in the app.
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)
+5 -5
View File
@@ -1,9 +1,9 @@
{
"name": "REST2NOSTR Proxy API",
"name": "psf-bch-api REST API",
"version": "1.0.0",
"description": "REST API proxy for Nostr WebSocket protocol",
"title": "REST2NOSTR Proxy API",
"url": "https://nostr-relay-api.psfoundation.info",
"sampleUrl": "https://nostr-relay-api.psfoundation.info"
"description": "REST API proxy to Bitcoin Cash infrastructure",
"title": "psf-bch-api REST API",
"url": "http://localhost:5942",
"sampleUrl": "http://localhost:5942"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+119 -3
View File
@@ -1,5 +1,5 @@
/*
Express server for REST2NOSTR Proxy API.
Express server for psf-bch-api REST API.
The architecture of the code follows the Clean Architecture pattern.
*/
@@ -7,6 +7,7 @@
import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
import { paymentMiddleware as x402PaymentMiddleware } from 'x402-bch-express'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
@@ -14,6 +15,9 @@ import { dirname, join } from 'path'
import config from '../src/config/index.js'
import Controllers from '../src/controllers/index.js'
import wlogger from '../src/adapters/wlogger.js'
import { buildX402Routes, getX402Settings, getBasicAuthSettings } from '../src/config/x402.js'
import { basicAuthMiddleware } from '../src/middleware/basic-auth.js'
import DiscoveryRouter from '../src/controllers/discovery/router.js'
// Load environment variables
dotenv.config()
@@ -56,6 +60,10 @@ class Server {
try {
// Create an Express instance.
const app = express()
app.set('trust proxy', true)
const x402Settings = getX402Settings()
const basicAuthSettings = getBasicAuthSettings()
// MIDDLEWARE START
app.use(express.json())
@@ -68,9 +76,107 @@ 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) {
wlogger.info('Basic auth middleware enabled')
app.use(basicAuthMiddleware)
}
// Apply x402 middleware based on configuration
// Logic:
// - 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) {
// X402_ENABLED=true AND USE_BASIC_AUTH=true: Apply x402 conditionally
const routes = buildX402Routes(this.config.apiPrefix)
const facilitatorOptions = x402Settings.facilitatorUrl
? { url: x402Settings.facilitatorUrl }
: undefined
wlogger.info(`x402 middleware enabled with basic auth bypass; enforcing ${x402Settings.priceSat} satoshis per request (unless basic auth provided)`)
// Create conditional x402 middleware that bypasses if basic auth is valid
const conditionalX402Middleware = (req, res, next) => {
// If basic auth is valid, bypass x402
if (req.locals?.basicAuthValid === true) {
return next()
}
// Otherwise, apply x402 middleware
return x402PaymentMiddleware(
x402Settings.serverAddress,
routes,
facilitatorOptions
)(req, res, next)
}
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)')
// Middleware that rejects requests without valid basic auth
const requireBasicAuthMiddleware = (req, res, next) => {
// Skip auth check for health endpoint and root
if (req.path === '/health' || req.path === '/') {
return next()
}
// If basic auth is valid, allow the request
if (req.locals?.basicAuthValid === true) {
return next()
}
// Reject unauthenticated requests
wlogger.warn(`Unauthenticated request rejected: ${req.method} ${req.path}`)
return res.status(401).json({
error: 'Unauthorized',
message: 'Valid Bearer token required in Authorization header'
})
}
app.use(requireBasicAuthMiddleware)
} else {
// X402_ENABLED=false AND USE_BASIC_AUTH=false: No access control middleware
wlogger.info('No access control middleware enabled')
}
// 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}`)
})
@@ -79,7 +185,10 @@ class Server {
// Request logging middleware
app.use((req, res, next) => {
wlogger.info(`${req.method} ${req.path}`)
wlogger.info(`${req.method} ${req.path}`, {
client_ip: req.ip,
remote_address: req.socket?.remoteAddress || null
})
next()
})
@@ -108,6 +217,8 @@ class Server {
// Attach REST API controllers to the app.
this.controllers.attachRESTControllers(app)
const discoveryRouter = new DiscoveryRouter()
discoveryRouter.attach(app)
// Initialize any other controller libraries.
this.controllers.initControllers()
@@ -142,6 +253,11 @@ class Server {
wlogger.info(`Server started on port ${this.config.port}`)
})
// Explicit timeout settings reduce stale keep-alive socket reuse races.
this.server.keepAliveTimeout = this.config.serverKeepAliveTimeoutMs
this.server.headersTimeout = this.config.serverHeadersTimeoutMs
this.server.requestTimeout = this.config.serverRequestTimeoutMs
this.server.on('error', (err) => {
console.error('Server error:', err)
wlogger.error('Server error:', err)
+21
View File
@@ -0,0 +1,21 @@
# 2026-03-16 Update Log
## Summary
Reduced noisy error logging for common SLP transaction misses in the `/v6/slp/txid` path.
## Changes Made
- Updated `src/use-cases/slp-use-cases.js` in `getTxid()`:
- Added a guard for expected missing-record errors (`404` + `Key not found in database`).
- Skips `wlogger.error()` for that specific, common case.
- Still rethrows the error so API response behavior is unchanged.
- Updated `src/controllers/rest-api/slp/controller.js` in `handleError()`:
- Added the same guard to suppress duplicate error-level logs for the same expected case.
- Keeps normal error logging for all other errors.
## Outcome
- The common "Key not found in database" case no longer pollutes error logs.
- Unexpected failures continue to be logged at error level.
- Client-facing status and error message behavior remains unchanged.
+76
View File
@@ -0,0 +1,76 @@
# 2026-03-17 Update Log
## Summary
Enhanced REST request logging to capture client network identity in Winston logs, enabled proxy-aware IP resolution, and reduced Fulcrum error-log noise for expected missing-transaction requests.
## Changes Made
- Updated `bin/server.js`:
- Set Express proxy handling with `app.set('trust proxy', true)`.
- Kept the current Winston request message format (`"${req.method} ${req.path}"`).
- Added structured Winston metadata fields to request logs:
- `client_ip` from `req.ip`
- `remote_address` from `req.socket.remoteAddress`
- Updated `src/adapters/fulcrum-api.js`:
- Added parsing helpers to normalize Fulcrum error messages from multiple response shapes.
- Mapped common daemon missing-TX error (`No such mempool or blockchain transaction`) to:
- status `404`
- message `Transaction not found`
- Updated `src/use-cases/fulcrum-use-cases.js`:
- Removed duplicate error logging in `getTransactionDetails()` and now rethrows adapter errors without a second error-level log.
- Updated `src/controllers/rest-api/fulcrum/controller.js`:
- Added TXID validation (`64`-character hex) for `GET /v6/fulcrum/tx/data/:txid`.
- Updated `handleError()` logging policy:
- `Transaction not found` (`404`) logs at `info`
- other `4xx` logs at `warn`
- `5xx` logs at `error`
## Useful Fields Available for REST Request Logging
- Routing and request basics:
- `method` (`req.method`)
- `path` (`req.path`)
- `original_url` (`req.originalUrl`)
- `query` (`req.query`)
- Client network identity:
- `client_ip` (`req.ip`)
- `forwarded_ips` (`req.ips`, when behind one or more proxies)
- `remote_address` (`req.socket.remoteAddress`)
- HTTP and transport:
- `protocol` (`req.protocol`)
- `secure` (`req.secure`)
- `http_version` (`req.httpVersion`)
- `host` (`req.get('host')`)
- `origin` (`req.get('origin')`)
- `referer` (`req.get('referer')`)
- `user_agent` (`req.get('user-agent')`)
- Request/response performance and size:
- `status_code` (`res.statusCode`, from `res.on('finish')`)
- `duration_ms` (elapsed time between request start and response finish)
- `request_size_bytes` (`req.get('content-length')`)
- `response_size_bytes` (`res.getHeader('content-length')`)
- App-specific request context in this codebase:
- `basic_auth_valid` (`req.locals.basicAuthValid`)
- x402 decision/bypass status (derived from middleware path and config)
## Already Logging
- In Winston request logs:
- `message` with method + path (for example `GET /v6/full-node/blockchain/getBlockCount`)
- `client_ip`
- `remote_address`
- `timestamp` (from Winston timestamp formatter)
- `level`
- In console endpoint logs:
- Request line with method, path, and `req.ip`
- Response line with method, path, and final `res.statusCode`
## Outcome
- Request logs now preserve existing behavior while adding IP attribution fields.
- `trust proxy` ensures `req.ip` is proxy-aware when the server is deployed behind a reverse proxy.
- The project now has a documented list of high-value request fields for future logging expansion.
- Fulcrum missing-transaction lookups now return cleaner API semantics (`404 Transaction not found`).
- Duplicate error logs for a single missing TX lookup were removed.
- Invalid TXIDs are rejected early with a `400` validation error.
+72
View File
@@ -0,0 +1,72 @@
# 2026-04-01 Update Log
## Summary
Added x402-gated discovery endpoints for agent/tool self-discovery, built a docs-derived artifact pipeline from apiDoc annotations, and documented the new flow and behavior.
## Changes Made
- Added new discovery controller/router:
- `src/controllers/discovery/controller.js`
- `src/controllers/discovery/router.js`
- Added five root-path discovery endpoints:
- `GET /.well-known/x402`
- `GET /openapi.json`
- `GET /swagger.json`
- `GET /llms.txt`
- `GET /.well-known/agent.json`
- Added x402-enabled gating:
- All five endpoints now return `404` when `X402_ENABLED=false`.
- When enabled, payloads are returned with x402-bch v2-oriented metadata.
- Added apiDoc-derived document builder:
- `src/discovery/build-documents.js`
- Parses `@api` annotations and builds OpenAPI, Swagger, llms, and agent documents.
- Uses `docs/discovery-artifacts.json` if present, otherwise builds in-process.
- Added artifact generation script:
- `scripts/build-discovery-artifacts.js`
- Writes `docs/discovery-artifacts.json`
- Updated npm scripts in `package.json`:
- `docs:discovery`
- `docs:all` (runs `docs` then `docs:discovery`)
- Wired discovery routes into server bootstrap:
- `bin/server.js`
- Added tests:
- `test/unit/controllers/discovery-controller-unit.js`
- `test/unit/controllers/discovery-router-unit.js`
- `test/unit/controllers/discovery-documents-unit.js`
- Updated docs/config examples:
- `README.md` (discovery endpoints + docs workflow)
- `.env-example` (x402 gating note for discovery endpoints)
## Why This Was Changed
- Endpoint probes for discovery paths are common from API tooling and AI agents.
- Serving structured discovery metadata improves machine interoperability for:
- API clients and SDK tooling (`openapi.json`, `swagger.json`)
- LLM retrieval workflows (`llms.txt`)
- Agent capability discovery (`agent.json`)
- x402 payment discovery (`/.well-known/x402`)
- Gating by `X402_ENABLED` keeps discovery aligned with monetization mode and avoids advertising payment surfaces when x402 is disabled.
## Validation Notes
- Lint passed.
- New discovery-focused unit tests passed.
- Full `npm test` run showed one pre-existing timeout failure in `test/unit/use-cases/price-use-cases-unit.js` unrelated to discovery endpoint changes.
## References
- Local protocol spec:
- `../x402-bch/specs/x402-bch-specification-v2.2.md`
- OpenAPI Specification:
- https://spec.openapis.org/oas/latest.html
- Swagger / OpenAPI 2.0:
- https://swagger.io/specification/v2/
- llms.txt proposal:
- https://www.llmstxt.org/index.html
- Agent manifest draft reference:
- https://agentwebprotocol.org/spec
- x402 HTTP 402 background:
- https://docs.x402.org/core-concepts/http-402
- x402 DNS discovery draft:
- https://www.ietf.org/archive/id/draft-jeftovic-x402-dns-discovery-00.html
+19
View File
@@ -0,0 +1,19 @@
# 2026-04-02 Update Log
## Summary
Docker deployments now run `npm run docs` at container start via an entrypoint script, and optionally apply `APIDOC_URL` from the environment so apiDoc HTML matches each deployment subdomain or public URL.
## Changes Made
- Added `scripts/patch-apidoc-from-env.js` to set `apidoc.json` and `package.json` `apidoc.url` from `APIDOC_URL` (dotenv loads the project `.env`, same path as `bin/server.js`).
- Added `production/docker/entrypoint.sh` to run the patch script, `npm run docs`, then `exec npm start`.
- Updated `production/docker/Dockerfile` to remove build-time `npm run docs`, copy the entrypoint and patch script from the build context, and use `ENTRYPOINT` for the shell script.
- Updated `production/docker/docker-compose.yml` to use build `context: ../..` and `dockerfile: production/docker/Dockerfile` so COPY paths resolve from the repository root.
- Compose mounts `./.env` at `/home/safeuser/psf-bch-api/.env` so the app and entrypoint share one file (not `/home/safeuser/.env`).
- Documented `APIDOC_URL` in `.env-example`, `production/docker/.env-example`, and `README.md` (Production Docker section).
## Outcome
- Operators can set `APIDOC_URL` in the mounted `.env` (for example `https://api.example.com`) per instance without rebuilding the image for each subdomain.
- The HTML apiDoc bundle is regenerated on every container start so it stays aligned with the configured URL.
+3278 -434
View File
File diff suppressed because it is too large Load Diff
+11 -3
View File
@@ -1,11 +1,13 @@
{
"name": "psf-bch-api",
"version": "1.0.0",
"main": "index.js",
"version": "7.0.0",
"main": "psf-bch-api.js",
"type": "module",
"scripts": {
"start": "node bin/server.js",
"docs": "./node_modules/.bin/apidoc -i src/ -o docs",
"docs:discovery": "node scripts/build-discovery-artifacts.js",
"docs:all": "npm run docs && npm run docs:discovery",
"lint": "standard --env mocha --fix",
"test": "npm run lint && TEST=unit c8 mocha 'test/unit/**/*.js' --exit",
"test:integration": "mocha --timeout 25000 'test/integration/**/*.js' --exit",
@@ -15,11 +17,17 @@
"license": "MIT",
"description": "REST API proxy to Bitcoin Cash infrastructure",
"dependencies": {
"@psf/bch-js": "7.1.14",
"axios": "1.7.7",
"cors": "2.8.5",
"dotenv": "16.3.1",
"express": "5.1.0",
"minimal-slp-wallet": "7.1.5",
"psffpp": "1.2.1",
"slp-token-media": "1.2.10",
"winston": "3.11.0",
"winston-daily-rotate-file": "4.7.1"
"winston-daily-rotate-file": "4.7.1",
"x402-bch-express": "2.0.0"
},
"devDependencies": {
"apidoc": "1.2.0",
+1
View File
@@ -0,0 +1 @@
+45
View File
@@ -0,0 +1,45 @@
# 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:5020
# REST API URL for wallet operations
LOCAL_RESTURL=http://172.17.0.1:5942/v6
# END INFRASTRUCTURE SETUP
# Public base URL for apiDoc HTML (set per deployment / subdomain).
# Applied at container start before `npm run docs`. Example: https://api.example.com
#APIDOC_URL=https://api.example.com
# 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
# PSF token liquidity price proxy (GET /v6/price/psf). Off by default.
#PSF_LIQUIDITY_PROXY_ENABLED=true
#PSF_LIQUIDITY_URL=http://192.168.0.126:5000
+14 -27
View File
@@ -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,28 @@ 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
# Runtime entrypoint + apidoc URL patch (see production/docker/entrypoint.sh).
# API docs are generated at container start so APIDOC_URL can be set per deployment.
COPY production/docker/entrypoint.sh /home/safeuser/psf-bch-api/entrypoint.sh
COPY scripts/patch-apidoc-from-env.js /home/safeuser/psf-bch-api/scripts/patch-apidoc-from-env.js
RUN chmod +x /home/safeuser/psf-bch-api/entrypoint.sh
#VOLUME /home/safeuser/keys
# Runtime `.env` is provided by docker-compose (mount at psf-bch-api/.env), not baked into the image.
# 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
ENTRYPOINT ["/home/safeuser/psf-bch-api/entrypoint.sh"]
# Expose the port the API will be served on.
#EXPOSE 5011
# 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"]
+9 -4
View File
@@ -1,9 +1,11 @@
# Start the service with the command 'docker-compose up -d'
services:
rest2nostr:
build: .
container_name: rest2nostr
psf-bch-api:
build:
context: ../..
dockerfile: production/docker/Dockerfile
container_name: psf-bch-api
logging:
driver: 'json-file'
options:
@@ -15,5 +17,8 @@ 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/psf-bch-api/.env
- ../data:/home/safeuser/psf-bch-api/production/data
- ../data/logs:/home/safeuser/psf-bch-api/logs
restart: always
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -euo pipefail
cd /home/safeuser/psf-bch-api
node scripts/patch-apidoc-from-env.js
npm run docs
exec npm start
-3
View File
@@ -1,3 +0,0 @@
#!/bin/bash
npm start
View File
+21
View File
@@ -0,0 +1,21 @@
/*
Build discovery endpoint artifacts from apiDoc source annotations.
*/
import { mkdirSync, writeFileSync } from 'fs'
import { dirname, resolve } from 'path'
import { buildDiscoveryDocuments } from '../src/discovery/build-documents.js'
function main () {
const outputPath = resolve(process.cwd(), 'docs/discovery-artifacts.json')
const docs = buildDiscoveryDocuments()
mkdirSync(dirname(outputPath), { recursive: true })
writeFileSync(outputPath, `${JSON.stringify(docs, null, 2)}\n`)
// eslint-disable-next-line no-console
console.log(`Wrote discovery artifacts to ${outputPath}`)
}
main()
+41
View File
@@ -0,0 +1,41 @@
/*
Applies APIDOC_URL from the environment to apidoc.json and package.json (apidoc.url).
Loads dotenv from the project root `.env` (same file as `dotenv.config()` in bin/server.js).
Exits without changes when APIDOC_URL is unset or empty.
*/
import dotenv from 'dotenv'
import { readFileSync, writeFileSync } from 'fs'
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
const root = resolve(__dirname, '..')
dotenv.config({ path: resolve(root, '.env') })
const url = process.env.APIDOC_URL
if (url === undefined || url === null || String(url).trim() === '') {
process.exit(0)
}
const normalized = String(url).trim()
function patchApidocJson () {
const path = resolve(root, 'apidoc.json')
const data = JSON.parse(readFileSync(path, 'utf8'))
data.url = normalized
data.sampleUrl = normalized
writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`)
}
function patchPackageJson () {
const path = resolve(root, 'package.json')
const data = JSON.parse(readFileSync(path, 'utf8'))
if (!data.apidoc) data.apidoc = {}
data.apidoc.url = normalized
writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`)
}
patchApidocJson()
patchPackageJson()
+154
View File
@@ -0,0 +1,154 @@
/*
Adapter library for interacting with Fulcrum API service over HTTP.
*/
import axios from 'axios'
import wlogger from './wlogger.js'
import config from '../config/index.js'
class FulcrumAPIAdapter {
constructor (localConfig = {}) {
this.config = localConfig.config || config
// Allow missing config for testing environments
if (!this.config.fulcrumApi || !this.config.fulcrumApi.baseUrl) {
if (process.env.NODE_ENV === 'test' || process.env.TEST) {
// In test environment, create a mock baseURL
this.config.fulcrumApi = {
baseUrl: 'http://localhost:50001',
timeoutMs: 15000
}
} else {
throw new Error('FULCRUM_API env var not set. Can not connect to Fulcrum indexer.')
}
}
const {
baseUrl,
timeoutMs = 15000
} = this.config.fulcrumApi
this.http = axios.create({
baseURL: baseUrl,
timeout: timeoutMs
})
}
async get (path) {
try {
const response = await this.http.get(path)
return response.data
} catch (err) {
throw this._handleError(err)
}
}
async post (path, data) {
try {
const response = await this.http.post(path, data)
return response.data
} catch (err) {
throw this._handleError(err)
}
}
_handleError (err) {
const { status, message } = this.decodeError(err)
const error = new Error(message)
error.status = status
error.originalError = err
return error
}
decodeError (err) {
try {
// Attempt to extract error message from response data
if (err.response && err.response.data) {
const data = err.response.data
const status = err.response.status || 400
const message = this._extractErrorMessage(data)
if (this._isCommonMissingTxError(message)) {
return this._formatError('Transaction not found', 404)
}
if (message) {
return this._formatError(message, status)
}
// Handle structured error responses
if (data.error) {
return this._formatError(data.error, status)
}
// Handle string error messages
if (typeof data === 'string') {
return this._formatError(data, status)
}
// Handle object responses that might contain error info
if (typeof data === 'object' && data.message) {
return this._formatError(data.message, status)
}
// Fallback to returning the status
return this._formatError('Fulcrum API error', err.response.status || 500)
}
// Network errors
if (err.message) {
if (err.message.includes('ENOTFOUND') || err.message.includes('ENETUNREACH') || err.message.includes('EAI_AGAIN')) {
return this._formatError(
'Network error: Could not communicate with Fulcrum API service.',
503
)
}
}
if (err.code && (err.code === 'ECONNABORTED' || err.code === 'ECONNREFUSED')) {
return this._formatError(
'Network error: Could not communicate with Fulcrum API service.',
503
)
}
if (err.error && typeof err.error === 'string' && err.error.includes('429')) {
return this._formatError('429 Too Many Requests', 429)
}
if (err.message) {
return this._formatError(err.message, err.status || 422)
}
return this._formatError('Unhandled Fulcrum API error', 500)
} catch (decodeError) {
wlogger.error('Unhandled error in FulcrumAPIAdapter.decodeError()', decodeError)
return this._formatError('Internal server error', 500)
}
}
_formatError (message, status = 500) {
return {
message: message || 'Internal server error',
status: status || 500
}
}
_extractErrorMessage (data) {
if (!data) return ''
if (typeof data === 'string') return data
if (typeof data === 'object') {
if (typeof data.error === 'string') return data.error
if (data.error && typeof data.error === 'object' && data.error.message) return data.error.message
if (data.message) return data.message
}
return ''
}
_isCommonMissingTxError (message = '') {
return typeof message === 'string' &&
message.includes('No such mempool or blockchain transaction')
}
}
export default FulcrumAPIAdapter
+130
View File
@@ -0,0 +1,130 @@
/*
Adapter library for interacting with a BCH full node over JSON-RPC.
*/
import axios from 'axios'
import wlogger from './wlogger.js'
import config from '../config/index.js'
class FullNodeRPCAdapter {
constructor (localConfig = {}) {
this.config = localConfig.config || config
if (!this.config.fullNode || !this.config.fullNode.rpcBaseUrl) {
throw new Error('Full node RPC configuration is required')
}
const {
rpcBaseUrl,
rpcUsername,
rpcPassword,
rpcTimeoutMs = 15000
} = this.config.fullNode
this.requestIdPrefix = this.config.fullNode.rpcRequestIdPrefix || 'psf-bch-api'
this.http = axios.create({
baseURL: rpcBaseUrl,
timeout: rpcTimeoutMs,
auth: {
username: rpcUsername,
password: rpcPassword
}
})
this.defaultRequestPayload = {
jsonrpc: '1.0'
}
}
async call (method, params = [], requestId) {
const id = requestId || `${this.requestIdPrefix}-${method}`
console.log('full-node-rpc.js/call(): this.http.defaults.baseURL: ', this.http.defaults.baseURL)
try {
const response = await this.http.post('', {
...this.defaultRequestPayload,
id,
method,
params
})
if (response.data && response.data.error) {
const rpcError = this._formatError(response.data.error.message, 400)
throw rpcError
}
return response.data.result
} catch (err) {
throw this._handleError(err)
}
}
_handleError (err) {
const { status, message } = this.decodeError(err)
const error = new Error(message)
error.status = status
error.originalError = err
return error
}
decodeError (err) {
try {
if (
err.response &&
err.response.data &&
err.response.data.error &&
err.response.data.error.message
) {
return this._formatError(err.response.data.error.message, 400)
}
if (err.response && err.response.data) {
return this._formatError(err.response.data, err.response.status || 500)
}
if (err.message) {
if (err.message.includes('ENOTFOUND') || err.message.includes('ENETUNREACH') || err.message.includes('EAI_AGAIN')) {
return this._formatError(
'Network error: Could not communicate with full node or other external service.',
503
)
}
}
if (err.code && (err.code === 'ECONNABORTED' || err.code === 'ECONNREFUSED')) {
return this._formatError(
'Network error: Could not communicate with full node or other external service.',
503
)
}
if (err.error && typeof err.error === 'string' && err.error.includes('429')) {
return this._formatError('429 Too Many Requests', 429)
}
if (err.message) {
return this._formatError(err.message, err.status || 422)
}
return this._formatError('Unhandled full node error', 500)
} catch (decodeError) {
wlogger.error('Unhandled error in FullNodeRPCAdapter.decodeError()', decodeError)
return this._formatError('Internal server error', 500)
}
}
validateArraySize (length) {
const limit = 20
return length <= limit
}
_formatError (message, status = 500) {
return {
message: message || 'Internal server error',
status: status || 500
}
}
}
export default FullNodeRPCAdapter
+7
View File
@@ -6,6 +6,9 @@
// Load individual adapter libraries.
// import NostrRelayAdapter from './nostr-relay.js'
import FullNodeRPCAdapter from './full-node-rpc.js'
import FulcrumAPIAdapter from './fulcrum-api.js'
import SlpIndexerAPIAdapter from './slp-indexer-api.js'
import config from '../config/index.js'
class Adapters {
@@ -30,6 +33,10 @@ class Adapters {
// Maintain backward compatibility: expose first relay as nostrRelay
// This allows existing code to work during transition
// this.nostrRelay = this.nostrRelays[0]
this.fullNode = new FullNodeRPCAdapter({ config: this.config })
this.fulcrum = new FulcrumAPIAdapter({ config: this.config })
this.slpIndexer = new SlpIndexerAPIAdapter({ config: this.config })
}
async start () {
-241
View File
@@ -1,241 +0,0 @@
/*
Nostr Relay WebSocket adapter.
Handles WebSocket connections to Nostr relays and manages message sending/receiving.
*/
import WebSocket from 'ws'
import config from '../config/index.js'
import wlogger from './wlogger.js'
class NostrRelayAdapter {
constructor (localConfig = {}) {
this.config = config
this.relayUrl = localConfig.relayUrl || config.nostrRelayUrl
this.ws = null
this.isConnected = false
this.reconnectAttempts = 0
this.maxReconnectAttempts = 5
this.reconnectDelay = 5000 // 5 seconds
this.messageHandlers = new Map() // Map subscription_id to handlers
this.pendingMessages = [] // Queue messages while disconnected
this.eventResolvers = new Map() // Map event_id to promise resolvers for OK responses
this.subscriptionHandlers = new Map() // Map subscription_id to event handlers
// Bind methods
this.connect = this.connect.bind(this)
this.disconnect = this.disconnect.bind(this)
this.sendEvent = this.sendEvent.bind(this)
this.sendReq = this.sendReq.bind(this)
this.sendClose = this.sendClose.bind(this)
this.handleMessage = this.handleMessage.bind(this)
this.handleError = this.handleError.bind(this)
this.handleClose = this.handleClose.bind(this)
}
async connect () {
if (this.ws && this.isConnected) {
return true
}
return new Promise((resolve, reject) => {
try {
wlogger.info(`Connecting to Nostr relay: ${this.relayUrl}`)
this.ws = new WebSocket(this.relayUrl)
this.ws.on('open', () => {
wlogger.info('Connected to Nostr relay')
this.isConnected = true
this.reconnectAttempts = 0
// Send any pending messages
while (this.pendingMessages.length > 0) {
const message = this.pendingMessages.shift()
this.ws.send(JSON.stringify(message))
}
resolve(true)
})
this.ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString())
this.handleMessage(message)
} catch (err) {
wlogger.error('Error parsing relay message:', err)
}
})
this.ws.on('error', this.handleError)
this.ws.on('close', this.handleClose)
// Timeout after 10 seconds
setTimeout(() => {
if (!this.isConnected) {
reject(new Error('Connection timeout'))
}
}, 10000)
} catch (err) {
wlogger.error('Error connecting to relay:', err)
reject(err)
}
})
}
async disconnect () {
if (this.ws) {
this.ws.close()
this.ws = null
this.isConnected = false
wlogger.info('Disconnected from Nostr relay')
}
}
handleMessage (message) {
if (!Array.isArray(message) || message.length === 0) {
return
}
const [type, ...args] = message
switch (type) {
case 'EVENT':
// ["EVENT", <subscription_id>, <event>]
if (args.length >= 2) {
const subscriptionId = args[0]
const event = args[1]
const handler = this.subscriptionHandlers.get(subscriptionId)
if (handler) {
handler.onEvent(event)
}
}
break
case 'OK':
// ["OK", <event_id>, <true|false>, <message>]
if (args.length >= 2) {
const eventId = args[0]
const accepted = args[1]
const message = args[2] || ''
const resolver = this.eventResolvers.get(eventId)
if (resolver) {
resolver({ accepted, message })
this.eventResolvers.delete(eventId)
}
}
break
case 'EOSE':
// ["EOSE", <subscription_id>]
if (args.length >= 1) {
const subscriptionId = args[0]
const handler = this.subscriptionHandlers.get(subscriptionId)
if (handler) {
handler.onEose()
}
}
break
case 'CLOSED':
// ["CLOSED", <subscription_id>, <message>]
if (args.length >= 1) {
const subscriptionId = args[0]
const message = args[1] || ''
const handler = this.subscriptionHandlers.get(subscriptionId)
if (handler) {
handler.onClosed(message)
}
}
break
case 'NOTICE':
// ["NOTICE", <message>]
if (args.length >= 1) {
const message = args[0]
wlogger.warn('Relay notice:', message)
}
break
default:
wlogger.warn('Unknown message type from relay:', type)
}
}
handleError (error) {
wlogger.error('WebSocket error:', error)
this.isConnected = false
}
handleClose () {
const now = new Date()
wlogger.warn(`WebSocket connection closed at ${now.toLocaleString()}`)
this.isConnected = false
// Attempt to reconnect
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++
wlogger.info(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
setTimeout(() => {
this.connect().catch(err => {
wlogger.error('Reconnection failed:', err)
})
}, this.reconnectDelay)
}
}
async sendMessage (message) {
if (!this.isConnected || !this.ws) {
// Queue message for when connection is established
this.pendingMessages.push(message)
await this.connect()
return
}
try {
this.ws.send(JSON.stringify(message))
} catch (err) {
wlogger.error('Error sending message:', err)
throw err
}
}
async sendEvent (event) {
// ["EVENT", <event>]
const message = ['EVENT', event]
await this.sendMessage(message)
// Return a promise that resolves when we get the OK response
return new Promise((resolve, reject) => {
this.eventResolvers.set(event.id, resolve)
// Timeout after 30 seconds
setTimeout(() => {
if (this.eventResolvers.has(event.id)) {
this.eventResolvers.delete(event.id)
reject(new Error('Timeout waiting for OK response'))
}
}, 30000)
})
}
async sendReq (subscriptionId, filters, handlers) {
// ["REQ", <subscription_id>, <filters>]
await this.connect()
// Store handlers for this subscription
this.subscriptionHandlers.set(subscriptionId, handlers)
const message = ['REQ', subscriptionId, ...filters]
await this.sendMessage(message)
}
async sendClose (subscriptionId) {
// ["CLOSE", <subscription_id>]
const message = ['CLOSE', subscriptionId]
await this.sendMessage(message)
// Clean up handlers
this.subscriptionHandlers.delete(subscriptionId)
this.messageHandlers.delete(subscriptionId)
}
}
export default NostrRelayAdapter
+124
View File
@@ -0,0 +1,124 @@
/*
Adapter library for interacting with SLP Indexer API service over HTTP.
*/
import axios from 'axios'
import wlogger from './wlogger.js'
import config from '../config/index.js'
class SlpIndexerAPIAdapter {
constructor (localConfig = {}) {
this.config = localConfig.config || config
// Allow missing config for testing environments
if (!this.config.slpIndexerApi || !this.config.slpIndexerApi.baseUrl) {
if (process.env.NODE_ENV === 'test' || process.env.TEST) {
// In test environment, create a mock baseURL
this.config.slpIndexerApi = {
baseUrl: 'http://localhost:5021',
timeoutMs: 15000
}
} else {
throw new Error('SLP_INDEXER_API env var not set. Can not connect to PSF SLP indexer.')
}
}
const {
baseUrl,
timeoutMs = 15000
} = this.config.slpIndexerApi
this.http = axios.create({
baseURL: baseUrl,
timeout: timeoutMs
})
}
async get (path) {
try {
const response = await this.http.get(path)
return response.data
} catch (err) {
throw this._handleError(err)
}
}
async post (path, data) {
try {
const response = await this.http.post(path, data)
return response.data
} catch (err) {
throw this._handleError(err)
}
}
_handleError (err) {
const { status, message } = this.decodeError(err)
const error = new Error(message)
error.status = status
error.originalError = err
return error
}
decodeError (err) {
try {
// Attempt to extract error message from response data
if (err.response && err.response.data) {
const data = err.response.data
// Handle structured error responses
if (data.error) {
return this._formatError(data.error, err.response.status || 400)
}
// Handle string error messages
if (typeof data === 'string') {
return this._formatError(data, err.response.status || 400)
}
// Handle object responses that might contain error info
if (typeof data === 'object' && data.message) {
return this._formatError(data.message, err.response.status || 400)
}
// Fallback to returning the status
return this._formatError('SLP Indexer API error', err.response.status || 500)
}
// Network errors
if (err.message) {
if (err.message.includes('ENOTFOUND') || err.message.includes('ENETUNREACH') || err.message.includes('EAI_AGAIN')) {
return this._formatError(
'Network error: Could not communicate with SLP Indexer API service.',
503
)
}
}
if (err.code && (err.code === 'ECONNABORTED' || err.code === 'ECONNREFUSED')) {
return this._formatError(
'Network error: Could not communicate with SLP Indexer API service.',
503
)
}
if (err.error && typeof err.error === 'string' && err.error.includes('429')) {
return this._formatError('429 Too Many Requests', 429)
}
if (err.message) {
return this._formatError(err.message, err.status || 422)
}
return this._formatError('Unhandled SLP Indexer API error', 500)
} catch (decodeError) {
wlogger.error('Unhandled error in SlpIndexerAPIAdapter.decodeError()', decodeError)
return this._formatError('Internal server error', 500)
}
}
_formatError (message, status = 500) {
return {
message: message || 'Internal server error',
status: status || 500
}
}
}
export default SlpIndexerAPIAdapter
+83 -23
View File
@@ -3,49 +3,109 @@
environments.
*/
import dotenv from 'dotenv'
// Hack to get __dirname back.
// https://blog.logrocket.com/alternatives-dirname-node-js-es-modules/
import * as url from 'url'
import { readFileSync } from 'fs'
dotenv.config()
const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
const pkgInfo = JSON.parse(readFileSync(`${__dirname.toString()}/../../../package.json`))
const version = pkgInfo.version
// This function is used to convert the string input of an environment variable to a boolean value.
const normalizeBoolean = (value, defaultValue) => {
if (value === undefined || value === null || value === '') return defaultValue
const normalized = String(value).trim().toLowerCase()
if (['false', '0', 'no', 'off'].includes(normalized)) return false
if (['true', '1', 'yes', 'on'].includes(normalized)) return true
return defaultValue
}
// 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 : 200
const x402Defaults = {
enabled: normalizeBoolean(process.env.X402_ENABLED, true),
facilitatorUrl: process.env.FACILITATOR_URL || 'http://localhost:4345/facilitator',
serverAddress: process.env.SERVER_BCH_ADDRESS || 'bitcoincash:qqsrke9lh257tqen99dkyy2emh4uty0vky9y0z0lsr',
priceSat
}
const basicAuthDefaults = {
enabled: normalizeBoolean(process.env.USE_BASIC_AUTH, false),
token: process.env.BASIC_AUTH_TOKEN || ''
}
const psfLiquidityUrlEnv = process.env.PSF_LIQUIDITY_URL
const psfLiquidityProxyBaseUrl =
psfLiquidityUrlEnv !== undefined &&
psfLiquidityUrlEnv !== null &&
String(psfLiquidityUrlEnv).trim() !== ''
? String(psfLiquidityUrlEnv).trim().replace(/\/$/, '')
: 'http://192.168.0.126:5000'
const psfLiquidityProxyDefaults = {
enabled: normalizeBoolean(process.env.PSF_LIQUIDITY_PROXY_ENABLED, false),
baseUrl: psfLiquidityProxyBaseUrl
}
export default {
// Server port
port: process.env.PORT || 5942,
port: parseInt(process.env.PORT, 10) || 5942,
// HTTP server connection lifecycle configuration.
serverKeepAliveTimeoutMs: Number(process.env.SERVER_KEEPALIVE_TIMEOUT_MS || 3000),
serverHeadersTimeoutMs: Number(process.env.SERVER_HEADERS_TIMEOUT_MS || 65000),
serverRequestTimeoutMs: Number(process.env.SERVER_REQUEST_TIMEOUT_MS || 120000),
// Environment
env: process.env.NODE_ENV || 'development',
// API prefix for REST controllers
apiPrefix: process.env.API_PREFIX || '/v6',
// Logging level
logLevel: process.env.LOG_LEVEL || 'info',
// Nostr relay configuration (array of relay URLs)
nostrRelayUrls: (() => {
// Support NOSTR_RELAY_URLS (plural) as comma-separated string or JSON array
if (process.env.NOSTR_RELAY_URLS) {
try {
// Try parsing as JSON array first
const parsed = JSON.parse(process.env.NOSTR_RELAY_URLS)
if (Array.isArray(parsed)) {
return parsed.filter(url => url && typeof url === 'string')
}
} catch (e) {
// Not JSON, treat as comma-separated string
return process.env.NOSTR_RELAY_URLS.split(',').map(url => url.trim()).filter(url => url.length > 0)
}
}
// Backward compatibility: support NOSTR_RELAY_URL (singular)
if (process.env.NOSTR_RELAY_URL) {
return [process.env.NOSTR_RELAY_URL]
}
// Full node RPC configuration
fullNode: {
rpcBaseUrl: process.env.RPC_BASEURL || 'http://127.0.0.1:8332',
rpcUsername: process.env.RPC_USERNAME || '',
rpcPassword: process.env.RPC_PASSWORD || '',
rpcTimeoutMs: Number(process.env.RPC_TIMEOUT_MS || 15000),
rpcRequestIdPrefix: process.env.RPC_REQUEST_ID_PREFIX || 'psf-bch-api'
},
// Default
return ['wss://nostr-relay.psfoundation.info', 'wss://relay.damus.io']
})(),
// Fulcrum API configuration
fulcrumApi: {
baseUrl: process.env.FULCRUM_API || '',
timeoutMs: Number(process.env.FULCRUM_TIMEOUT_MS || 15000)
},
// SLP Indexer API configuration
slpIndexerApi: {
baseUrl: process.env.SLP_INDEXER_API || '',
timeoutMs: Number(process.env.SLP_INDEXER_TIMEOUT_MS || 15000)
},
// REST API URL for wallet operations
restURL: process.env.REST_URL || process.env.LOCAL_RESTURL || 'http://127.0.0.1:5942/v6/',
// IPFS Gateway URL
ipfsGateway: process.env.IPFS_GATEWAY || 'p2wdb-gateway-678.fullstack.cash',
x402: x402Defaults,
basicAuth: basicAuthDefaults,
psfLiquidityProxy: psfLiquidityProxyDefaults,
// Version
version
+50
View File
@@ -0,0 +1,50 @@
import config from './index.js'
const DEFAULT_DESCRIPTION = 'Access to protected psf-bch-api resources'
const DEFAULT_TIMEOUT_SECONDS = 60
const NETWORK = 'bch'
/**
* Builds a route configuration map for x402-bch middleware.
*
* @param {string} apiPrefix Express API prefix (e.g., "/v6")
* @returns {Object} Routes configuration compatible with x402-bch-express
*/
export function buildX402Routes (apiPrefix = '/v6') {
const normalizedPrefix = apiPrefix.endsWith('/')
? apiPrefix.slice(0, -1)
: apiPrefix
const prefixWithSlash = normalizedPrefix.startsWith('/')
? normalizedPrefix
: `/${normalizedPrefix}`
const routeKey = `${prefixWithSlash}/*`
return {
network: NETWORK,
[routeKey]: {
price: config.x402.priceSat,
network: NETWORK,
config: {
description: `${DEFAULT_DESCRIPTION} (${config.x402.priceSat} satoshis)`,
maxTimeoutSeconds: DEFAULT_TIMEOUT_SECONDS
}
}
}
}
export function getX402Settings () {
return {
enabled: Boolean(config.x402?.enabled),
facilitatorUrl: config.x402?.facilitatorUrl,
serverAddress: config.x402?.serverAddress,
priceSat: config.x402?.priceSat
}
}
export function getBasicAuthSettings () {
return {
enabled: Boolean(config.basicAuth?.enabled),
token: config.basicAuth?.token || ''
}
}
+152
View File
@@ -0,0 +1,152 @@
/*
Controller for discovery and machine-readable metadata endpoints.
*/
import config from '../../config/index.js'
import { getX402Settings } from '../../config/x402.js'
import { getDiscoveryDocuments } from '../../discovery/build-documents.js'
const BCH_MAINNET_CAIP2 = 'bip122:000000000000000000651ef99cb9fcbe'
const BCH_NATIVE_ASSET = '0x0000000000000000000000000000000000000001'
const X402_TIMEOUT_SECONDS = 60
class DiscoveryController {
constructor (localConfig = {}) {
this.getX402Settings = localConfig.getX402Settings || getX402Settings
this.getDiscoveryDocuments = localConfig.getDiscoveryDocuments || getDiscoveryDocuments
this.apiPrefix = localConfig.apiPrefix || config.apiPrefix
this.x402Manifest = this.x402Manifest.bind(this)
this.openapi = this.openapi.bind(this)
this.swagger = this.swagger.bind(this)
this.llmsTxt = this.llmsTxt.bind(this)
this.agentManifest = this.agentManifest.bind(this)
this.respondNotFoundWhenDisabled = this.respondNotFoundWhenDisabled.bind(this)
this.sendText = this.sendText.bind(this)
}
respondNotFoundWhenDisabled (res) {
const { enabled } = this.getX402Settings()
if (enabled) return false
res.status(404).json({
error: 'Not found'
})
return true
}
/**
* @api {get} /.well-known/x402 x402-bch resource discovery
* @apiName X402Discovery
* @apiGroup Discovery
* @apiDescription Returns x402-bch v2 resource and payment requirement metadata.
*/
x402Manifest (req, res) {
if (this.respondNotFoundWhenDisabled(res)) return
const x402 = this.getX402Settings()
const apiPrefix = this.apiPrefix || '/v6'
const prefixWithSlash = apiPrefix.startsWith('/') ? apiPrefix : `/${apiPrefix}`
const payload = {
x402Version: 2,
network: BCH_MAINNET_CAIP2,
facilitator: {
url: x402.facilitatorUrl
},
resources: [
{
resource: `${prefixWithSlash}/*`,
type: 'http',
x402Version: 2,
accepts: [
{
scheme: 'utxo',
network: BCH_MAINNET_CAIP2,
amount: String(x402.priceSat),
description: `Access to protected psf-bch-api resources (${x402.priceSat} satoshis)`,
mimeType: 'application/json',
payTo: x402.serverAddress,
maxTimeoutSeconds: X402_TIMEOUT_SECONDS,
asset: BCH_NATIVE_ASSET,
extra: {}
}
]
}
]
}
return res.status(200).json(payload)
}
/**
* @api {get} /openapi.json OpenAPI discovery document
* @apiName OpenApiDiscovery
* @apiGroup Discovery
* @apiDescription Returns an OpenAPI document generated from apiDoc annotations.
*/
openapi (req, res) {
if (this.respondNotFoundWhenDisabled(res)) return
const docs = this.getDiscoveryDocuments()
return res.status(200).json(docs.openapi)
}
/**
* @api {get} /swagger.json Swagger discovery document
* @apiName SwaggerDiscovery
* @apiGroup Discovery
* @apiDescription Returns a Swagger 2.0 compatibility document generated from apiDoc annotations.
*/
swagger (req, res) {
if (this.respondNotFoundWhenDisabled(res)) return
const docs = this.getDiscoveryDocuments()
return res.status(200).json(docs.swagger)
}
/**
* @api {get} /llms.txt LLM discovery file
* @apiName LlmsDiscovery
* @apiGroup Discovery
* @apiDescription Returns an llms.txt markdown index for AI tooling discovery.
*/
llmsTxt (req, res) {
if (this.respondNotFoundWhenDisabled(res)) return
const docs = this.getDiscoveryDocuments()
return this.sendText(res, docs.llms)
}
/**
* @api {get} /.well-known/agent.json Agent manifest
* @apiName AgentManifestDiscovery
* @apiGroup Discovery
* @apiDescription Returns a draft agent manifest describing API capabilities.
*/
agentManifest (req, res) {
if (this.respondNotFoundWhenDisabled(res)) return
const docs = this.getDiscoveryDocuments()
return res.status(200).json(docs.agent)
}
sendText (res, text) {
res.status(200)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
if (typeof res.send === 'function') {
return res.send(text)
}
if (typeof res.write === 'function') {
res.write(text)
}
if (typeof res.end === 'function') {
res.end()
}
return res
}
}
export default DiscoveryController
+30
View File
@@ -0,0 +1,30 @@
/*
Router for discovery and machine-readable metadata endpoints.
*/
import express from 'express'
import DiscoveryController from './controller.js'
class DiscoveryRouter {
constructor (localConfig = {}) {
this.controller = localConfig.controller || new DiscoveryController()
this.router = express.Router()
this.attach = this.attach.bind(this)
}
attach (app) {
if (!app) {
throw new Error('Must pass app object when attaching DiscoveryRouter.')
}
this.router.get('/.well-known/x402', this.controller.x402Manifest)
this.router.get('/openapi.json', this.controller.openapi)
this.router.get('/swagger.json', this.controller.swagger)
this.router.get('/llms.txt', this.controller.llmsTxt)
this.router.get('/.well-known/agent.json', this.controller.agentManifest)
app.use(this.router)
}
}
export default DiscoveryRouter
+3 -1
View File
@@ -18,6 +18,7 @@ class Controllers {
this.useCases = new UseCases({ adapters: this.adapters })
this.config = config
this.timerController = new TimerController({ adapters: this.adapters, useCases: this.useCases })
this.apiPrefix = this.config.apiPrefix || '/v6'
// Bind 'this' object to all subfunctions
this.initAdapters = this.initAdapters.bind(this)
@@ -45,7 +46,8 @@ class Controllers {
attachRESTControllers (app) {
const restControllers = new RESTControllers({
adapters: this.adapters,
useCases: this.useCases
useCases: this.useCases,
apiPrefix: this.apiPrefix
})
// Attach the REST API Controllers to the Express app.
@@ -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
@@ -1,99 +0,0 @@
/*
REST API Controller library for the /event route
*/
// Local libraries
import wlogger from '../../../adapters/wlogger.js'
class EventRESTControllerLib {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating /event REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating /event REST Controller.'
)
}
// Bind 'this' object to all subfunctions
this.publishEvent = this.publishEvent.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {post} /event Publish a Nostr event
* @apiPermission public
* @apiName PublishEvent
* @apiGroup Event
*
* @apiDescription Publish a signed Nostr event to the relay. Maps to the Nostr WebSocket protocol message: ["EVENT", <event>]
*
* @apiParam {String} id Event ID (32-bytes lowercase hex-encoded sha256)
* @apiParam {String} pubkey Public key of event creator (32-bytes lowercase hex-encoded)
* @apiParam {Number} created_at Unix timestamp in seconds
* @apiParam {Number} kind Integer between 0 and 65535
* @apiParam {Array} tags Array of tag arrays
* @apiParam {String} content Event content (arbitrary string)
* @apiParam {String} sig Signature (64-bytes lowercase hex)
*
* @apiExample {json} Example usage:
* {
* "id": "5c83da77af1dec6d7289834998ad7aafbd9e2191396d75ec3cc27f5a77226f36",
* "pubkey": "2c7e76c0f8dc1dca9d0197c7d19be580a8d074ccada6a2f6ebe056ae41092e9",
* "created_at": 1672531200,
* "kind": 1,
* "tags": [],
* "content": "Hello, Nostr!",
* "sig": "abc123..."
* }
*
* @apiSuccess {Boolean} accepted Whether the event was accepted by the relay
* @apiSuccess {String} message Optional message from the relay
* @apiSuccess {String} eventId The event ID
*
* @apiError {String} error Error message
*/
async publishEvent (req, res) {
try {
const eventData = req.body
// Check if eventData is missing or empty
if (!eventData || (typeof eventData === 'object' && Object.keys(eventData).length === 0)) {
return res.status(400).json({
error: 'Event data is required'
})
}
const result = await this.useCases.publishEvent.execute(eventData)
if (result.accepted) {
return res.status(200).json(result)
} else {
return res.status(400).json(result)
}
} catch (err) {
return this.handleError(err, req, res)
}
}
handleError (err, req, res) {
wlogger.error('Error in EventRESTController:', err)
// Return 400 for validation errors, 500 for other errors
// Validation errors indicate the client sent bad data
const isValidationError = err.message && err.message.includes('Invalid event structure')
const statusCode = isValidationError ? 400 : 500
return res.status(statusCode).json({
error: err.message || 'Internal server error'
})
}
}
export default EventRESTControllerLib
-55
View File
@@ -1,55 +0,0 @@
/*
REST API library for the /event route.
*/
// Public npm libraries.
import express from 'express'
// Local libraries.
import EventRESTControllerLib from './controller.js'
class EventRouter {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Event REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Event REST Controller.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
// Encapsulate dependencies.
this.eventRESTController = new EventRESTControllerLib(dependencies)
// Instantiate the router and set the base route.
this.baseUrl = '/event'
this.router = express.Router()
}
attach (app) {
if (!app) {
throw new Error(
'Must pass app object when attaching REST API controllers.'
)
}
// Define the routes and attach the controller.
this.router.post('/', this.eventRESTController.publishEvent)
// Attach the Controller routes to the Express app.
app.use(this.baseUrl, this.router)
}
}
export default EventRouter
@@ -0,0 +1,605 @@
/*
REST API Controller for the /fulcrum routes.
*/
import wlogger from '../../../adapters/wlogger.js'
import BCHJS from '@psf/bch-js'
import config from '../../../config/index.js'
const bchjs = new BCHJS({ restURL: config.restURL })
class FulcrumRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Fulcrum REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.fulcrum) {
throw new Error(
'Instance of Fulcrum use cases required when instantiating Fulcrum REST Controller.'
)
}
this.fulcrumUseCases = this.useCases.fulcrum
// Bind functions
this.root = this.root.bind(this)
this.getBalance = this.getBalance.bind(this)
this.balanceBulk = this.balanceBulk.bind(this)
this.getUtxos = this.getUtxos.bind(this)
this.utxosBulk = this.utxosBulk.bind(this)
this.getTransactionDetails = this.getTransactionDetails.bind(this)
this.transactionDetailsBulk = this.transactionDetailsBulk.bind(this)
this.broadcastTransaction = this.broadcastTransaction.bind(this)
this.getBlockHeaders = this.getBlockHeaders.bind(this)
this.blockHeadersBulk = this.blockHeadersBulk.bind(this)
this.getTransactions = this.getTransactions.bind(this)
this.transactionsBulk = this.transactionsBulk.bind(this)
this.getMempool = this.getMempool.bind(this)
this.mempoolBulk = this.mempoolBulk.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/fulcrum/ Service status
* @apiName FulcrumRoot
* @apiGroup Fulcrum
*
* @apiDescription Returns the status of the fulcrum service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'fulcrum' })
}
/**
* Validates and converts an address to cash address format
* @param {string} address - Address to validate and convert
* @returns {string} Cash address
* @throws {Error} If address is invalid or not mainnet
*/
_validateAndConvertAddress (address) {
if (!address) {
throw new Error('address is empty')
}
// Convert legacy to cash address
const cashAddr = bchjs.Address.toCashAddress(address)
// Ensure it's a valid BCH address
try {
bchjs.Address.toLegacyAddress(cashAddr)
} catch (err) {
throw new Error(`Invalid BCH address. Double check your address is valid: ${address}`)
}
// Ensure it's mainnet (no testnet support)
const isMainnet = bchjs.Address.isMainnetAddress(cashAddr)
if (!isMainnet) {
throw new Error('Invalid network. Only mainnet addresses are supported.')
}
return cashAddr
}
_isValidTxid (txid) {
return typeof txid === 'string' && /^[a-fA-F0-9]{64}$/.test(txid)
}
_isCommonMissingTxError (err) {
return err?.status === 404 &&
typeof err?.message === 'string' &&
err.message.includes('Transaction not found')
}
/**
* @api {get} /v6/fulcrum/balance/:address Get balance for a single address
* @apiName GetBalance
* @apiGroup Fulcrum
* @apiDescription Returns an object with confirmed and unconfirmed balance associated with an address.
*/
async getBalance (req, res) {
try {
const address = req.params.address
if (Array.isArray(address)) {
return res.status(400).json({
success: false,
error: 'address can not be an array. Use POST for bulk upload.'
})
}
const cashAddr = this._validateAndConvertAddress(address)
const result = await this.fulcrumUseCases.getBalance({ address: cashAddr })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/balance Get balances for an array of addresses
* @apiName GetBalances
* @apiGroup Fulcrum
* @apiDescription Returns an array of balances associated with an array of addresses. Limited to 20 items per request.
*/
async balanceBulk (req, res) {
try {
const addresses = req.body.addresses
if (!Array.isArray(addresses)) {
return res.status(400).json({
success: false,
error: 'addresses needs to be an array. Use GET for single address.'
})
}
if (!this.adapters.fullNode.validateArraySize(addresses.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
// Validate and convert all addresses
const validatedAddresses = []
for (let i = 0; i < addresses.length; i++) {
try {
const cashAddr = this._validateAndConvertAddress(addresses[i])
validatedAddresses.push(cashAddr)
} catch (err) {
return res.status(400).json({
success: false,
error: err.message
})
}
}
const result = await this.fulcrumUseCases.getBalances({ addresses: validatedAddresses })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/fulcrum/utxos/:address Get utxos for a single address
* @apiName GetUtxos
* @apiGroup Fulcrum
* @apiDescription Returns an object with UTXOs associated with an address.
*/
async getUtxos (req, res) {
try {
const address = req.params.address
if (Array.isArray(address)) {
return res.status(400).json({
success: false,
error: 'address can not be an array. Use POST for bulk upload.'
})
}
const cashAddr = this._validateAndConvertAddress(address)
const result = await this.fulcrumUseCases.getUtxos({ address: cashAddr })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/utxos Get utxos for an array of addresses
* @apiName GetUtxosBulk
* @apiGroup Fulcrum
* @apiDescription Returns an array of objects with UTXOs associated with an address. Limited to 20 items per request.
*/
async utxosBulk (req, res) {
try {
const addresses = req.body.addresses
if (!Array.isArray(addresses)) {
return res.status(400).json({
success: false,
error: 'addresses needs to be an array. Use GET for single address.'
})
}
if (!this.adapters.fullNode.validateArraySize(addresses.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
// Validate and convert all addresses
const validatedAddresses = []
for (let i = 0; i < addresses.length; i++) {
try {
const cashAddr = this._validateAndConvertAddress(addresses[i])
validatedAddresses.push(cashAddr)
} catch (err) {
return res.status(400).json({
success: false,
error: err.message
})
}
}
const result = await this.fulcrumUseCases.getUtxosBulk({ addresses: validatedAddresses })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/fulcrum/tx/data/:txid Get transaction details for a TXID
* @apiName GetTransactionDetails
* @apiGroup Fulcrum
* @apiDescription Returns an object with transaction details of the TXID
*/
async getTransactionDetails (req, res) {
try {
const txid = req.params.txid
if (!this._isValidTxid(txid)) {
return res.status(400).json({
success: false,
error: 'txid must be a 64-character hex string'
})
}
const result = await this.fulcrumUseCases.getTransactionDetails({ txid })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/tx/data Get transaction details for an array of TXIDs
* @apiName GetTransactionDetailsBulk
* @apiGroup Fulcrum
* @apiDescription Returns an array of objects with transaction details of an array of TXIDs. Limited to 20 items per request.
*/
async transactionDetailsBulk (req, res) {
try {
const txids = req.body.txids
const verbose = req.body.verbose !== undefined ? req.body.verbose : true
if (!Array.isArray(txids)) {
return res.status(400).json({
success: false,
error: 'txids needs to be an array. Use GET for single txid.'
})
}
if (!this.adapters.fullNode.validateArraySize(txids.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
const result = await this.fulcrumUseCases.getTransactionDetailsBulk({ txids, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/tx/broadcast Broadcast a raw transaction
* @apiName BroadcastTransaction
* @apiGroup Fulcrum
* @apiDescription Broadcast a raw transaction and return the transaction ID on success or error on failure.
*/
async broadcastTransaction (req, res) {
try {
const txHex = req.body.txHex
if (typeof txHex !== 'string') {
return res.status(400).json({
success: false,
error: 'txHex must be a string'
})
}
const result = await this.fulcrumUseCases.broadcastTransaction({ txHex })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/fulcrum/block/headers/:height Get block headers
* @apiName GetBlockHeaders
* @apiGroup Fulcrum
* @apiDescription Returns an array with block headers starting at the block height
*
* @apiParam {Number} height Block height
* @apiParam {Number} count Number of block headers to return (query parameter, default: 1)
*/
async getBlockHeaders (req, res) {
try {
const heightRaw = req.params.height
const countRaw = req.query.count
const height = Number(heightRaw)
const count = countRaw === undefined ? 1 : Number(countRaw)
if (Number.isNaN(height) || height < 0) {
return res.status(400).json({
success: false,
error: 'height must be a positive number'
})
}
if (Number.isNaN(count) || count < 0) {
return res.status(400).json({
success: false,
error: 'count must be a positive number'
})
}
const result = await this.fulcrumUseCases.getBlockHeaders({ height, count })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/block/headers Get block headers for an array of height + count pairs
* @apiName GetBlockHeadersBulk
* @apiGroup Fulcrum
* @apiDescription Returns an array of objects with block headers. Limited to 20 items per request.
*/
async blockHeadersBulk (req, res) {
try {
const heights = req.body.heights
if (!Array.isArray(heights)) {
return res.status(400).json({
success: false,
error: 'heights needs to be an array. Use GET for single height.'
})
}
if (!this.adapters.fullNode.validateArraySize(heights.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
// Validate each height object
for (const item of heights) {
if (!item || typeof item.height !== 'number' || typeof item.count !== 'number') {
return res.status(400).json({
success: false,
error: 'Each height object must have numeric height and count properties'
})
}
if (item.height < 0 || item.count < 0) {
return res.status(400).json({
success: false,
error: 'height and count must be positive numbers'
})
}
}
const result = await this.fulcrumUseCases.getBlockHeadersBulk({ heights })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/fulcrum/transactions/:address Get transaction history for a single address
* @apiName GetTransactions
* @apiGroup Fulcrum
* @apiDescription Returns an array of historical transactions associated with an address. Results are returned in descending order (most recent TX first). Passing allTxs=true will return the entire transaction history, otherwise, only the last 100 TXIDs will be returned.
*
* @apiParam {String} address Address
* @apiParam {Boolean} allTxs Optional: return all transactions (default: false, limited to 100)
*/
async getTransactions (req, res) {
try {
const address = req.params.address
let allTxs = false
// Check if allTxs is in params or query
if (req.params.allTxs) {
allTxs = req.params.allTxs === 'true'
} else if (req.query.allTxs) {
allTxs = req.query.allTxs === 'true'
}
if (Array.isArray(address)) {
return res.status(400).json({
success: false,
error: 'address can not be an array. Use POST for bulk upload.'
})
}
const cashAddr = this._validateAndConvertAddress(address)
// 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)
}
}
/**
* @api {post} /v6/fulcrum/transactions Get the transaction history for an array of addresses
* @apiName GetTransactionsBulk
* @apiGroup Fulcrum
* @apiDescription Returns an array of transactions associated with an array of addresses. Limited to 20 items per request. Passing allTxs=true will return the entire transaction history, otherwise, only the last 100 TXIDs will be returned.
*/
async transactionsBulk (req, res) {
try {
const addresses = req.body.addresses
const allTxs = req.body.allTxs === true
if (!Array.isArray(addresses)) {
return res.status(400).json({
success: false,
error: 'addresses needs to be an array. Use GET for single address.'
})
}
if (!this.adapters.fullNode.validateArraySize(addresses.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
// Validate and convert all addresses
const validatedAddresses = []
for (let i = 0; i < addresses.length; i++) {
try {
const cashAddr = this._validateAndConvertAddress(addresses[i])
validatedAddresses.push(cashAddr)
} catch (err) {
return res.status(400).json({
success: false,
error: err.message
})
}
}
// 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,
bearerToken
})
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/fulcrum/unconfirmed/:address Get unconfirmed utxos for a single address
* @apiName GetMempool
* @apiGroup Fulcrum
* @apiDescription Returns an object with unconfirmed UTXOs associated with an address.
*/
async getMempool (req, res) {
try {
const address = req.params.address
if (Array.isArray(address)) {
return res.status(400).json({
success: false,
error: 'address can not be an array. Use POST for bulk upload.'
})
}
const cashAddr = this._validateAndConvertAddress(address)
const result = await this.fulcrumUseCases.getMempool({ address: cashAddr })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/fulcrum/unconfirmed Get unconfirmed utxos for an array of addresses
* @apiName GetMempoolBulk
* @apiGroup Fulcrum
* @apiDescription Returns an array of objects with unconfirmed UTXOs associated with an address. Limited to 20 items per request.
*/
async mempoolBulk (req, res) {
try {
const addresses = req.body.addresses
if (!Array.isArray(addresses)) {
return res.status(400).json({
success: false,
error: 'addresses needs to be an array. Use GET for single address.'
})
}
if (!this.adapters.fullNode.validateArraySize(addresses.length)) {
return res.status(400).json({
success: false,
error: 'Array too large.'
})
}
// Validate and convert all addresses
const validatedAddresses = []
for (let i = 0; i < addresses.length; i++) {
try {
const cashAddr = this._validateAndConvertAddress(addresses[i])
validatedAddresses.push(cashAddr)
} catch (err) {
return res.status(400).json({
success: false,
error: err.message
})
}
}
const result = await this.fulcrumUseCases.getMempoolBulk({ addresses: validatedAddresses })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
const status = err.status || 500
const isCommonMissingTxError = this._isCommonMissingTxError(err)
if (isCommonMissingTxError) {
wlogger.info(`Fulcrum transaction not found: ${err.message}`)
} else if (status >= 500) {
wlogger.error('Error in FulcrumRESTController:', err)
} else {
wlogger.warn(`Fulcrum client error (${status}): ${err.message}`)
}
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default FulcrumRESTController
@@ -0,0 +1,64 @@
/*
REST API router for /full-node/fulcrum routes.
*/
import express from 'express'
import FulcrumRESTController from './controller.js'
class FulcrumRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Fulcrum REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Fulcrum REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.fulcrumController = new FulcrumRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/fulcrum`
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.fulcrumController.root)
this.router.get('/balance/:address', this.fulcrumController.getBalance)
this.router.post('/balance', this.fulcrumController.balanceBulk)
this.router.get('/utxos/:address', this.fulcrumController.getUtxos)
this.router.post('/utxos', this.fulcrumController.utxosBulk)
this.router.get('/tx/data/:txid', this.fulcrumController.getTransactionDetails)
this.router.post('/tx/data', this.fulcrumController.transactionDetailsBulk)
this.router.post('/tx/broadcast', this.fulcrumController.broadcastTransaction)
this.router.get('/block/headers/:height', this.fulcrumController.getBlockHeaders)
this.router.post('/block/headers', this.fulcrumController.blockHeadersBulk)
this.router.get('/transactions/:address', this.fulcrumController.getTransactions)
this.router.get('/transactions/:address/:allTxs', this.fulcrumController.getTransactions)
this.router.post('/transactions', this.fulcrumController.transactionsBulk)
this.router.get('/unconfirmed/:address', this.fulcrumController.getMempool)
this.router.post('/unconfirmed', this.fulcrumController.mempoolBulk)
app.use(this.baseUrl, this.router)
}
}
export default FulcrumRouter
@@ -0,0 +1,553 @@
/*
REST API Controller for the /full-node/blockchain routes.
*/
import wlogger from '../../../../adapters/wlogger.js'
class BlockchainRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Blockchain REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.blockchain) {
throw new Error(
'Instance of Blockchain use cases required when instantiating Blockchain REST Controller.'
)
}
this.blockchainUseCases = this.useCases.blockchain
// Bind functions
this.root = this.root.bind(this)
this.getBestBlockHash = this.getBestBlockHash.bind(this)
this.getBlockchainInfo = this.getBlockchainInfo.bind(this)
this.getBlockCount = this.getBlockCount.bind(this)
this.getBlockHeaderSingle = this.getBlockHeaderSingle.bind(this)
this.getBlockHeaderBulk = this.getBlockHeaderBulk.bind(this)
this.getChainTips = this.getChainTips.bind(this)
this.getDifficulty = this.getDifficulty.bind(this)
this.getMempoolEntrySingle = this.getMempoolEntrySingle.bind(this)
this.getMempoolEntryBulk = this.getMempoolEntryBulk.bind(this)
this.getMempoolAncestorsSingle = this.getMempoolAncestorsSingle.bind(this)
this.getMempoolInfo = this.getMempoolInfo.bind(this)
this.getRawMempool = this.getRawMempool.bind(this)
this.getTxOut = this.getTxOut.bind(this)
this.getTxOutPost = this.getTxOutPost.bind(this)
this.getTxOutProofSingle = this.getTxOutProofSingle.bind(this)
this.getTxOutProofBulk = this.getTxOutProofBulk.bind(this)
this.verifyTxOutProofSingle = this.verifyTxOutProofSingle.bind(this)
this.verifyTxOutProofBulk = this.verifyTxOutProofBulk.bind(this)
this.getBlock = this.getBlock.bind(this)
this.getBlockHash = this.getBlockHash.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/full-node/blockchain/ Service status
* @apiName BlockchainRoot
* @apiGroup Blockchain
*
* @apiDescription Returns the status of the blockchain service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'blockchain' })
}
/**
* @api {get} /v6/full-node/blockchain/getBestBlockHash Get best block hash
* @apiName GetBestBlockHash
* @apiGroup Blockchain
* @apiDescription Returns the hash of the best (tip) block in the longest block chain.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/blockchain/getBestBlockHash" -H "accept: application/json"
*
* @apiSuccess {String} bestBlockHash Hash of the best block
*/
async getBestBlockHash (req, res) {
try {
const result = await this.blockchainUseCases.getBestBlockHash()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getBlockchainInfo Get blockchain info
* @apiName GetBlockchainInfo
* @apiGroup Blockchain
* @apiDescription Returns various state info regarding blockchain processing.
*/
async getBlockchainInfo (req, res) {
try {
const result = await this.blockchainUseCases.getBlockchainInfo()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getBlockCount Get block count
* @apiName GetBlockCount
* @apiGroup Blockchain
* @apiDescription Returns the number of blocks in the longest blockchain.
*/
async getBlockCount (req, res) {
try {
const result = await this.blockchainUseCases.getBlockCount()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getBlockHeader/:hash Get single block header
* @apiName GetSingleBlockHeader
* @apiGroup Blockchain
* @apiDescription Returns serialized block header data.
*
* @apiParam {String} hash Block hash
* @apiParam {Boolean} verbose Return verbose data (default false)
*/
async getBlockHeaderSingle (req, res) {
try {
const hash = req.params.hash
if (!hash) {
return res.status(400).json({ error: 'hash can not be empty' })
}
const verbose = req.query.verbose?.toString() === 'true'
const result = await this.blockchainUseCases.getBlockHeader({ hash, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/getBlockHeader Get multiple block headers
* @apiName GetBulkBlockHeader
* @apiGroup Blockchain
* @apiDescription Returns serialized block header data for multiple hashes.
*
* @apiParam {String[]} hashes Block hashes
* @apiParam {Boolean} verbose Return verbose data (default false)
*/
async getBlockHeaderBulk (req, res) {
try {
const hashes = req.body.hashes
const verbose = !!req.body.verbose
if (!Array.isArray(hashes)) {
return res.status(400).json({
error: 'hashes needs to be an array. Use GET for single hash.'
})
}
if (!this.adapters.fullNode.validateArraySize(hashes.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
for (const hash of hashes) {
if (!hash || hash.length !== 64) {
return res.status(400).json({ error: `This is not a hash: ${hash}` })
}
}
const result = await this.blockchainUseCases.getBlockHeaders({ hashes, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getChainTips Get chain tips
* @apiName GetChainTips
* @apiGroup Blockchain
* @apiDescription Returns information about known tips in the block tree.
*/
async getChainTips (req, res) {
try {
const result = await this.blockchainUseCases.getChainTips()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getDifficulty Get difficulty
* @apiName GetDifficulty
* @apiGroup Blockchain
* @apiDescription Returns the current difficulty value.
*/
async getDifficulty (req, res) {
try {
const result = await this.blockchainUseCases.getDifficulty()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getMempoolEntry/:txid Get single mempool entry
* @apiName GetMempoolEntry
* @apiGroup Blockchain
* @apiDescription Returns mempool data for a transaction.
*/
async getMempoolEntrySingle (req, res) {
try {
const txid = req.params.txid
if (!txid) {
return res.status(400).json({ error: 'txid can not be empty' })
}
const result = await this.blockchainUseCases.getMempoolEntry({ txid })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/getMempoolEntry Get bulk mempool entry
* @apiName GetMempoolEntryBulk
* @apiGroup Blockchain
* @apiDescription Returns mempool data for multiple transactions.
*/
async getMempoolEntryBulk (req, res) {
try {
const txids = req.body.txids
if (!Array.isArray(txids)) {
return res.status(400).json({
error: 'txids needs to be an array. Use GET for single txid.'
})
}
if (!this.adapters.fullNode.validateArraySize(txids.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
for (const txid of txids) {
if (!txid || txid.length !== 64) {
return res.status(400).json({ error: 'This is not a txid' })
}
}
const result = await this.blockchainUseCases.getMempoolEntries({ txids })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getMempoolAncestors/:txid Get mempool ancestors
* @apiName GetMempoolAncestors
* @apiGroup Blockchain
* @apiDescription Returns mempool ancestor data for a transaction.
*/
async getMempoolAncestorsSingle (req, res) {
try {
const txid = req.params.txid
if (!txid) {
return res.status(400).json({ error: 'txid can not be empty' })
}
let verbose = false
if (req.query.verbose && req.query.verbose.toString() === 'true') {
verbose = true
}
const result = await this.blockchainUseCases.getMempoolAncestors({ txid, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getMempoolInfo Get mempool info
* @apiName GetMempoolInfo
* @apiGroup Blockchain
* @apiDescription Returns details on the state of the mempool.
*/
async getMempoolInfo (req, res) {
try {
const result = await this.blockchainUseCases.getMempoolInfo()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getRawMempool Get raw mempool
* @apiName GetRawMempool
* @apiGroup Blockchain
* @apiDescription Returns all transaction ids in the mempool.
*
* @apiParam {Boolean} verbose Return verbose data (default false)
*/
async getRawMempool (req, res) {
try {
const verbose = req.query.verbose === 'true'
const result = await this.blockchainUseCases.getRawMempool({ verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getTxOut/:txid/:n Get transaction output
* @apiName GetTxOut
* @apiGroup Blockchain
* @apiDescription Returns details about an unspent transaction output.
*/
async getTxOut (req, res) {
try {
const txid = req.params.txid
if (!txid) {
return res.status(400).json({ error: 'txid can not be empty' })
}
const nRaw = req.params.n
if (nRaw === undefined || nRaw === '') {
return res.status(400).json({ error: 'n can not be empty' })
}
const n = parseInt(nRaw)
const includeMempool = req.query.includeMempool === 'true'
const result = await this.blockchainUseCases.getTxOut({
txid,
n,
includeMempool
})
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/getTxOut Validate a UTXO
* @apiName GetTxOutPost
* @apiGroup Blockchain
* @apiDescription Returns details about an unspent transaction output.
*/
async getTxOutPost (req, res) {
try {
const txid = req.body.txid
if (!txid) {
return res.status(400).json({ error: 'txid can not be empty' })
}
const voutRaw = req.body.vout
if (voutRaw === undefined || voutRaw === '') {
return res.status(400).json({ error: 'vout can not be empty' })
}
const n = parseInt(voutRaw)
const mempool = req.body.mempool !== undefined ? !!req.body.mempool : true
const result = await this.blockchainUseCases.getTxOut({
txid,
n,
includeMempool: mempool
})
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getTxOutProof/:txid Get TxOut proof
* @apiName GetTxOutProofSingle
* @apiGroup Blockchain
* @apiDescription Returns a hex-encoded proof that the transaction was included in a block.
*/
async getTxOutProofSingle (req, res) {
try {
const txid = req.params.txid
if (!txid) {
return res.status(400).json({ error: 'txid can not be empty' })
}
const result = await this.blockchainUseCases.getTxOutProof({ txid })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/getTxOutProof Get TxOut proofs
* @apiName GetTxOutProofBulk
* @apiGroup Blockchain
* @apiDescription Returns hex-encoded proofs for transactions.
*/
async getTxOutProofBulk (req, res) {
try {
const txids = req.body.txids
if (!Array.isArray(txids)) {
return res.status(400).json({
error: 'txids needs to be an array. Use GET for single txid.'
})
}
if (!this.adapters.fullNode.validateArraySize(txids.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
for (const txid of txids) {
if (!txid || txid.length !== 64) {
return res.status(400).json({
error: `Invalid txid. Double check your txid is valid: ${txid}`
})
}
}
const result = await this.blockchainUseCases.getTxOutProofs({ txids })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/verifyTxOutProof/:proof Verify TxOut proof
* @apiName VerifyTxOutProofSingle
* @apiGroup Blockchain
* @apiDescription Verifies a hex-encoded proof was included in a block.
*/
async verifyTxOutProofSingle (req, res) {
try {
const proof = req.params.proof
if (!proof) {
return res.status(400).json({ error: 'proof can not be empty' })
}
const result = await this.blockchainUseCases.verifyTxOutProof({ proof })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/verifyTxOutProof Verify TxOut proofs
* @apiName VerifyTxOutProofBulk
* @apiGroup Blockchain
* @apiDescription Verifies hex-encoded proofs were included in blocks.
*/
async verifyTxOutProofBulk (req, res) {
try {
const proofs = req.body.proofs
if (!Array.isArray(proofs)) {
return res.status(400).json({
error: 'proofs needs to be an array. Use GET for single proof.'
})
}
if (!this.adapters.fullNode.validateArraySize(proofs.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
for (const proof of proofs) {
if (!proof) {
return res.status(400).json({ error: `proof can not be empty: ${proof}` })
}
}
const result = await this.blockchainUseCases.verifyTxOutProofs({ proofs })
const flattened = result.map(entry => Array.isArray(entry) ? entry[0] : entry)
return res.status(200).json(flattened)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/blockchain/getBlock Get block details
* @apiName GetBlock
* @apiGroup Blockchain
* @apiDescription Returns block details for a hash.
*/
async getBlock (req, res) {
try {
const blockhash = req.body.blockhash
if (!blockhash) {
return res.status(400).json({ error: 'blockhash can not be empty' })
}
let verbosity = req.body.verbosity
if (verbosity === undefined || verbosity === null) {
verbosity = 1
}
const result = await this.blockchainUseCases.getBlock({
blockhash,
verbosity
})
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/blockchain/getBlockHash/:height Get block hash
* @apiName GetBlockHash
* @apiGroup Blockchain
* @apiDescription Returns the hash of a block by height.
*/
async getBlockHash (req, res) {
try {
const heightRaw = req.params.height
if (!heightRaw) {
return res.status(400).json({ error: 'height can not be empty' })
}
const height = parseInt(heightRaw)
const result = await this.blockchainUseCases.getBlockHash({ height })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in BlockchainRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default BlockchainRESTController
@@ -0,0 +1,70 @@
/*
REST API router for /full-node/blockchain routes.
*/
import express from 'express'
import BlockchainRESTController from './controller.js'
class BlockchainRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Blockchain REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Blockchain REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.blockchainController = new BlockchainRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/full-node/blockchain`
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.blockchainController.root)
this.router.get('/getBestBlockHash', this.blockchainController.getBestBlockHash)
this.router.get('/getBlockchainInfo', this.blockchainController.getBlockchainInfo)
this.router.get('/getBlockCount', this.blockchainController.getBlockCount)
this.router.get('/getBlockHeader/:hash', this.blockchainController.getBlockHeaderSingle)
this.router.post('/getBlockHeader', this.blockchainController.getBlockHeaderBulk)
this.router.get('/getChainTips', this.blockchainController.getChainTips)
this.router.get('/getDifficulty', this.blockchainController.getDifficulty)
this.router.get('/getMempoolEntry/:txid', this.blockchainController.getMempoolEntrySingle)
this.router.post('/getMempoolEntry', this.blockchainController.getMempoolEntryBulk)
this.router.get('/getMempoolAncestors/:txid', this.blockchainController.getMempoolAncestorsSingle)
this.router.get('/getMempoolInfo', this.blockchainController.getMempoolInfo)
this.router.get('/getRawMempool', this.blockchainController.getRawMempool)
this.router.get('/getTxOut/:txid/:n', this.blockchainController.getTxOut)
this.router.post('/getTxOut', this.blockchainController.getTxOutPost)
this.router.get('/getTxOutProof/:txid', this.blockchainController.getTxOutProofSingle)
this.router.post('/getTxOutProof', this.blockchainController.getTxOutProofBulk)
this.router.get('/verifyTxOutProof/:proof', this.blockchainController.verifyTxOutProofSingle)
this.router.post('/verifyTxOutProof', this.blockchainController.verifyTxOutProofBulk)
this.router.post('/getBlock', this.blockchainController.getBlock)
this.router.get('/getBlockHash/:height', this.blockchainController.getBlockHash)
app.use(this.baseUrl, this.router)
}
}
export default BlockchainRouter
@@ -0,0 +1,68 @@
/*
REST API Controller for the /full-node/control routes.
*/
import wlogger from '../../../../adapters/wlogger.js'
class ControlRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Control REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.control) {
throw new Error(
'Instance of Control use cases required when instantiating Control REST Controller.'
)
}
this.controlUseCases = this.useCases.control
this.root = this.root.bind(this)
this.getNetworkInfo = this.getNetworkInfo.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/full-node/control/ Service status
* @apiName ControlRoot
* @apiGroup Control
*
* @apiDescription Returns the status of the control service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'control' })
}
/**
* @api {get} /v6/full-node/control/getNetworkInfo Get Network Info
* @apiName GetNetworkInfo
* @apiGroup Control
* @apiDescription RPC call that gets basic full node information.
*/
async getNetworkInfo (req, res) {
try {
const result = await this.controlUseCases.getNetworkInfo()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in ControlRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default ControlRESTController
@@ -0,0 +1,51 @@
/*
REST API router for /full-node/control routes.
*/
import express from 'express'
import ControlRESTController from './controller.js'
class ControlRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Control REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Control REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.controlController = new ControlRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/full-node/control`
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.controlController.root)
this.router.get('/getNetworkInfo', this.controlController.getNetworkInfo)
app.use(this.baseUrl, this.router)
}
}
export default ControlRouter
@@ -0,0 +1,90 @@
/*
REST API Controller for the /full-node/dsproof routes.
*/
import wlogger from '../../../../adapters/wlogger.js'
class DSProofRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating DSProof REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.dsproof) {
throw new Error(
'Instance of DSProof use cases required when instantiating DSProof REST Controller.'
)
}
this.dsproofUseCases = this.useCases.dsproof
this.root = this.root.bind(this)
this.getDSProof = this.getDSProof.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/full-node/dsproof/ Service status
* @apiName DSProofRoot
* @apiGroup DSProof
*
* @apiDescription Returns the status of the dsproof service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'dsproof' })
}
/**
* @api {get} /v6/full-node/dsproof/getDSProof/:txid Get Double-Spend Proof
* @apiName GetDSProof
* @apiGroup DSProof
* @apiDescription Get information for a double-spend proof.
*
* @apiParam {String} txid Transaction ID
* @apiParam {String} verbose Verbose level (`false`, `true`) for compatibility with legacy API
*/
async getDSProof (req, res) {
try {
const txid = req.params.txid
if (!txid) {
return res.status(400).json({
success: false,
error: 'txid can not be empty'
})
}
if (txid.length !== 64) {
return res.status(400).json({
success: false,
error: `txid must be of length 64 (not ${txid.length})`
})
}
let verbose = 2
if (req.query.verbose === 'true') verbose = 3
const result = await this.dsproofUseCases.getDSProof({ txid, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in DSProofRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default DSProofRESTController
@@ -0,0 +1,51 @@
/*
REST API router for /full-node/dsproof routes.
*/
import express from 'express'
import DSProofRESTController from './controller.js'
class DSProofRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating DSProof REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating DSProof REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.dsproofController = new DSProofRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/full-node/dsproof`
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.dsproofController.root)
this.router.get('/getDSProof/:txid', this.dsproofController.getDSProof)
app.use(this.baseUrl, this.router)
}
}
export default DSProofRouter
@@ -0,0 +1,99 @@
/*
REST API Controller for the /full-node/mining routes.
*/
import wlogger from '../../../../adapters/wlogger.js'
class MiningRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Mining REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.mining) {
throw new Error(
'Instance of Mining use cases required when instantiating Mining REST Controller.'
)
}
this.miningUseCases = this.useCases.mining
// Bind functions
this.root = this.root.bind(this)
this.getMiningInfo = this.getMiningInfo.bind(this)
this.getNetworkHashPS = this.getNetworkHashPS.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/full-node/mining/ Service status
* @apiName MiningRoot
* @apiGroup Mining
*
* @apiDescription Returns the status of the mining service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'mining' })
}
/**
* @api {get} /v6/full-node/mining/getMiningInfo Get Mining Info
* @apiName GetMiningInfo
* @apiGroup Mining
* @apiDescription Returns a json object containing mining-related information.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/mining/getMiningInfo" -H "accept: application/json"
*/
async getMiningInfo (req, res) {
try {
const result = await this.miningUseCases.getMiningInfo()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/mining/getNetworkHashPS Get Estimated network hashes per second
* @apiName GetNetworkHashPS
* @apiGroup Mining
* @apiDescription Returns the estimated network hashes per second based on the last n blocks. Pass in [nblocks] to override # of blocks, -1 specifies since last difficulty change. Pass in [height] to estimate the network speed at the time when a certain block was found.
*
* @apiParam {Number} nblocks Number of blocks to use for estimation (default: 120)
* @apiParam {Number} height Block height to estimate at (default: -1)
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/mining/getNetworkHashPS?nblocks=120&height=-1" -H "accept: application/json"
*/
async getNetworkHashPS (req, res) {
try {
let nblocks = 120 // Default
let height = -1 // Default
if (req.query.nblocks) nblocks = parseInt(req.query.nblocks)
if (req.query.height) height = parseInt(req.query.height)
const result = await this.miningUseCases.getNetworkHashPS({ nblocks, height })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in MiningRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default MiningRESTController
@@ -0,0 +1,52 @@
/*
REST API router for /full-node/mining routes.
*/
import express from 'express'
import MiningRESTController from './controller.js'
class MiningRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Mining REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Mining REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.miningController = new MiningRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/full-node/mining`
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.miningController.root)
this.router.get('/getMiningInfo', this.miningController.getMiningInfo)
this.router.get('/getNetworkHashPS', this.miningController.getNetworkHashPS)
app.use(this.baseUrl, this.router)
}
}
export default MiningRouter
@@ -0,0 +1,333 @@
/*
REST API Controller for the /full-node/rawtransactions routes.
*/
import wlogger from '../../../../adapters/wlogger.js'
class RawTransactionsRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating RawTransactions REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.rawtransactions) {
throw new Error(
'Instance of RawTransactions use cases required when instantiating RawTransactions REST Controller.'
)
}
this.rawtransactionsUseCases = this.useCases.rawtransactions
// Bind functions
this.root = this.root.bind(this)
this.decodeRawTransactionSingle = this.decodeRawTransactionSingle.bind(this)
this.decodeRawTransactionBulk = this.decodeRawTransactionBulk.bind(this)
this.decodeScriptSingle = this.decodeScriptSingle.bind(this)
this.decodeScriptBulk = this.decodeScriptBulk.bind(this)
this.getRawTransactionSingle = this.getRawTransactionSingle.bind(this)
this.getRawTransactionBulk = this.getRawTransactionBulk.bind(this)
this.sendRawTransactionSingle = this.sendRawTransactionSingle.bind(this)
this.sendRawTransactionBulk = this.sendRawTransactionBulk.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/full-node/rawtransactions/ Service status
* @apiName RawTransactionsRoot
* @apiGroup RawTransactions
*
* @apiDescription Returns the status of the rawtransactions service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'rawtransactions' })
}
/**
* @api {get} /v6/full-node/rawtransactions/decodeRawTransaction/:hex Decode Single Raw Transaction
* @apiName DecodeSingleRawTransaction
* @apiGroup RawTransactions
* @apiDescription Return a JSON object representing the serialized, hex-encoded transaction.
*
* @apiParam {String} hex Hex-encoded transaction
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/rawtransactions/decodeRawTransaction/02000000010e991f7ccec410f27d333f737f149b5d3be6728687da81072e638aed0063a176010000006b483045022100cd20443b0af090053450bc4ab00d563d4ac5955bb36e0135b00b8a96a19f233302205047f2c70a08c6ef4b76f2d198b33a31d17edfaa7e1e9e865894da0d396009354121024d4e7f522f67105b7bf5f9dbe557e7b2244613fdfcd6fe09304f93877328f6beffffffff02a0860100000000001976a9140ee020c07f39526ac5505c54fa1ab98490979b8388acb5f0f70b000000001976a9143a9b2b0c12fe722fcf653b6ef5dcc38732d6ff5188ac00000000" -H "accept: application/json"
*/
async decodeRawTransactionSingle (req, res) {
try {
const hex = req.params.hex
if (!hex || hex === '') {
return res.status(400).json({ error: 'hex can not be empty' })
}
const result = await this.rawtransactionsUseCases.decodeRawTransaction({ hex })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/rawtransactions/decodeRawTransaction Decode Bulk Raw Transactions
* @apiName DecodeBulkRawTransactions
* @apiGroup RawTransactions
* @apiDescription Return bulk hex encoded transaction.
*
* @apiParam {String[]} hexes Array of hex-encoded transactions
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v6/full-node/rawtransactions/decodeRawTransaction" -H "accept: application/json" -H "Content-Type: application/json" -d '{"hexes":["01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"]}'
*/
async decodeRawTransactionBulk (req, res) {
try {
const hexes = req.body.hexes
if (!Array.isArray(hexes)) {
return res.status(400).json({ error: 'hexes must be an array' })
}
if (!this.adapters.fullNode.validateArraySize(hexes.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
// Validate each element in the array
for (const hex of hexes) {
if (!hex || hex === '') {
return res.status(400).json({ error: 'Encountered empty hex' })
}
}
const result = await this.rawtransactionsUseCases.decodeRawTransactions({ hexes })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/rawtransactions/decodeScript/:hex Decode Single Script
* @apiName DecodeSingleScript
* @apiGroup RawTransactions
* @apiDescription Decode a hex-encoded script.
*
* @apiParam {String} hex Hex-encoded script
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/rawtransactions/decodeScript/4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16" -H "accept: application/json"
*/
async decodeScriptSingle (req, res) {
try {
const hex = req.params.hex
if (!hex || hex === '') {
return res.status(400).json({ error: 'hex can not be empty' })
}
const result = await this.rawtransactionsUseCases.decodeScript({ hex })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/rawtransactions/decodeScript Bulk Decode Script
* @apiName DecodeBulkScript
* @apiGroup RawTransactions
* @apiDescription Decode multiple hex-encoded scripts.
*
* @apiParam {String[]} hexes Array of hex-encoded scripts
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v6/full-node/rawtransactions/decodeScript" -H "accept: application/json" -H "Content-Type: application/json" -d '{"hexes":["01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"]}'
*/
async decodeScriptBulk (req, res) {
try {
const hexes = req.body.hexes
if (!Array.isArray(hexes)) {
return res.status(400).json({ error: 'hexes must be an array' })
}
if (!this.adapters.fullNode.validateArraySize(hexes.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
// Validate each hex in the array
for (const hex of hexes) {
if (!hex || hex === '') {
return res.status(400).json({ error: 'Encountered empty hex' })
}
}
const result = await this.rawtransactionsUseCases.decodeScripts({ hexes })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/rawtransactions/getRawTransaction/:txid Get Raw Transaction
* @apiName GetRawTransaction
* @apiGroup RawTransactions
* @apiDescription Return the raw transaction data. If verbose is 'true', returns an Object with information about 'txid'. If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.
*
* @apiParam {String} txid Transaction ID
* @apiParam {Boolean} verbose Return verbose data (default false)
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/rawtransactions/getRawTransaction/fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33?verbose=true" -H "accept: application/json"
*/
async getRawTransactionSingle (req, res) {
try {
const txid = req.params.txid
const verbose = req.query.verbose === 'true'
if (!txid || txid === '') {
return res.status(400).json({ error: 'txid can not be empty' })
}
if (txid.length !== 64) {
return res.status(400).json({
error: `parameter 1 must be of length 64 (not ${txid.length})`
})
}
const result = await this.rawtransactionsUseCases.getRawTransactionWithHeight({ txid, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/rawtransactions/getRawTransaction Get Bulk Raw Transactions
* @apiName GetBulkRawTransactions
* @apiGroup RawTransactions
* @apiDescription Return the raw transaction data for multiple transactions. If verbose is 'true', returns an Object with information about 'txid'. If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.
*
* @apiParam {String[]} txids Array of transaction IDs
* @apiParam {Boolean} verbose Return verbose data (default false)
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v6/full-node/rawtransactions/getRawTransaction" -H "accept: application/json" -H "Content-Type: application/json" -d '{"txids":["a5f972572ee1753e2fd2457dd61ce5f40fa2f8a30173d417e49feef7542c96a1","5165dc531aad05d1149bb0f0d9b7bda99c73e2f05e314bcfb5b4bb9ca5e1af5e"],"verbose":true}'
*/
async getRawTransactionBulk (req, res) {
try {
const txids = req.body.txids
const verbose = !!req.body.verbose
if (!Array.isArray(txids)) {
return res.status(400).json({ error: 'txids must be an array' })
}
if (!this.adapters.fullNode.validateArraySize(txids.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
// Validate each txid in the array
for (const txid of txids) {
if (!txid || txid === '') {
return res.status(400).json({ error: 'Encountered empty TXID' })
}
if (txid.length !== 64) {
return res.status(400).json({
error: `parameter 1 must be of length 64 (not ${txid.length})`
})
}
}
const result = await this.rawtransactionsUseCases.getRawTransactions({ txids, verbose })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/full-node/rawtransactions/sendRawTransaction/:hex Send Single Raw Transaction
* @apiName SendSingleRawTransaction
* @apiGroup RawTransactions
* @apiDescription Submits single raw transaction (serialized, hex-encoded) to local node and network.
*
* @apiParam {String} hex Hex-encoded transaction
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/full-node/rawtransactions/sendRawTransaction/01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" -H "accept: application/json"
*/
async sendRawTransactionSingle (req, res) {
try {
const hex = req.params.hex
if (typeof hex !== 'string') {
return res.status(400).json({ error: 'hex must be a string' })
}
if (hex === '') {
return res.status(400).json({ error: 'Encountered empty hex' })
}
const result = await this.rawtransactionsUseCases.sendRawTransaction({ hex })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/full-node/rawtransactions/sendRawTransaction Send Bulk Raw Transactions
* @apiName SendBulkRawTransactions
* @apiGroup RawTransactions
* @apiDescription Submits multiple raw transaction (serialized, hex-encoded) to local node and network.
*
* @apiParam {String[]} hexes Array of hex-encoded transactions
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v6/full-node/rawtransactions/sendRawTransaction" -H "accept: application/json" -H "Content-Type: application/json" -d '{"hexes":["01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"]}'
*/
async sendRawTransactionBulk (req, res) {
try {
const hexes = req.body.hexes
if (!Array.isArray(hexes)) {
return res.status(400).json({ error: 'hex must be an array' })
}
if (!this.adapters.fullNode.validateArraySize(hexes.length)) {
return res.status(400).json({ error: 'Array too large.' })
}
// Validate each element
for (const hex of hexes) {
if (hex === '') {
return res.status(400).json({ error: 'Encountered empty hex' })
}
}
const result = await this.rawtransactionsUseCases.sendRawTransactions({ hexes })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in RawTransactionsRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default RawTransactionsRESTController
@@ -0,0 +1,58 @@
/*
REST API router for /full-node/rawtransactions routes.
*/
import express from 'express'
import RawTransactionsRESTController from './controller.js'
class RawTransactionsRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating RawTransactions REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating RawTransactions REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.rawtransactionsController = new RawTransactionsRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/full-node/rawtransactions`
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.rawtransactionsController.root)
this.router.get('/decodeRawTransaction/:hex', this.rawtransactionsController.decodeRawTransactionSingle)
this.router.post('/decodeRawTransaction', this.rawtransactionsController.decodeRawTransactionBulk)
this.router.get('/decodeScript/:hex', this.rawtransactionsController.decodeScriptSingle)
this.router.post('/decodeScript', this.rawtransactionsController.decodeScriptBulk)
this.router.get('/getRawTransaction/:txid', this.rawtransactionsController.getRawTransactionSingle)
this.router.post('/getRawTransaction', this.rawtransactionsController.getRawTransactionBulk)
this.router.get('/sendRawTransaction/:hex', this.rawtransactionsController.sendRawTransactionSingle)
this.router.post('/sendRawTransaction', this.rawtransactionsController.sendRawTransactionBulk)
app.use(this.baseUrl, this.router)
}
}
export default RawTransactionsRouter
+47 -4
View File
@@ -7,6 +7,15 @@
// Local libraries
// import EventRouter from './event/index.js'
// import ReqRouter from './req/index.js'
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'
import RawTransactionsRouter from './full-node/rawtransactions/router.js'
import SlpRouter from './slp/router.js'
import config from '../../config/index.js'
class RESTControllers {
@@ -25,6 +34,12 @@ class RESTControllers {
)
}
// Allow overriding the API prefix for testing, default to v6.
this.apiPrefix = localConfig.apiPrefix || '/v6'
if (this.apiPrefix.length > 1 && this.apiPrefix.endsWith('/')) {
this.apiPrefix = this.apiPrefix.slice(0, -1)
}
// Bind 'this' object to all subfunctions.
this.attachRESTControllers = this.attachRESTControllers.bind(this)
@@ -33,10 +48,11 @@ class RESTControllers {
}
attachRESTControllers (app) {
// const dependencies = {
// adapters: this.adapters,
// useCases: this.useCases
// }
const dependencies = {
adapters: this.adapters,
useCases: this.useCases,
apiPrefix: this.apiPrefix
}
// Attach the REST API Controllers associated with the /event route
// const eventRouter = new EventRouter(dependencies)
@@ -45,6 +61,33 @@ class RESTControllers {
// Attach the REST API Controllers associated with the /req route
// const reqRouter = new ReqRouter(dependencies)
// reqRouter.attach(app)
const blockchainRouter = new BlockchainRouter(dependencies)
blockchainRouter.attach(app)
const controlRouter = new ControlRouter(dependencies)
controlRouter.attach(app)
const dsproofRouter = new DSProofRouter(dependencies)
dsproofRouter.attach(app)
const encryptionRouter = new EncryptionRouter(dependencies)
encryptionRouter.attach(app)
const fulcrumRouter = new FulcrumRouter(dependencies)
fulcrumRouter.attach(app)
const miningRouter = new MiningRouter(dependencies)
miningRouter.attach(app)
const priceRouter = new PriceRouter(dependencies)
priceRouter.attach(app)
const rawtransactionsRouter = new RawTransactionsRouter(dependencies)
rawtransactionsRouter.attach(app)
const slpRouter = new SlpRouter(dependencies)
slpRouter.attach(app)
}
}
@@ -0,0 +1,121 @@
/*
REST API Controller for the /price routes.
*/
import wlogger from '../../../adapters/wlogger.js'
class PriceRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Price REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.price) {
throw new Error(
'Instance of Price use cases required when instantiating Price REST Controller.'
)
}
this.priceUseCases = this.useCases.price
// Bind functions
this.root = this.root.bind(this)
this.getBCHUSD = this.getBCHUSD.bind(this)
this.getPsffppWritePrice = this.getPsffppWritePrice.bind(this)
this.getPsfLiquidityPrice = this.getPsfLiquidityPrice.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/price/ Service status
* @apiName PriceRoot
* @apiGroup Price
*
* @apiDescription Returns the status of the price service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'price' })
}
/**
* @api {get} /v6/price/bchusd Get the USD price of BCH
* @apiName GetBCHUSD
* @apiGroup Price
* @apiDescription Get the USD price of BCH from Coinex.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/price/bchusd" -H "accept: application/json"
*
* @apiSuccess {Number} usd The USD price of BCH
*/
async getBCHUSD (req, res) {
try {
const price = await this.priceUseCases.getBCHUSD()
return res.status(200).json({ usd: price })
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/price/psffpp Get the PSF price for writing to the PSFFPP
* @apiName GetPsffppWritePrice
* @apiGroup Price
* @apiDescription Get the price to pin 1MB of content to the PSFFPP pinning
* network on IPFS. The price is denominated in PSF tokens.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/price/psffpp" -H "accept: application/json"
*
* @apiSuccess {Number} writePrice The price in PSF tokens to write 1MB to PSFFPP
*/
async getPsffppWritePrice (req, res) {
try {
const writePrice = await this.priceUseCases.getPsffppWritePrice()
return res.status(200).json({ writePrice })
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {get} /v6/price/psf PSF token liquidity spot price (proxied)
* @apiName GetPsfLiquidityPrice
* @apiGroup Price
* @apiDescription Proxies GET /price from the PSF token liquidity app when
* `PSF_LIQUIDITY_PROXY_ENABLED` is true. Returns 503 when the proxy is disabled.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v6/price/psf" -H "accept: application/json"
*
* @apiSuccess {Number} usdPerBCH USD price per 1 BCH
* @apiSuccess {Number} bchBalance BCH balance (liquidity app)
* @apiSuccess {Number} tokenBalance Effective PSF token balance
* @apiSuccess {Number} usdPerToken USD price per 1 PSF token
*/
async getPsfLiquidityPrice (req, res) {
try {
const payload = await this.priceUseCases.getPsfLiquidityPrice()
return res.status(200).json(payload)
} catch (err) {
return this.handleError(err, res)
}
}
handleError (err, res) {
wlogger.error('Error in PriceRESTController:', err)
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default PriceRESTController
+53
View File
@@ -0,0 +1,53 @@
/*
REST API router for /price routes.
*/
import express from 'express'
import PriceRESTController from './controller.js'
class PriceRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Price REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Price REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.priceController = new PriceRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/price`
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.priceController.root)
this.router.get('/bchusd', this.priceController.getBCHUSD)
this.router.get('/psffpp', this.priceController.getPsffppWritePrice)
this.router.get('/psf', this.priceController.getPsfLiquidityPrice)
app.use(this.baseUrl, this.router)
}
}
export default PriceRouter
-296
View File
@@ -1,296 +0,0 @@
/*
REST API Controller library for the /req route
*/
// Local libraries
import wlogger from '../../../adapters/wlogger.js'
class ReqRESTControllerLib {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating /req REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating /req REST Controller.'
)
}
// Bind 'this' object to all subfunctions
this.queryEvents = this.queryEvents.bind(this)
this.createSubscription = this.createSubscription.bind(this)
this.closeSubscription = this.closeSubscription.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /req/:subId Query events (stateless)
* @apiPermission public
* @apiName QueryEvents
* @apiGroup Request
*
* @apiDescription Query events from the relay with filters. Returns events immediately. Maps to: ["REQ", <sub_id>, <filters>]
*
* @apiParam {String} subId Subscription ID (unique identifier)
* @apiParam {String} filters JSON-encoded filters object (query parameter)
*
* @apiExample {curl} Example usage:
* curl -X GET "http://localhost:3000/req/sub1?filters=[{\"kinds\":[1],\"limit\":10}]"
*
* @apiSuccess {Array} events Array of Nostr events
*
* @apiError {String} error Error message
*/
async queryEvents (req, res) {
try {
const { subId } = req.params
let filters = req.query.filters
if (!subId) {
return res.status(400).json({
error: 'Subscription ID is required'
})
}
// Parse filters from query string
if (typeof filters === 'string') {
try {
filters = JSON.parse(filters)
} catch (err) {
return res.status(400).json({
error: 'Invalid filters JSON'
})
}
} else if (!filters) {
// If no filters provided, accept filters from query params
filters = {}
if (req.query.kinds) {
filters.kinds = JSON.parse(req.query.kinds)
}
if (req.query.authors) {
filters.authors = JSON.parse(req.query.authors)
}
if (req.query.ids) {
filters.ids = JSON.parse(req.query.ids)
}
if (req.query.limit) {
filters.limit = parseInt(req.query.limit)
}
if (req.query.since) {
filters.since = parseInt(req.query.since)
}
if (req.query.until) {
filters.until = parseInt(req.query.until)
}
}
// Ensure filters is an array (Nostr protocol expects array of filters)
const filtersArray = Array.isArray(filters) ? filters : [filters]
const events = await this.useCases.queryEvents.execute(filtersArray, subId)
return res.status(200).json(events)
} catch (err) {
return this.handleError(err, req, res)
}
}
/**
* @api {post} /req/:subId Create subscription (SSE)
* @apiPermission public
* @apiName CreateSubscription
* @apiGroup Request
*
* @apiDescription Create a subscription for Server-Sent Events. Maps to: ["REQ", <sub_id>, <filters>]
*
* @apiParam {String} subId Subscription ID (unique identifier)
* @apiParam {Object} filters Filters object in request body
*
* @apiExample {json} Example usage:
* {
* "kinds": [1],
* "authors": ["2c7e76c0f8dc1dca9d0197c7d19be580a8d074ccada6a2f6ebe056ae41092e9"]
* }
*
* @apiSuccess {String} message Success message
*
* @apiError {String} error Error message
*/
async createSubscription (req, res) {
try {
const { subId } = req.params
const filters = req.body
if (!subId) {
return res.status(400).json({
error: 'Subscription ID is required'
})
}
if (!filters || (typeof filters === 'object' && Object.keys(filters).length === 0)) {
return res.status(400).json({
error: 'Filters are required'
})
}
// Ensure filters is an array
const filtersArray = Array.isArray(filters) ? filters : [filters]
// Set up Server-Sent Events
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.setHeader('X-Accel-Buffering', 'no') // Disable buffering in nginx
// Track if response is still writable
let isResponseWritable = true
// Helper function to safely write to SSE stream
const safeWrite = (data) => {
if (!isResponseWritable) {
return false
}
try {
if (!res.writable || res.destroyed || res.closed) {
isResponseWritable = false
return false
}
return res.write(data)
} catch (err) {
wlogger.warn(`Error writing to SSE stream for subscription ${subId}:`, err.message)
isResponseWritable = false
return false
}
}
// Handle response stream errors
res.on('error', (err) => {
wlogger.warn(`Response stream error for subscription ${subId}:`, err.message)
isResponseWritable = false
// Clean up subscription on stream error
this.useCases.manageSubscription.closeSubscription(subId).catch(closeErr => {
wlogger.error('Error closing subscription on stream error:', closeErr)
})
})
// Send initial connection message
if (!safeWrite(`data: ${JSON.stringify({ type: 'connected', subscriptionId: subId })}\n\n`)) {
wlogger.warn(`Failed to send initial connection message for subscription ${subId}`)
return res.status(500).json({ error: 'Failed to establish SSE connection' })
}
// Handle events
const onEvent = (event) => {
if (!safeWrite(`data: ${JSON.stringify({ type: 'event', data: event })}\n\n`)) {
wlogger.debug(`Cannot write event to SSE stream for subscription ${subId} - connection may be closed`)
}
}
// Handle EOSE
const onEose = () => {
if (!safeWrite(`data: ${JSON.stringify({ type: 'eose' })}\n\n`)) {
wlogger.debug(`Cannot write EOSE to SSE stream for subscription ${subId} - connection may be closed`)
}
}
// Handle CLOSED
const onClosed = (message) => {
if (safeWrite(`data: ${JSON.stringify({ type: 'closed', message })}\n\n`)) {
try {
if (!res.destroyed && !res.closed) {
res.end()
}
} catch (err) {
wlogger.warn(`Error ending SSE stream for subscription ${subId}:`, err.message)
}
}
isResponseWritable = false
}
// Create subscription
await this.useCases.manageSubscription.createSubscription(
subId,
filtersArray,
onEvent,
onEose,
onClosed
)
// Handle client disconnect
req.on('close', () => {
wlogger.info(`Client disconnected from subscription ${subId}`)
isResponseWritable = false
this.useCases.manageSubscription.closeSubscription(subId).catch(err => {
wlogger.error('Error closing subscription on disconnect:', err)
})
})
// Handle response finish
res.on('finish', () => {
isResponseWritable = false
})
} catch (err) {
return this.handleError(err, req, res)
}
}
/**
* @api {put} /req/:subId Create subscription (SSE) - alternative method
* @apiPermission public
* @apiName CreateSubscriptionPut
* @apiGroup Request
*
* @apiDescription Same as POST /req/:subId - create a subscription for Server-Sent Events
*/
async createSubscriptionPut (req, res) {
return this.createSubscription(req, res)
}
/**
* @api {delete} /req/:subId Close subscription
* @apiPermission public
* @apiName CloseSubscription
* @apiGroup Request
*
* @apiDescription Close an existing subscription. Maps to: ["CLOSE", <sub_id>]
*
* @apiParam {String} subId Subscription ID to close
*
* @apiSuccess {String} message Success message
*
* @apiError {String} error Error message
*/
async closeSubscription (req, res) {
try {
const { subId } = req.params
if (!subId) {
return res.status(400).json({
error: 'Subscription ID is required'
})
}
await this.useCases.manageSubscription.closeSubscription(subId)
return res.status(200).json({
message: `Subscription ${subId} closed successfully`
})
} catch (err) {
return this.handleError(err, req, res)
}
}
handleError (err, req, res) {
wlogger.error('Error in ReqRESTController:', err)
return res.status(500).json({
error: err.message || 'Internal server error'
})
}
}
export default ReqRESTControllerLib
-75
View File
@@ -1,75 +0,0 @@
/*
REST API library for the /req route.
*/
// Public npm libraries.
import express from 'express'
// Local libraries.
import ReqRESTControllerLib from './controller.js'
class ReqRouter {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating Req REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating Req REST Controller.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
// Encapsulate dependencies.
this.reqRESTController = new ReqRESTControllerLib(dependencies)
// Instantiate the router and set the base route.
this.router = express.Router()
}
attach (app) {
if (!app) {
throw new Error(
'Must pass app object when attaching REST API controllers.'
)
}
// Define the routes and attach the controller.
// Handle empty subId case first
this.router.get('/', (req, res) => {
res.status(400).json({
error: 'Subscription ID is required'
})
})
this.router.post('/', (req, res) => {
res.status(400).json({
error: 'Subscription ID is required'
})
})
this.router.delete('/', (req, res) => {
res.status(400).json({
error: 'Subscription ID is required'
})
})
// Routes with subId parameter
this.router.get('/:subId', this.reqRESTController.queryEvents)
this.router.post('/:subId', this.reqRESTController.createSubscription)
this.router.put('/:subId', this.reqRESTController.createSubscriptionPut)
this.router.delete('/:subId', this.reqRESTController.closeSubscription)
// Attach the Controller routes to the Express app.
app.use('/req', this.router)
}
}
export default ReqRouter
+227
View File
@@ -0,0 +1,227 @@
/*
REST API Controller for the /slp routes.
*/
import wlogger from '../../../adapters/wlogger.js'
import BCHJS from '@psf/bch-js'
import config from '../../../config/index.js'
const bchjs = new BCHJS({ restURL: config.restURL })
class SlpRESTController {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating SLP REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases || !this.useCases.slp) {
throw new Error(
'Instance of SLP use cases required when instantiating SLP REST Controller.'
)
}
this.slpUseCases = this.useCases.slp
// Bind functions
this.root = this.root.bind(this)
this.getStatus = this.getStatus.bind(this)
this.getAddress = this.getAddress.bind(this)
this.getTxid = this.getTxid.bind(this)
this.getTokenStats = this.getTokenStats.bind(this)
this.getTokenData = this.getTokenData.bind(this)
this.handleError = this.handleError.bind(this)
}
/**
* @api {get} /v6/slp/ Service status
* @apiName SlpRoot
* @apiGroup SLP
*
* @apiDescription Returns the status of the SLP service.
*
* @apiSuccess {String} status Service identifier
*/
async root (req, res) {
return res.status(200).json({ status: 'psf-slp-indexer' })
}
/**
* Validates and converts an address to cash address format
* @param {string} address - Address to validate and convert
* @returns {string} Cash address
* @throws {Error} If address is invalid or not mainnet
*/
_validateAndConvertAddress (address) {
if (!address) {
throw new Error('address is empty')
}
// Convert legacy to cash address
const cashAddr = bchjs.SLP.Address.toCashAddress(address)
// Ensure it's a valid BCH address
try {
bchjs.SLP.Address.toLegacyAddress(cashAddr)
} catch (err) {
throw new Error(`Invalid BCH address. Double check your address is valid: ${address}`)
}
// Ensure it's mainnet (no testnet support)
const isMainnet = bchjs.Address.isMainnetAddress(cashAddr)
if (!isMainnet) {
throw new Error('Invalid network. Only mainnet addresses are supported.')
}
return cashAddr
}
/**
* @api {get} /v6/slp/status Get indexer status
* @apiName GetStatus
* @apiGroup SLP
* @apiDescription Returns the status of the SLP indexer.
*/
async getStatus (req, res) {
try {
const result = await this.slpUseCases.getStatus()
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/slp/address Get SLP balance for address
* @apiName GetAddress
* @apiGroup SLP
* @apiDescription Returns SLP balance for an address.
*/
async getAddress (req, res) {
try {
const address = req.body.address
if (!address || address === '') {
return res.status(400).json({
success: false,
error: 'address can not be empty'
})
}
// Validate and convert address
const cashAddr = this._validateAndConvertAddress(address)
const result = await this.slpUseCases.getAddress({ address: cashAddr })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/slp/txid Get SLP transaction data
* @apiName GetTxid
* @apiGroup SLP
* @apiDescription Returns SLP transaction data for a TXID.
*/
async getTxid (req, res) {
try {
const txid = req.body.txid
if (!txid || txid === '') {
return res.status(400).json({
success: false,
error: 'txid can not be empty'
})
}
if (txid.length !== 64) {
return res.status(400).json({
success: false,
error: 'This is not a txid'
})
}
const result = await this.slpUseCases.getTxid({ txid })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/slp/token Get token statistics
* @apiName GetTokenStats
* @apiGroup SLP
* @apiDescription Returns statistics for a single SLP token.
*/
async getTokenStats (req, res) {
try {
const tokenId = req.body.tokenId
if (!tokenId || tokenId === '') {
return res.status(400).json({
success: false,
error: 'tokenId can not be empty'
})
}
// Flag to toggle tx history of the token
const withTxHistory = req.body.withTxHistory === true
const result = await this.slpUseCases.getTokenStats({ tokenId, withTxHistory })
return res.status(200).json(result)
} catch (err) {
return this.handleError(err, res)
}
}
/**
* @api {post} /v6/slp/token/data Get token data
* @apiName GetTokenData
* @apiGroup SLP
* @apiDescription Get mutable and immutable data if the token contains them.
*/
async getTokenData (req, res) {
try {
const tokenId = req.body.tokenId
if (!tokenId || tokenId === '') {
return res.status(400).json({
success: false,
error: 'tokenId can not be empty'
})
}
// Flag to toggle tx history of the token
const withTxHistory = req.body.withTxHistory === true
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)
}
}
handleError (err, res) {
const isCommonMissingTxError =
err?.status === 404 &&
typeof err?.message === 'string' &&
err.message.includes('Key not found in database')
if (!isCommonMissingTxError) {
wlogger.error('Error in SlpRESTController:', err)
}
const status = err.status || 500
const message = err.message || 'Internal server error'
return res.status(status).json({ error: message })
}
}
export default SlpRESTController
+55
View File
@@ -0,0 +1,55 @@
/*
REST API router for /slp routes.
*/
import express from 'express'
import SlpRESTController from './controller.js'
class SlpRouter {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating SLP REST Router.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating SLP REST Router.'
)
}
const dependencies = {
adapters: this.adapters,
useCases: this.useCases
}
this.slpController = new SlpRESTController(dependencies)
this.apiPrefix = (localConfig.apiPrefix || '').replace(/\/$/, '')
this.baseUrl = `${this.apiPrefix}/slp`
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.slpController.root)
this.router.get('/status', this.slpController.getStatus)
this.router.post('/address', this.slpController.getAddress)
this.router.post('/txid', this.slpController.getTxid)
this.router.post('/token', this.slpController.getTokenStats)
this.router.post('/token/data', this.slpController.getTokenData)
app.use(this.baseUrl, this.router)
}
}
export default SlpRouter
+1 -1
View File
@@ -23,7 +23,7 @@ class TimerController {
}
// Constants
this.SHUTDOWN_INTERVAL_MS = 10 * 60 * 1000 // 10 minutes in milliseconds
this.SHUTDOWN_INTERVAL_MS = 10 * 60 * 60 * 1000 // 10 hours in milliseconds
this.LIVENESS_CHECK_INTERVAL_MS = 1 * 60 * 1000 // 1 minute in milliseconds
// Handlers
+223
View File
@@ -0,0 +1,223 @@
/*
Build and cache discovery documents from apiDoc-style annotations.
*/
import { readFileSync, existsSync, readdirSync } from 'fs'
import { resolve } from 'path'
import config from '../config/index.js'
import { getX402Settings } from '../config/x402.js'
const BCH_MAINNET_CAIP2 = 'bip122:000000000000000000651ef99cb9fcbe'
const X402_SPEC_VERSION = 2
let cachedDocs = null
function parseApiAnnotations () {
const srcRoot = resolve(process.cwd(), 'src/controllers/rest-api')
const entries = []
const files = walkJsFiles(srcRoot)
for (const file of files) {
const text = readFileSync(file, 'utf8')
const blocks = text.match(/\/\*\*[\s\S]*?\*\//g) || []
for (const block of blocks) {
const endpoint = parseBlock(block)
if (endpoint) entries.push(endpoint)
}
}
return entries
}
function parseBlock (block) {
const methodMatch = block.match(/@api\s+\{([^}]+)\}\s+(\S+)\s+([^\n\r*]+)/)
if (!methodMatch) return null
const method = methodMatch[1].trim().toUpperCase()
const path = methodMatch[2].trim()
const summary = methodMatch[3].trim()
const groupMatch = block.match(/@apiGroup\s+([^\n\r*]+)/)
const descriptionMatch = block.match(/@apiDescription\s+([^\n\r*][\s\S]*?)(?=\n\s*\*\s*@api|\n\s*\*\/)/)
const apiNameMatch = block.match(/@apiName\s+([^\n\r*]+)/)
return {
method,
path,
summary,
group: groupMatch ? groupMatch[1].trim() : 'General',
operationId: apiNameMatch ? apiNameMatch[1].trim() : `${method.toLowerCase()}_${path.replace(/[^\w]/g, '_')}`,
description: descriptionMatch
? descriptionMatch[1].replace(/\n\s*\*\s?/g, ' ').trim()
: summary
}
}
function walkJsFiles (dir) {
const output = []
for (const item of readdirSync(dir, { withFileTypes: true })) {
const fullPath = resolve(dir, item.name)
if (item.isDirectory()) {
output.push(...walkJsFiles(fullPath))
continue
}
if (item.isFile() && fullPath.endsWith('.js')) output.push(fullPath)
}
return output
}
function normalizePaths (endpoints) {
const paths = {}
for (const endpoint of endpoints) {
if (!paths[endpoint.path]) paths[endpoint.path] = {}
const op = {
tags: [endpoint.group],
summary: endpoint.summary,
description: endpoint.description,
operationId: endpoint.operationId,
responses: {
200: {
description: 'Successful response'
},
402: {
description: 'Payment required when x402 is enabled'
}
},
'x-payment-model': 'x402-bch-v2'
}
paths[endpoint.path][endpoint.method.toLowerCase()] = op
}
return paths
}
function buildOpenApi (paths) {
return {
openapi: '3.0.3',
info: {
title: 'psf-bch-api',
version: config.version,
description: 'OpenAPI projection generated from apiDoc annotations'
},
servers: [
{
url: '/'
}
],
paths
}
}
function buildSwagger (paths) {
return {
swagger: '2.0',
info: {
title: 'psf-bch-api',
version: config.version,
description: 'Swagger projection generated from apiDoc annotations'
},
basePath: '/',
schemes: ['https', 'http'],
paths
}
}
function buildLlms (endpoints) {
const lines = [
'# psf-bch-api',
'',
'> REST API proxy to Bitcoin Cash infrastructure with optional x402-bch monetized access.',
'',
'## Discovery',
'- [OpenAPI document](/openapi.json): OpenAPI 3 projection generated from apiDoc annotations.',
'- [Swagger document](/swagger.json): Swagger 2.0 compatibility projection.',
'- [x402 manifest](/.well-known/x402): x402-bch v2 payment requirement discovery.',
'- [Agent manifest](/.well-known/agent.json): draft agent capability surface.',
'',
'## API Groups'
]
const seen = new Set()
for (const endpoint of endpoints) {
if (seen.has(endpoint.group)) continue
seen.add(endpoint.group)
lines.push(`- ${endpoint.group}`)
}
lines.push('', '## Optional', '- [Human docs](/): apiDoc HTML documentation root.')
return lines.join('\n')
}
function buildAgent (endpoints) {
const x402 = getX402Settings()
const actions = endpoints.map(endpoint => ({
id: endpoint.operationId,
description: endpoint.summary,
auth_required: true,
endpoint: endpoint.path,
method: endpoint.method
}))
return {
awp_version: '0.1',
domain: 'localhost',
intent: 'Programmatic BCH blockchain API access',
capabilities: {
batch_actions: false,
streaming: false
},
auth: {
type: 'x402-bch-v2',
required_for: actions.map(a => a.id),
pricing: {
amountSat: String(x402.priceSat),
payTo: x402.serverAddress,
network: BCH_MAINNET_CAIP2,
x402Version: X402_SPEC_VERSION
}
},
actions
}
}
export function buildDiscoveryDocuments () {
const endpoints = parseApiAnnotations()
const paths = normalizePaths(endpoints)
return {
openapi: buildOpenApi(paths),
swagger: buildSwagger(paths),
llms: buildLlms(endpoints),
agent: buildAgent(endpoints)
}
}
export function getDiscoveryDocuments () {
if (cachedDocs) return cachedDocs
const artifactPath = resolve(process.cwd(), 'docs/discovery-artifacts.json')
if (existsSync(artifactPath)) {
try {
cachedDocs = JSON.parse(readFileSync(artifactPath, 'utf8'))
return cachedDocs
} catch {
cachedDocs = buildDiscoveryDocuments()
return cachedDocs
}
}
cachedDocs = buildDiscoveryDocuments()
return cachedDocs
}
export function resetDiscoveryDocumentCache () {
cachedDocs = null
}
-71
View File
@@ -1,71 +0,0 @@
/*
Event entity - represents a Nostr event.
This is a domain model following Clean Architecture principles.
*/
class Event {
constructor (data) {
this.id = data.id
this.pubkey = data.pubkey
this.created_at = data.created_at
this.kind = data.kind
this.tags = data.tags || []
this.content = data.content
this.sig = data.sig
}
/**
* Validates the event structure
* @returns {boolean} True if valid
*/
isValid () {
if (!this.id || !this.pubkey || !this.created_at || this.kind === undefined || !this.sig) {
return false
}
// Basic type checks
if (typeof this.id !== 'string' || this.id.length !== 64) {
return false
}
if (typeof this.pubkey !== 'string' || this.pubkey.length !== 64) {
return false
}
if (typeof this.created_at !== 'number') {
return false
}
if (typeof this.kind !== 'number' || this.kind < 0 || this.kind > 65535) {
return false
}
if (typeof this.sig !== 'string' || this.sig.length !== 128) {
return false
}
if (!Array.isArray(this.tags)) {
return false
}
return true
}
/**
* Convert to plain object
* @returns {Object} Plain event object
*/
toJSON () {
return {
id: this.id,
pubkey: this.pubkey,
created_at: this.created_at,
kind: this.kind,
tags: this.tags,
content: this.content,
sig: this.sig
}
}
}
export default Event
+61
View File
@@ -0,0 +1,61 @@
/*
Basic Authentication Middleware
This middleware validates Bearer tokens from the Authorization header.
When a valid token is provided, it sets req.locals.basicAuthValid = true
to allow bypassing x402 middleware.
*/
import config from '../config/index.js'
import wlogger from '../adapters/wlogger.js'
/**
* Middleware function that validates Bearer token authentication
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @param {Function} next - Express next middleware function
*/
export function basicAuthMiddleware (req, res, next) {
// Initialize req.locals if it doesn't exist
if (!req.locals) {
req.locals = {}
}
// Default to false
req.locals.basicAuthValid = false
// Get the configured token
const configuredToken = config.basicAuth?.token
// If no token is configured, skip validation
if (!configuredToken) {
wlogger.warn('Basic auth enabled but no BASIC_AUTH_TOKEN configured')
return next()
}
// Get the Authorization header
const authHeader = req.headers.authorization
// If no Authorization header, continue (x402 will handle unauthorized requests)
if (!authHeader) {
return next()
}
// Check if it's a Bearer token
const parts = authHeader.split(' ')
if (parts.length !== 2 || parts[0] !== 'Bearer') {
return next()
}
const providedToken = parts[1]
// Compare tokens
if (providedToken === configuredToken) {
req.locals.basicAuthValid = true
wlogger.verbose(`Basic auth validated for request to ${req.path}`)
}
// Always continue to next middleware
// If auth failed, x402 middleware will handle the request
next()
}
+120
View File
@@ -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
+192
View File
@@ -0,0 +1,192 @@
/*
Use cases for interacting with the Fulcrum API service.
*/
import wlogger from '../adapters/wlogger.js'
import BCHJS from '@psf/bch-js'
import config from '../config/index.js'
// 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 = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating Fulcrum use cases.')
}
this.fulcrum = this.adapters.fulcrum
if (!this.fulcrum) {
throw new Error('Fulcrum adapter required when instantiating Fulcrum use cases.')
}
// Allow bchjs to be injected for testing
this.bchjs = localConfig.bchjs || bchjs
}
async getBalance ({ address }) {
return this.fulcrum.get(`electrumx/balance/${address}`)
}
async getBalances ({ addresses }) {
try {
const response = await this.fulcrum.post('electrumx/balance/', { addresses })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getBalances()', err)
throw err
}
}
async getUtxos ({ address }) {
return this.fulcrum.get(`electrumx/utxos/${address}`)
}
async getUtxosBulk ({ addresses }) {
try {
const response = await this.fulcrum.post('electrumx/utxos/', { addresses })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getUtxosBulk()', err)
throw err
}
}
async getTransactionDetails ({ txid }) {
const response = await this.fulcrum.get(`electrumx/tx/data/${txid}`)
// console.log(`getTransactionDetails() TXID ${txid}: ${JSON.stringify(response, null, 2)}`)
return response
}
async getTransactionDetailsBulk ({ txids, verbose }) {
try {
const response = await this.fulcrum.post('electrumx/tx/data', { txids, verbose })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getTransactionDetailsBulk()', err)
throw err
}
}
async broadcastTransaction ({ txHex }) {
try {
const response = await this.fulcrum.post('electrumx/tx/broadcast', { txHex })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.broadcastTransaction()', err)
throw err
}
}
async getBlockHeaders ({ height, count }) {
return this.fulcrum.get(`electrumx/block/headers/${height}?count=${count}`)
}
async getBlockHeadersBulk ({ heights }) {
try {
const response = await this.fulcrum.post('electrumx/block/headers', { heights })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getBlockHeadersBulk()', err)
throw err
}
}
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)) {
// 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.
response.transactions = response.transactions.slice(0, 100)
}
}
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getTransactions()', err)
throw err
}
}
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 bchjsInstance.Electrumx.sortAllTxs(thisEntry.transactions, 'DESCENDING')
if (!allTxs && thisEntry.transactions.length > 100) {
// Extract only the first 100 transactions.
thisEntry.transactions = thisEntry.transactions.slice(0, 100)
}
}
}
}
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getTransactionsBulk()', err)
throw err
}
}
async getMempool ({ address }) {
return this.fulcrum.get(`electrumx/unconfirmed/${address}`)
}
async getMempoolBulk ({ addresses }) {
try {
const response = await this.fulcrum.post('electrumx/unconfirmed/', { addresses })
return response
} catch (err) {
wlogger.error('Error in FulcrumUseCases.getMempoolBulk()', err)
throw err
}
}
}
export default FulcrumUseCases
@@ -0,0 +1,134 @@
/*
Use cases for interacting with the BCH full node blockchain RPC interface.
*/
import wlogger from '../adapters/wlogger.js'
class BlockchainUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating Blockchain use cases.')
}
this.fullNode = this.adapters.fullNode
if (!this.fullNode) {
throw new Error('Full node adapter required when instantiating Blockchain use cases.')
}
}
async getBestBlockHash () {
return this.fullNode.call('getbestblockhash')
}
async getBlockchainInfo () {
return this.fullNode.call('getblockchaininfo')
}
async getBlockCount () {
return this.fullNode.call('getblockcount')
}
async getBlockHeader ({ hash, verbose = false }) {
return this.fullNode.call('getblockheader', [hash, verbose])
}
async getBlockHeaders ({ hashes, verbose = false }) {
try {
const promises = hashes.map(hash =>
this.fullNode.call('getblockheader', [hash, verbose], `getblockheader-${hash}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in BlockchainUseCases.getBlockHeaders()', err)
throw err
}
}
async getChainTips () {
return this.fullNode.call('getchaintips')
}
async getDifficulty () {
return this.fullNode.call('getdifficulty')
}
async getMempoolEntry ({ txid }) {
return this.fullNode.call('getmempoolentry', [txid])
}
async getMempoolEntries ({ txids }) {
try {
const promises = txids.map(txid =>
this.fullNode.call('getmempoolentry', [txid], `getmempoolentry-${txid}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in BlockchainUseCases.getMempoolEntries()', err)
throw err
}
}
async getMempoolAncestors ({ txid, verbose = false }) {
return this.fullNode.call('getmempoolancestors', [txid, verbose])
}
async getMempoolInfo () {
return this.fullNode.call('getmempoolinfo')
}
async getRawMempool ({ verbose = false }) {
return this.fullNode.call('getrawmempool', [verbose])
}
async getTxOut ({ txid, n, includeMempool }) {
return this.fullNode.call('gettxout', [txid, n, includeMempool])
}
async getTxOutProof ({ txid }) {
return this.fullNode.call('gettxoutproof', [[txid]])
}
async getTxOutProofs ({ txids }) {
try {
const promises = txids.map(txid =>
this.fullNode.call('gettxoutproof', [[txid]], `gettxoutproof-${txid}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in BlockchainUseCases.getTxOutProofs()', err)
throw err
}
}
async verifyTxOutProof ({ proof }) {
return this.fullNode.call('verifytxoutproof', [proof])
}
async verifyTxOutProofs ({ proofs }) {
try {
const promises = proofs.map(proof =>
this.fullNode.call('verifytxoutproof', [proof], `verifytxoutproof-${proof.slice(0, 16)}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in BlockchainUseCases.verifyTxOutProofs()', err)
throw err
}
}
async getBlock ({ blockhash, verbosity }) {
return this.fullNode.call('getblock', [blockhash, verbosity])
}
async getBlockHash ({ height }) {
return this.fullNode.call('getblockhash', [height])
}
}
export default BlockchainUseCases
@@ -0,0 +1,24 @@
/*
Use cases for interacting with the BCH full node control RPC interface.
*/
class ControlUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating Control use cases.')
}
this.fullNode = this.adapters.fullNode
if (!this.fullNode) {
throw new Error('Full node adapter required when instantiating Control use cases.')
}
}
async getNetworkInfo () {
return this.fullNode.call('getnetworkinfo')
}
}
export default ControlUseCases
@@ -0,0 +1,24 @@
/*
Use cases for interacting with the BCH full node double-spend proof RPC interface.
*/
class DSProofUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating DSProof use cases.')
}
this.fullNode = this.adapters.fullNode
if (!this.fullNode) {
throw new Error('Full node adapter required when instantiating DSProof use cases.')
}
}
async getDSProof ({ txid, verbose }) {
return this.fullNode.call('getdsproof', [txid, verbose])
}
}
export default DSProofUseCases
@@ -0,0 +1,28 @@
/*
Use cases for interacting with the BCH full node mining RPC interface.
*/
class MiningUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating Mining use cases.')
}
this.fullNode = this.adapters.fullNode
if (!this.fullNode) {
throw new Error('Full node adapter required when instantiating Mining use cases.')
}
}
async getMiningInfo () {
return this.fullNode.call('getmininginfo')
}
async getNetworkHashPS ({ nblocks, height }) {
return this.fullNode.call('getnetworkhashps', [nblocks, height])
}
}
export default MiningUseCases
@@ -0,0 +1,121 @@
/*
Use cases for interacting with the BCH full node raw transactions RPC interface.
*/
import wlogger from '../adapters/wlogger.js'
class RawTransactionsUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating RawTransactions use cases.')
}
this.fullNode = this.adapters.fullNode
if (!this.fullNode) {
throw new Error('Full node adapter required when instantiating RawTransactions use cases.')
}
}
async decodeRawTransaction ({ hex }) {
return this.fullNode.call('decoderawtransaction', [hex])
}
async decodeRawTransactions ({ hexes }) {
try {
const promises = hexes.map(hex =>
this.fullNode.call('decoderawtransaction', [hex], `decoderawtransaction-${hex.slice(0, 16)}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in RawTransactionsUseCases.decodeRawTransactions()', err)
throw err
}
}
async decodeScript ({ hex }) {
return this.fullNode.call('decodescript', [hex])
}
async decodeScripts ({ hexes }) {
try {
const promises = hexes.map(hex =>
this.fullNode.call('decodescript', [hex], `decodescript-${hex.slice(0, 16)}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in RawTransactionsUseCases.decodeScripts()', err)
throw err
}
}
async getRawTransaction ({ txid, verbose = false }) {
const verboseInt = verbose ? 1 : 0
return this.fullNode.call('getrawtransaction', [txid, verboseInt])
}
async getRawTransactions ({ txids, verbose = false }) {
try {
const verboseInt = verbose ? 1 : 0
const promises = txids.map(txid =>
this.fullNode.call('getrawtransaction', [txid, verboseInt], `getrawtransaction-${txid}`)
)
return await Promise.all(promises)
} catch (err) {
wlogger.error('Error in RawTransactionsUseCases.getRawTransactions()', err)
throw err
}
}
async getRawTransactionWithHeight ({ txid, verbose = false }) {
const verboseInt = verbose ? 1 : 0
const data = await this.fullNode.call('getrawtransaction', [txid, verboseInt])
if (verbose && data && data.blockhash) {
data.height = null
try {
// Look up the block height and append it to the TX response.
const blockHeader = await this.fullNode.call('getblockheader', [data.blockhash, true])
data.height = blockHeader.height
} catch (err) {
// Exit quietly if block header lookup fails
wlogger.debug('Could not fetch block header for height lookup', err)
}
}
return data
}
async getBlockHeader ({ blockHash, verbose = false }) {
return this.fullNode.call('getblockheader', [blockHash, verbose])
}
async sendRawTransaction ({ hex }) {
return this.fullNode.call('sendrawtransaction', [hex])
}
async sendRawTransactions ({ hexes }) {
// Dev Note: Sending the 'sendrawtransaction' RPC call to a full node in parallel will
// not work. Testing showed that the full node will return the same TXID for
// different TX hexes. I believe this is by design, to prevent double spends.
// In parallel, we are essentially asking the node to broadcast a new TX before
// it's finished broadcasting the previous one. Serial execution is required.
try {
const result = []
for (const hex of hexes) {
const txid = await this.fullNode.call('sendrawtransaction', [hex], `sendrawtransaction-${hex.slice(0, 16)}`)
result.push(txid)
}
return result
} catch (err) {
wlogger.error('Error in RawTransactionsUseCases.sendRawTransactions()', err)
throw err
}
}
}
export default RawTransactionsUseCases
+23 -6
View File
@@ -5,9 +5,15 @@
*/
// Local libraries
// import PublishEventUseCase from './publish-event.js'
// import QueryEventsUseCase from './query-events.js'
// import ManageSubscriptionUseCase from './manage-subscription.js'
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'
import RawTransactionsUseCases from './full-node-rawtransactions-use-cases.js'
import SlpUseCases from './slp-use-cases.js'
class UseCases {
constructor (localConfig = {}) {
@@ -18,9 +24,20 @@ class UseCases {
)
}
// this.publishEvent = new PublishEventUseCase({ adapters: this.adapters })
// this.queryEvents = new QueryEventsUseCase({ adapters: this.adapters })
// this.manageSubscription = new ManageSubscriptionUseCase({ adapters: this.adapters })
this.blockchain = new BlockchainUseCases({ adapters: this.adapters })
this.control = new ControlUseCases({ adapters: this.adapters })
this.dsproof = new DSProofUseCases({ adapters: this.adapters })
this.fulcrum = new FulcrumUseCases({ adapters: this.adapters })
this.mining = new MiningUseCases({ adapters: this.adapters })
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.
-216
View File
@@ -1,216 +0,0 @@
/*
Use case: Manage subscriptions for Server-Sent Events (SSE).
This encapsulates the business logic for creating and managing subscriptions.
*/
import wlogger from '../adapters/wlogger.js'
class ManageSubscriptionUseCase {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required')
}
if (!this.adapters.nostrRelays || !Array.isArray(this.adapters.nostrRelays) || this.adapters.nostrRelays.length === 0) {
throw new Error('NostrRelay adapters array required')
}
// Map subscriptionId to { relaySubscriptions: Map<relayIndex, subscriptionId>, handlers, seenEventIds }
this.activeSubscriptions = new Map()
}
/**
* Create a subscription for SSE streaming across all relays
* @param {string} subscriptionId - Unique subscription ID
* @param {Array} filters - Array of filter objects
* @param {Function} onEvent - Callback for events
* @param {Function} onEose - Callback for EOSE
* @param {Function} onClosed - Callback for CLOSED
* @returns {Promise<void>}
*/
async createSubscription (subscriptionId, filters, onEvent, onEose, onClosed) {
try {
if (this.activeSubscriptions.has(subscriptionId)) {
throw new Error(`Subscription ${subscriptionId} already exists`)
}
wlogger.info(`Creating subscription ${subscriptionId} across ${this.adapters.nostrRelays.length} relay(s)`)
// Track seen event IDs to de-duplicate across relays
const seenEventIds = new Set()
// Track EOSE and CLOSED status per relay
const relayStatuses = this.adapters.nostrRelays.map(() => ({
eoseReceived: false,
closedReceived: false
}))
// Create unified handlers that merge events from all relays
const handlers = {
onEvent: (event) => {
// De-duplicate events by ID across all relays
if (event && event.id && !seenEventIds.has(event.id)) {
seenEventIds.add(event.id)
if (onEvent) {
onEvent(event)
}
}
},
onEose: () => {
// Call onEose only once when all relays have sent EOSE
// This is called from the per-relay handler only when all relays have EOSE
if (onEose) {
onEose()
}
},
onClosed: (message) => {
if (onClosed) {
onClosed(message)
}
// Clean up subscription if any relay closes it
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
if (subscriptionInfo && subscriptionInfo.eoseTimeoutId) {
clearTimeout(subscriptionInfo.eoseTimeoutId)
}
this.activeSubscriptions.delete(subscriptionId)
}
}
// Create subscription per relay with unique subscription IDs
const relaySubscriptions = new Map()
const subscriptionPromises = this.adapters.nostrRelays.map(async (relay, index) => {
const relaySubscriptionId = `${subscriptionId}-relay-${index}`
relaySubscriptions.set(index, relaySubscriptionId)
// Create per-relay handlers that update shared state
const relayHandlers = {
onEvent: (event) => {
handlers.onEvent(event)
},
onEose: () => {
relayStatuses[index].eoseReceived = true
// Check if all relays have sent EOSE
if (relayStatuses.every(s => s.eoseReceived)) {
// Clear the timeout since we got EOSE from all relays
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
if (subscriptionInfo && subscriptionInfo.eoseTimeoutId) {
clearTimeout(subscriptionInfo.eoseTimeoutId)
subscriptionInfo.eoseTimeoutId = null
}
handlers.onEose()
}
},
onClosed: (message) => {
relayStatuses[index].closedReceived = true
handlers.onClosed(message)
}
}
await relay.sendReq(relaySubscriptionId, filters, relayHandlers)
})
// Store subscription info
this.activeSubscriptions.set(subscriptionId, {
relaySubscriptions,
handlers,
seenEventIds,
relayStatuses,
eoseTimeoutId: null
})
// Subscribe to all relays concurrently
const results = await Promise.allSettled(subscriptionPromises)
// Check if any relay subscription failed and clean up if so
const hasFailures = results.some(result => result.status === 'rejected')
if (hasFailures) {
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
if (subscriptionInfo && subscriptionInfo.eoseTimeoutId) {
clearTimeout(subscriptionInfo.eoseTimeoutId)
}
this.activeSubscriptions.delete(subscriptionId)
const errors = results
.filter(result => result.status === 'rejected')
.map(result => result.reason)
throw new Error(`Failed to create subscription on some relays: ${errors.map(e => e.message).join(', ')}`)
}
// Set up EOSE timeout fallback - if not all relays send EOSE within 10 seconds, call onEose anyway
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
const EOSE_TIMEOUT_MS = 10000 // 10 seconds
subscriptionInfo.eoseTimeoutId = setTimeout(() => {
// Check if subscription still exists and if all relays have sent EOSE
if (this.activeSubscriptions.has(subscriptionId)) {
const currentInfo = this.activeSubscriptions.get(subscriptionId)
const allEoseReceived = currentInfo.relayStatuses.every(s => s.eoseReceived)
if (!allEoseReceived) {
wlogger.warn(`EOSE timeout reached for subscription ${subscriptionId} - calling onEose callback anyway`)
if (handlers.onEose) {
handlers.onEose()
}
}
}
}, EOSE_TIMEOUT_MS)
} catch (err) {
wlogger.error('Error creating subscription:', err)
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
if (subscriptionInfo && subscriptionInfo.eoseTimeoutId) {
clearTimeout(subscriptionInfo.eoseTimeoutId)
}
this.activeSubscriptions.delete(subscriptionId)
throw err
}
}
/**
* Close a subscription across all relays
* @param {string} subscriptionId - Subscription ID to close
* @returns {Promise<void>}
*/
async closeSubscription (subscriptionId) {
try {
if (!this.activeSubscriptions.has(subscriptionId)) {
// Subscription doesn't exist - already closed, treat as success (idempotent)
wlogger.info(`Subscription ${subscriptionId} already closed or does not exist`)
return
}
wlogger.info(`Closing subscription ${subscriptionId} across all relays`)
const subscriptionInfo = this.activeSubscriptions.get(subscriptionId)
const { relaySubscriptions } = subscriptionInfo
// Clear EOSE timeout if it exists
if (subscriptionInfo.eoseTimeoutId) {
clearTimeout(subscriptionInfo.eoseTimeoutId)
}
// Close subscriptions on all relays concurrently
const closePromises = Array.from(relaySubscriptions.entries()).map(async ([relayIndex, relaySubscriptionId]) => {
try {
await this.adapters.nostrRelays[relayIndex].sendClose(relaySubscriptionId)
} catch (err) {
wlogger.warn(`Error closing subscription on relay ${relayIndex}:`, err.message)
}
})
await Promise.allSettled(closePromises)
this.activeSubscriptions.delete(subscriptionId)
} catch (err) {
wlogger.error('Error closing subscription:', err)
// Clean up even if there's an error
this.activeSubscriptions.delete(subscriptionId)
throw err
}
}
/**
* Check if a subscription exists
* @param {string} subscriptionId - Subscription ID
* @returns {boolean}
*/
hasSubscription (subscriptionId) {
return this.activeSubscriptions.has(subscriptionId)
}
}
export default ManageSubscriptionUseCase
+140
View File
@@ -0,0 +1,140 @@
/*
Use cases for price-related operations.
*/
// Global npm libraries
import axios from 'axios'
import SlpWallet from 'minimal-slp-wallet'
import PSFFPP from 'psffpp'
// Local libraries
import wlogger from '../adapters/wlogger.js'
import config from '../config/index.js'
class PriceUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating Price use cases.')
}
// Get config
this.config = localConfig.config || config
// Coinex API URL for BCH/USDT
this.bchCoinexPriceUrl =
'https://api.coinex.com/v1/market/ticker?market=bchusdt'
// Allow axios to be injected for testing
this.axios = localConfig.axios || axios
this.psfLiquidityPriceKeys = [
'usdPerBCH',
'bchBalance',
'tokenBalance',
'usdPerToken'
]
}
/**
* Get the USD price of BCH from Coinex.
* @returns {Promise<number>} The USD price of BCH
*/
async getBCHUSD () {
try {
// Request options
const opt = {
method: 'get',
baseURL: this.bchCoinexPriceUrl,
timeout: 15000
}
const response = await this.axios.request(opt)
const price = Number(response.data.data.ticker.last)
return price
} catch (err) {
wlogger.error('Error in PriceUseCases.getBCHUSD()', err)
throw err
}
}
/**
* Get the PSF price for writing to the PSFFPP.
* Returns the price to pin 1MB of content to the PSFFPP pinning
* network on IPFS. The price is denominated in PSF tokens.
* @returns {Promise<number>} The write price in PSF tokens
*/
async getPsffppWritePrice () {
try {
const wallet = new SlpWallet(undefined, {
interface: 'rest-api',
restURL: this.config.restURL
})
await wallet.walletInfoPromise
const psffpp = new PSFFPP({ wallet })
const writePrice = await psffpp.getMcWritePrice()
return writePrice
} catch (err) {
wlogger.error('Error in PriceUseCases.getPsffppWritePrice()', err)
throw err
}
}
/**
* Proxies PSF token liquidity spot price from the token-liquidity app (GET /price).
* @returns {Promise<Object>} usdPerBCH, bchBalance, tokenBalance, usdPerToken
*/
async getPsfLiquidityPrice () {
try {
const proxy = this.config.psfLiquidityProxy
if (!proxy || !proxy.enabled) {
const err = new Error('PSF liquidity price proxy is disabled')
err.status = 503
throw err
}
const baseUrl = String(proxy.baseUrl).replace(/\/$/, '')
const fullUrl = `${baseUrl}/price`
const opt = {
method: 'get',
url: fullUrl,
timeout: 15000
}
const response = await this.axios.request(opt)
const data = response.data
if (
!data ||
typeof data !== 'object' ||
Array.isArray(data) ||
!this.psfLiquidityPriceKeys.every(
(k) => typeof data[k] === 'number' && !Number.isNaN(data[k])
)
) {
const err = new Error('Invalid response from PSF liquidity price service')
err.status = 502
throw err
}
return {
usdPerBCH: data.usdPerBCH,
bchBalance: data.bchBalance,
tokenBalance: data.tokenBalance,
usdPerToken: data.usdPerToken
}
} catch (err) {
wlogger.error('Error in PriceUseCases.getPsfLiquidityPrice()', err)
throw err
}
}
}
export default PriceUseCases
-87
View File
@@ -1,87 +0,0 @@
/*
Use case: Publish a Nostr event to the relay.
This encapsulates the business logic for publishing events.
*/
import Event from '../entities/event.js'
import wlogger from '../adapters/wlogger.js'
class PublishEventUseCase {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required')
}
if (!this.adapters.nostrRelays || !Array.isArray(this.adapters.nostrRelays) || this.adapters.nostrRelays.length === 0) {
throw new Error('NostrRelay adapters array required')
}
}
/**
* Publish an event to all Nostr relays (broadcast)
* @param {Object} eventData - Event data (must be signed)
* @returns {Promise<Object>} Result with accepted status, message, and relay results
*/
async execute (eventData) {
try {
// Create event entity
const event = new Event(eventData)
// Validate event
if (!event.isValid()) {
throw new Error('Invalid event structure')
}
wlogger.info(`Publishing event ${event.id} (kind ${event.kind}) to ${this.adapters.nostrRelays.length} relay(s)`)
// Broadcast event to all relays
const results = await this.adapters.broadcastEvent(event.toJSON())
// Aggregate results
const acceptedRelays = results.filter(r => r.accepted)
const rejectedRelays = results.filter(r => !r.accepted)
const failedRelays = results.filter(r => !r.success)
const atLeastOneAccepted = acceptedRelays.length > 0
const allAccepted = acceptedRelays.length === results.length && failedRelays.length === 0
// Build aggregated message
let message = ''
if (allAccepted) {
message = `Accepted by all ${acceptedRelays.length} relay(s)`
} else if (atLeastOneAccepted) {
message = `Accepted by ${acceptedRelays.length}/${results.length} relay(s)`
if (rejectedRelays.length > 0) {
message += `, rejected by ${rejectedRelays.length} relay(s)`
}
if (failedRelays.length > 0) {
message += `, failed to reach ${failedRelays.length} relay(s)`
}
} else {
message = `Rejected or failed by all ${results.length} relay(s)`
if (rejectedRelays.length > 0) {
const rejectionMessages = rejectedRelays.map(r => r.message).filter(m => m).join('; ')
if (rejectionMessages) {
message += `: ${rejectionMessages}`
}
}
}
wlogger.info(`Event ${event.id} ${atLeastOneAccepted ? 'accepted' : 'rejected/failed'}: ${message}`)
return {
accepted: atLeastOneAccepted,
message,
eventId: event.id,
relayResults: results,
acceptedCount: acceptedRelays.length,
totalRelays: results.length
}
} catch (err) {
wlogger.error('Error in PublishEventUseCase:', err)
throw err
}
}
}
export default PublishEventUseCase
-41
View File
@@ -1,41 +0,0 @@
/*
Use case: Query events from the relay (stateless).
This encapsulates the business logic for querying events.
*/
import wlogger from '../adapters/wlogger.js'
class QueryEventsUseCase {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required')
}
if (!this.adapters.nostrRelays || !Array.isArray(this.adapters.nostrRelays) || this.adapters.nostrRelays.length === 0) {
throw new Error('NostrRelay adapters array required')
}
}
/**
* Query events with filters from all relays (stateless - returns immediately)
* @param {Array} filters - Array of filter objects
* @param {string} subscriptionId - Unique subscription ID
* @returns {Promise<Array>} Array of events (merged and de-duplicated from all relays)
*/
async execute (filters, subscriptionId) {
try {
wlogger.info(`Querying events with subscription ${subscriptionId} from ${this.adapters.nostrRelays.length} relay(s)`)
// Query all relays concurrently and merge results
const events = await this.adapters.queryAllRelays(filters, subscriptionId)
wlogger.info(`Query returned ${events.length} events from ${this.adapters.nostrRelays.length} relay(s)`)
return events
} catch (err) {
wlogger.error('Error in QueryEventsUseCase:', err)
throw err
}
}
}
export default QueryEventsUseCase
+332
View File
@@ -0,0 +1,332 @@
/*
Use cases for interacting with the SLP Indexer API service.
*/
import wlogger from '../adapters/wlogger.js'
import BCHJS from '@psf/bch-js'
import SlpWallet from 'minimal-slp-wallet'
import SlpTokenMedia from 'slp-token-media'
import axios from 'axios'
import config from '../config/index.js'
const bchjs = new BCHJS({ restURL: config.restURL })
class SlpUseCases {
constructor (localConfig = {}) {
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error('Adapters instance required when instantiating SLP use cases.')
}
this.slpIndexer = this.adapters.slpIndexer
if (!this.slpIndexer) {
throw new Error('SLP Indexer adapter required when instantiating SLP use cases.')
}
// Allow bchjs to be injected for testing
this.bchjs = localConfig.bchjs || bchjs
// Get config
this.config = localConfig.config || config
// Initialize wallet (lazy initialization)
this.wallet = null
this.slpTokenMedia = null
this.walletInitialized = false
this.initializationPromise = null
}
// Initialize wallet and SlpTokenMedia asynchronously
async _ensureInitialized () {
if (this.walletInitialized) {
return
}
if (this.initializationPromise) {
return this.initializationPromise
}
this.initializationPromise = this._initialize()
return this.initializationPromise
}
async _initialize () {
try {
// Initialize wallet
this.wallet = new SlpWallet(undefined, {
restURL: this.config.restURL,
interface: 'rest-api'
})
// Wait for wallet to initialize
await this.wallet.walletInfoPromise
// Initialize SlpTokenMedia
this.slpTokenMedia = new SlpTokenMedia({
wallet: this.wallet,
ipfsGatewayUrl: this.config.ipfsGateway
})
this.walletInitialized = true
wlogger.info('SLP wallet and token media initialized')
} catch (err) {
wlogger.error('Error initializing SLP wallet:', err)
throw err
}
}
async getStatus () {
try {
return await this.slpIndexer.get('slp/status/')
} catch (err) {
wlogger.error('Error in SlpUseCases.getStatus()', err)
throw err
}
}
async getAddress ({ address }) {
try {
return await this.slpIndexer.post('slp/address/', { address })
} catch (err) {
wlogger.error('Error in SlpUseCases.getAddress()', err)
throw err
}
}
async getTxid ({ txid }) {
try {
return await this.slpIndexer.post('slp/tx/', { txid })
} catch (err) {
const isCommonMissingTxError =
err?.status === 404 &&
typeof err?.message === 'string' &&
err.message.includes('Key not found in database')
if (!isCommonMissingTxError) {
wlogger.error('Error in SlpUseCases.getTxid()', err)
}
throw err
}
}
async getTokenStats ({ tokenId, withTxHistory = false }) {
try {
return await this.slpIndexer.post('slp/token/', { tokenId, withTxHistory })
} catch (err) {
wlogger.error('Error in SlpUseCases.getTokenStats()', err)
throw err
}
}
async getTokenData ({ tokenId, withTxHistory = false }) {
try {
const tokenData = {}
// Get token stats from the Genesis TX of the token
const response = await this.slpIndexer.post('slp/token/', { tokenId, withTxHistory })
const tokenStats = response.tokenData
tokenData.genesisData = tokenStats
// Try to get immutable data
try {
const immutableData = tokenStats.documentUri
tokenData.immutableData = immutableData || ''
} catch (error) {
tokenData.immutableData = ''
}
// Try to get mutable data
try {
const mutableData = await this.getMutableCid({ tokenStats })
tokenData.mutableData = mutableData || ''
} catch (error) {
wlogger.warn('Error getting mutable data:', error)
tokenData.mutableData = ''
}
return tokenData
} catch (err) {
wlogger.error('Error in SlpUseCases.getTokenData()', err)
throw err
}
}
async getMutableCid ({ tokenStats }) {
// Validate input - this should throw, not be caught
if (!tokenStats || !tokenStats.documentHash) {
throw new Error('No documentHash property found in tokenStats')
}
try {
await this._ensureInitialized()
// Get the OP_RETURN data and decode it
const mutableData = await this.decodeOpReturn({ txid: tokenStats.documentHash })
const jsonData = JSON.parse(mutableData)
// mda = mutable data address
const mda = jsonData.mda
// Get the mda transaction history
const transactions = await this.wallet.getTransactions(mda)
wlogger.info(`MDA has ${transactions.length} transactions in its history.`)
const mdaTxs = transactions
let data = false
// These are used to filter blockchain data to find the most recent
// update to the MDA
let largestBlock = 700000
let largestTimestamp = 1666107111271
let bestEntry
// Used to track the number of transactions before the best candidate is found
let txCnt = 0
// Map each transaction of the mda
// If it finds an OP_RETURN, decode it and exit the loop
for (let i = 0; i < mdaTxs.length; i++) {
const tx = mdaTxs[i]
const txid = tx.tx_hash
txCnt++
data = await this.decodeOpReturn({ txid })
// Try parse the OP_RETURN data to a JSON object
if (data) {
try {
// Convert the OP_RETURN data to a JSON object
const obj = JSON.parse(data)
// Keep searching if this TX does not have a cid value
if (!obj.cid) continue
// Ensure data was generated by the MDA
const txData = await this.wallet.getTxData([txid])
const vinAddress = txData[0].vin[0].address
// Skip entry if it was not made by the MDA private key
if (mda !== vinAddress) {
continue
}
// First best entry found
if (!bestEntry) {
bestEntry = data
largestBlock = tx.height
if (obj.ts) {
largestTimestamp = obj.ts
}
} else {
// One candidate already found. Looking for potentially better entry
if (tx.height < largestBlock) {
// Exit loop if next candidate has an older block height
break
}
if (obj.ts && obj.ts < largestTimestamp) {
// Continue looping through entries if the current entry in
// the same block has a smaller timestamp
continue
}
bestEntry = data
largestBlock = tx.height
if (obj.ts) {
largestTimestamp = obj.ts
}
}
} catch (error) {
continue
}
}
}
wlogger.info(`${txCnt} transactions reviewed to find mutable data.`)
if (!bestEntry) {
return false
}
// Get the CID
const obj = JSON.parse(bestEntry)
const cid = obj.cid
if (!cid) {
return false
}
// Assuming that CID starts with ipfs://. Cutting out that prefix
const mutableCid = cid.substring(7)
return mutableCid
} catch (err) {
console.log('Error in SlpUseCases.getMutableCid()', err)
wlogger.error('Error in SlpUseCases.getMutableCid()', err)
return false
}
}
async decodeOpReturn ({ txid }) {
try {
if (!txid || typeof txid !== 'string') {
throw new Error('txid must be a string.')
}
// 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
for (let i = 0; i < txData.details.vout.length; i++) {
const vout = txData.details.vout[i]
const script = this.bchjs.Script.toASM(
Buffer.from(vout.scriptPubKey.hex, 'hex')
).split(' ')
// Exit on the first OP_RETURN found
if (script[0] === 'OP_RETURN') {
data = Buffer.from(script[1], 'hex').toString('ascii')
break
}
}
return data
} catch (error) {
console.log('Error in SlpUseCases.decodeOpReturn()', error)
wlogger.error('Error in SlpUseCases.decodeOpReturn()', error)
throw error
}
}
async getCIDData ({ cid }) {
try {
if (!cid || typeof cid !== 'string') {
throw new Error('cid must be a string.')
}
// Assuming that CID starts with ipfs://. Cutting out that prefix
const cidWithoutPrefix = cid.substring(7)
const dataUrl = `https://${cidWithoutPrefix}.ipfs.dweb.link/data.json`
wlogger.info(`Fetching IPFS data from: ${dataUrl}`)
const response = await axios.get(dataUrl)
return response.data
} catch (error) {
wlogger.error('Error in SlpUseCases.getCIDData()', error)
throw error
}
}
}
export default SlpUseCases
-250
View File
@@ -1,250 +0,0 @@
/*
Integration tests for POST /event endpoint.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Server from '../../../bin/server.js'
import { finalizeEvent, getPublicKey, generateSecretKey } from 'nostr-tools/pure'
import { hexToBytes } from '@noble/hashes/utils.js'
describe('#event-integration.js', () => {
let server
const baseUrl = 'http://localhost:3001' // Use different port for tests
before(async () => {
// Start test server
server = new Server()
server.config.port = 3001
await server.startServer()
// Wait for server to be ready
await new Promise(resolve => setTimeout(resolve, 1000))
})
after(async () => {
// Stop server
if (server && server.server) {
await new Promise((resolve) => {
server.server.close(() => {
resolve()
})
})
}
})
describe('POST /event', () => {
it('should publish kind 0 event (profile metadata) - covers example 01', async () => {
// Generate keys
const sk = generateSecretKey()
// Create profile metadata event (kind 0)
const profileMetadata = {
name: 'Test User',
about: 'Integration test user',
picture: 'https://example.com/test.jpg'
}
const eventTemplate = {
kind: 0,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: JSON.stringify(profileMetadata)
}
// Sign the event
const signedEvent = finalizeEvent(eventTemplate, sk)
// Publish to REST API
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signedEvent)
})
const result = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.property(result, 'accepted')
assert.property(result, 'eventId')
assert.equal(result.eventId, signedEvent.id)
})
it('should publish kind 1 event (text post) - covers example 03', async () => {
// Alice's private key from examples
const alicePrivKeyHex = '3292a48aa331aeccce003d50d70fbd79617ba91860abbd2c78fa4a8301e36bc0'
const alicePrivKeyBin = hexToBytes(alicePrivKeyHex)
const alicePubKey = getPublicKey(alicePrivKeyBin)
// Generate a post
const eventTemplate = {
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'Integration test post'
}
// Sign the post
const signedEvent = finalizeEvent(eventTemplate, alicePrivKeyBin)
// Publish to REST API
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signedEvent)
})
const result = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.property(result, 'accepted')
assert.property(result, 'eventId')
assert.equal(result.eventId, signedEvent.id)
assert.equal(signedEvent.pubkey, alicePubKey)
})
it('should publish kind 3 event (follow list) - covers example 06', async () => {
// Alice's private key
const alicePrivKeyHex = '3292a48aa331aeccce003d50d70fbd79617ba91860abbd2c78fa4a8301e36bc0'
const alicePrivKeyBin = hexToBytes(alicePrivKeyHex)
// Bob's public key
const bobPrivKeyHex = 'd2e71a977bc3900d6b0f787421e3d1a666cd12ca625482b0d9eeffd23489c99f'
const bobPrivKeyBin = hexToBytes(bobPrivKeyHex)
const bobPubKey = getPublicKey(bobPrivKeyBin)
const psf = 'wss://nostr-relay.psfoundation.info'
const followList = [
['p', bobPubKey, psf, 'bob']
]
// Generate a follow list event (kind 3)
const eventTemplate = {
kind: 3,
created_at: Math.floor(Date.now() / 1000),
tags: followList,
content: ''
}
// Sign the event
const signedEvent = finalizeEvent(eventTemplate, alicePrivKeyBin)
// Publish to REST API
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signedEvent)
})
const result = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.property(result, 'accepted')
assert.property(result, 'eventId')
assert.equal(result.eventId, signedEvent.id)
})
it('should publish kind 7 event (reaction/like) - covers example 07', async () => {
// Bob's private key
const bobPrivKeyHex = 'd2e71a977bc3900d6b0f787421e3d1a666cd12ca625482b0d9eeffd23489c99f'
const bobPrivKeyBin = hexToBytes(bobPrivKeyHex)
const bobPubKey = getPublicKey(bobPrivKeyBin)
const psf = 'wss://nostr-relay.psfoundation.info'
// Use a test event ID
const evIdToLike = 'd09b4c5da59be3cd2768aa53fa78b77bf4859084c94f3bf26d401f004a9c8167'
const evIdAuthorPubKey = '2c7e76c0f8dc1dca9d0197c7d19be580a8d074ccada6a2f6ebe056ae41092e92'
// Generate like event (kind 7)
const likeEventTemplate = {
kind: 7,
created_at: Math.floor(Date.now() / 1000),
pubkey: bobPubKey,
tags: [
['e', evIdToLike, psf],
['p', evIdAuthorPubKey, psf]
],
content: '+'
}
// Sign the event
const signedEvent = finalizeEvent(likeEventTemplate, bobPrivKeyBin)
// Publish to REST API
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signedEvent)
})
const result = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.property(result, 'accepted')
assert.property(result, 'eventId')
assert.equal(result.eventId, signedEvent.id)
})
it('should reject invalid event', async () => {
const invalidEvent = {
id: 'invalid',
pubkey: 'invalid',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Test',
sig: 'invalid'
}
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(invalidEvent)
})
const result = await response.json()
// Should reject invalid event - error response format
assert.equal(response.status, 400)
assert.property(result, 'error')
assert.include(result.error, 'Invalid event structure')
})
it('should return 400 when event data is missing', async () => {
// Send empty body - Express will parse as undefined, controller should handle it
const response = await fetch(`${baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: ''
})
// Empty body should be parsed as undefined by Express
const result = await response.json()
assert.equal(response.status, 400)
assert.property(result, 'error')
assert.include(result.error, 'Event data is required')
})
})
})
-173
View File
@@ -1,173 +0,0 @@
/*
Integration tests for GET /req/:subId endpoint.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Server from '../../../bin/server.js'
import { getPublicKey } from 'nostr-tools/pure'
import { hexToBytes } from '@noble/hashes/utils.js'
describe('#req-integration.js', () => {
let server
const baseUrl = 'http://localhost:3002' // Use different port for tests
before(async () => {
// Start test server
server = new Server()
server.config.port = 3002
await server.startServer()
// Wait for server to be ready
await new Promise(resolve => setTimeout(resolve, 1000))
})
after(async () => {
// Stop server
if (server && server.server) {
await new Promise((resolve) => {
server.server.close(() => {
resolve()
})
})
}
})
describe('GET /req/:subId', () => {
it('should query kind 1 events (posts) - covers examples 02, 04', async () => {
// JB55's public key from example 02
const jb55 = '32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
// Create subscription ID
const subId = 'read-posts-' + Date.now()
// Create filters - read posts from JB55
const filters = {
limit: 2,
kinds: [1],
authors: [jb55]
}
// Query events using GET /req/:subId
const filtersJson = encodeURIComponent(JSON.stringify([filters]))
const url = `${baseUrl}/req/${subId}?filters=${filtersJson}`
const response = await fetch(url)
const events = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.isArray(events)
// May be empty if no events exist, but structure should be correct
if (events.length > 0) {
assert.property(events[0], 'id')
assert.property(events[0], 'pubkey')
assert.property(events[0], 'created_at')
assert.property(events[0], 'kind')
assert.property(events[0], 'content')
assert.equal(events[0].kind, 1)
}
})
it('should query Alice posts - covers example 04', async () => {
// Alice's public key
const alicePrivKeyHex = '3292a48aa331aeccce003d50d70fbd79617ba91860abbd2c78fa4a8301e36bc0'
const alicePrivKeyBin = hexToBytes(alicePrivKeyHex)
const alicePubKey = getPublicKey(alicePrivKeyBin)
// Create subscription ID
const subId = 'read-alice-posts-' + Date.now()
// Create filters - read posts from Alice
const filters = {
limit: 2,
kinds: [1],
authors: [alicePubKey]
}
// Query events using GET /req/:subId
const filtersJson = encodeURIComponent(JSON.stringify([filters]))
const url = `${baseUrl}/req/${subId}?filters=${filtersJson}`
const response = await fetch(url)
const events = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.isArray(events)
if (events.length > 0) {
assert.equal(events[0].pubkey, alicePubKey)
assert.equal(events[0].kind, 1)
}
})
it('should query kind 3 events (follow list) - covers example 05', async () => {
// Alice's public key
const alicePrivKeyHex = '3292a48aa331aeccce003d50d70fbd79617ba91860abbd2c78fa4a8301e36bc0'
const alicePrivKeyBin = hexToBytes(alicePrivKeyHex)
const alicePubKey = getPublicKey(alicePrivKeyBin)
// Create subscription ID
const subId = 'get-follow-list-' + Date.now()
// Create filters - get follow list (kind 3) from Alice
const filters = {
limit: 5,
kinds: [3],
authors: [alicePubKey]
}
// Query events using GET /req/:subId
const filtersJson = encodeURIComponent(JSON.stringify([filters]))
const url = `${baseUrl}/req/${subId}?filters=${filtersJson}`
const response = await fetch(url)
const events = await response.json()
// Assert response
assert.equal(response.status, 200)
assert.isArray(events)
if (events.length > 0) {
assert.equal(events[0].kind, 3)
assert.equal(events[0].pubkey, alicePubKey)
assert.isArray(events[0].tags)
}
})
it('should handle filters as individual query params', async () => {
const subId = 'test-sub-' + Date.now()
const url = `${baseUrl}/req/${subId}?kinds=[1]&limit=10`
const response = await fetch(url)
const events = await response.json()
assert.equal(response.status, 200)
assert.isArray(events)
})
it('should return 400 when subscription ID is missing', async () => {
const url = `${baseUrl}/req/?filters=${encodeURIComponent(JSON.stringify([{ kinds: [1] }]))}`
const response = await fetch(url)
await response.json()
// Should return 404 or 400
assert.isAtLeast(response.status, 400)
})
it('should return 400 when filters JSON is invalid', async () => {
const subId = 'test-sub-' + Date.now()
const url = `${baseUrl}/req/${subId}?filters=invalid-json{`
const response = await fetch(url)
const result = await response.json()
assert.equal(response.status, 400)
assert.property(result, 'error')
assert.include(result.error, 'Invalid filters JSON')
})
})
})
@@ -1,198 +0,0 @@
/*
Integration tests for POST /req/:subId SSE subscription and DELETE /req/:subId.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Server from '../../../bin/server.js'
describe('#subscription-integration.js', () => {
let server
const baseUrl = 'http://localhost:3003' // Use different port for tests
before(async () => {
// Start test server
server = new Server()
server.config.port = 3003
await server.startServer()
// Wait for server to be ready
await new Promise(resolve => setTimeout(resolve, 1000))
})
after(async function () {
this.timeout(10000) // Increase timeout for cleanup
// Stop server
if (server && server.server) {
// Close all connections forcefully if available
if (server.server.closeAllConnections) {
server.server.closeAllConnections()
}
await new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve() // Force resolve after 2 seconds
}, 2000)
server.server.close(() => {
clearTimeout(timeout)
resolve()
})
})
}
})
describe('POST /req/:subId', () => {
it('should create SSE subscription', async () => {
const subId = 'test-sub-' + Date.now()
const filters = { kinds: [1], limit: 10 }
const response = await fetch(`${baseUrl}/req/${subId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(filters)
})
// Assert SSE headers
assert.equal(response.headers.get('content-type'), 'text/event-stream')
assert.equal(response.headers.get('cache-control'), 'no-cache')
assert.equal(response.headers.get('connection'), 'keep-alive')
// Read initial connection message
const reader = response.body.getReader()
const decoder = new TextDecoder()
try {
const { value } = await reader.read()
const text = decoder.decode(value)
assert.include(text, 'connected')
assert.include(text, subId)
} finally {
reader.releaseLock()
}
})
it('should return 400 when subscription ID is missing', async () => {
const filters = { kinds: [1] }
const response = await fetch(`${baseUrl}/req/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(filters)
})
// Should return 404 or 400
assert.isAtLeast(response.status, 400)
})
it('should return 400 when filters are missing', async () => {
const subId = 'test-sub-' + Date.now()
const response = await fetch(`${baseUrl}/req/${subId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
})
const result = await response.json()
assert.equal(response.status, 400)
assert.property(result, 'error')
assert.include(result.error, 'Filters are required')
})
})
describe('DELETE /req/:subId', () => {
it('should close a subscription', async () => {
const subId = 'test-sub-' + Date.now()
const response = await fetch(`${baseUrl}/req/${subId}`, {
method: 'DELETE'
})
// May return 200 if subscription exists, or 500 if it doesn't
// The important thing is it doesn't crash
assert.isAtMost(response.status, 500)
})
it('should return 400 when subscription ID is missing', async () => {
const response = await fetch(`${baseUrl}/req/`, {
method: 'DELETE'
})
// Should return 404 or 400
assert.isAtLeast(response.status, 400)
})
})
describe('PUT /req/:subId', () => {
it('should create SSE subscription (alternative method)', async function () {
this.timeout(10000) // Increase timeout for this test
const subId = 'test-sub-' + Date.now()
const filters = { kinds: [1], limit: 10 }
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 8000)
let response
try {
response = await fetch(`${baseUrl}/req/${subId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(filters),
signal: controller.signal
})
// Assert SSE headers
assert.equal(response.headers.get('content-type'), 'text/event-stream')
clearTimeout(timeoutId)
// Consume the stream to prevent hanging
const reader = response.body.getReader()
const decoder = new TextDecoder()
try {
// Read initial connection message with timeout
const readPromise = reader.read()
const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve({ value: null, done: true }), 2000))
const { value, done } = await Promise.race([readPromise, timeoutPromise])
if (value && !done) {
const text = decoder.decode(value)
assert.include(text, 'connected')
}
} finally {
reader.releaseLock()
}
} catch (err) {
// AbortController aborted - this is expected
if (err.name !== 'AbortError') {
throw err
}
} finally {
clearTimeout(timeoutId)
// Always close the subscription
try {
await fetch(`${baseUrl}/req/${subId}`, {
method: 'DELETE'
})
} catch (err) {
// Ignore errors when closing
}
}
})
})
})
@@ -1,163 +0,0 @@
/*
Integration tests for ManageSubscriptionUseCase with real adapter.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Adapters from '../../../src/adapters/index.js'
import ManageSubscriptionUseCase from '../../../src/use-cases/manage-subscription.js'
describe('#manage-subscription-integration.js', () => {
let adapters
let uut
before(async () => {
// Initialize adapters (will connect to real relay)
adapters = new Adapters()
await adapters.start()
uut = new ManageSubscriptionUseCase({ adapters })
})
after(async () => {
// Clean up all subscriptions and disconnect from all relays
// Note: This is a simplified cleanup - in production you'd track all subscriptions
if (adapters && adapters.nostrRelays) {
await Promise.allSettled(
adapters.nostrRelays.map(relay => relay.disconnect())
)
}
})
describe('#createSubscription()', () => {
it('should successfully create a subscription', async () => {
const subscriptionId = 'test-sub-' + Date.now()
const filters = [{ kinds: [1], limit: 5 }]
let eventReceived = false
let eoseReceived = false
const onEvent = (event) => {
eventReceived = true
assert.property(event, 'id')
assert.property(event, 'kind')
}
const onEose = () => {
eoseReceived = true
}
const onClosed = () => {
// Handler for closed events
}
await uut.createSubscription(subscriptionId, filters, onEvent, onEose, onClosed)
// Assert subscription exists
assert.isTrue(uut.hasSubscription(subscriptionId))
// Wait a bit for events/EOSE
await new Promise(resolve => setTimeout(resolve, 2000))
// EOSE should be received (or events)
// Note: May not receive events if none exist, but EOSE should come
assert.isTrue(eoseReceived || eventReceived)
// Clean up
if (uut.hasSubscription(subscriptionId)) {
await uut.closeSubscription(subscriptionId)
}
})
it('should prevent duplicate subscriptions', async () => {
const subscriptionId = 'test-dup-' + Date.now()
const filters = [{ kinds: [1] }]
await uut.createSubscription(subscriptionId, filters)
try {
await uut.createSubscription(subscriptionId, filters)
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'already exists')
}
// Clean up
if (uut.hasSubscription(subscriptionId)) {
await uut.closeSubscription(subscriptionId)
}
})
it('should handle subscription with no events', async () => {
const subscriptionId = 'test-empty-' + Date.now()
const filters = [{ kinds: [99999], limit: 1 }] // Unlikely to have events
let eoseReceived = false
const onEose = () => {
eoseReceived = true
}
await uut.createSubscription(subscriptionId, filters, null, onEose, null)
// Wait for EOSE
await new Promise(resolve => setTimeout(resolve, 2000))
// Should receive EOSE even with no events
assert.isTrue(eoseReceived)
// Clean up
if (uut.hasSubscription(subscriptionId)) {
await uut.closeSubscription(subscriptionId)
}
})
})
describe('#closeSubscription()', () => {
it('should successfully close a subscription', async () => {
const subscriptionId = 'test-close-' + Date.now()
const filters = [{ kinds: [1] }]
await uut.createSubscription(subscriptionId, filters)
assert.isTrue(uut.hasSubscription(subscriptionId))
await uut.closeSubscription(subscriptionId)
// Assert subscription is removed
assert.isFalse(uut.hasSubscription(subscriptionId))
})
it('should return successfully when closing non-existent subscription (idempotent)', async () => {
const subscriptionId = 'non-existent-sub'
// Should not throw - idempotent operation
await uut.closeSubscription(subscriptionId)
// Should return successfully without error
assert.isTrue(true, 'closeSubscription should succeed for non-existent subscription')
})
})
describe('#hasSubscription()', () => {
it('should return false for non-existent subscription', () => {
assert.isFalse(uut.hasSubscription('non-existent'))
})
it('should return true for existing subscription', async () => {
const subscriptionId = 'test-has-' + Date.now()
const filters = [{ kinds: [1] }]
assert.isFalse(uut.hasSubscription(subscriptionId))
await uut.createSubscription(subscriptionId, filters)
assert.isTrue(uut.hasSubscription(subscriptionId))
// Clean up
if (uut.hasSubscription(subscriptionId)) {
await uut.closeSubscription(subscriptionId)
}
})
})
})
@@ -1,104 +0,0 @@
/*
Integration tests for PublishEventUseCase with real adapter.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Adapters from '../../../src/adapters/index.js'
import PublishEventUseCase from '../../../src/use-cases/publish-event.js'
import { finalizeEvent, generateSecretKey } from 'nostr-tools/pure'
describe('#publish-event-integration.js', () => {
let adapters
let uut
before(async () => {
// Initialize adapters (will connect to real relay)
adapters = new Adapters()
await adapters.start()
uut = new PublishEventUseCase({ adapters })
})
after(async () => {
// Clean up adapters - disconnect from all relays
if (adapters && adapters.nostrRelays) {
await Promise.allSettled(
adapters.nostrRelays.map(relay => relay.disconnect())
)
}
})
describe('#execute()', () => {
it('should successfully publish a valid event', async () => {
// Generate keys
const sk = generateSecretKey()
// Create event template
const eventTemplate = {
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'Integration test post from use case'
}
// Sign the event
const signedEvent = finalizeEvent(eventTemplate, sk)
// Execute use case
const result = await uut.execute(signedEvent)
// Assert result
assert.property(result, 'accepted')
assert.property(result, 'message')
assert.property(result, 'eventId')
assert.equal(result.eventId, signedEvent.id)
})
it('should reject invalid event structure', async () => {
const invalidEvent = {
id: 'invalid',
pubkey: 'invalid',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Test',
sig: 'invalid'
}
try {
await uut.execute(invalidEvent)
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'Invalid event structure')
}
})
it('should handle relay rejection', async () => {
// Generate keys
const sk = generateSecretKey()
// Create a duplicate event (if we send same event twice)
const eventTemplate = {
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'Duplicate test post'
}
const signedEvent = finalizeEvent(eventTemplate, sk)
// Publish first time
const result1 = await uut.execute(signedEvent)
assert.property(result1, 'accepted')
// Try to publish again (may be rejected as duplicate)
const result2 = await uut.execute(signedEvent)
assert.property(result2, 'accepted')
// Result may be accepted or rejected depending on relay
})
})
})
@@ -1,95 +0,0 @@
/*
Integration tests for QueryEventsUseCase with real adapter.
These tests require a running Nostr relay.
*/
// npm libraries
import { assert } from 'chai'
// Unit under test
import Adapters from '../../../src/adapters/index.js'
import QueryEventsUseCase from '../../../src/use-cases/query-events.js'
describe('#query-events-integration.js', () => {
let adapters
let uut
before(async () => {
// Initialize adapters (will connect to real relay)
adapters = new Adapters()
await adapters.start()
uut = new QueryEventsUseCase({ adapters })
})
after(async () => {
// Clean up adapters - disconnect from all relays
if (adapters && adapters.nostrRelays) {
await Promise.allSettled(
adapters.nostrRelays.map(relay => relay.disconnect())
)
}
})
describe('#execute()', () => {
it('should successfully query events', async () => {
const filters = [{ kinds: [1], limit: 5 }]
const subscriptionId = 'test-query-' + Date.now()
const events = await uut.execute(filters, subscriptionId)
// Assert result is an array
assert.isArray(events)
// If events are returned, verify structure
if (events.length > 0) {
assert.property(events[0], 'id')
assert.property(events[0], 'pubkey')
assert.property(events[0], 'created_at')
assert.property(events[0], 'kind')
assert.property(events[0], 'content')
assert.equal(events[0].kind, 1)
}
})
it('should handle empty results', async () => {
// Query for events that likely don't exist
const filters = [{ kinds: [99999], limit: 1 }]
const subscriptionId = 'test-empty-' + Date.now()
const events = await uut.execute(filters, subscriptionId)
// Should return empty array, not throw
assert.isArray(events)
assert.equal(events.length, 0)
})
it('should handle multiple filters', async function () {
// Increase timeout for this test - needs to be longer than use case timeout (30s)
this.timeout(35000)
const filters = [
{ kinds: [1], limit: 2 },
{ kinds: [3], limit: 2 }
]
const subscriptionId = 'test-multi-' + Date.now()
const events = await uut.execute(filters, subscriptionId)
// Should return array (may be empty)
assert.isArray(events)
})
it('should timeout if EOSE not received', async () => {
// This test may take up to 30 seconds
// Use a filter that might not return EOSE quickly
const filters = [{ kinds: [1] }] // No limit, might timeout
const subscriptionId = 'test-timeout-' + Date.now()
// Should eventually return (even if empty)
const events = await uut.execute(filters, subscriptionId)
assert.isArray(events)
})
})
})
+125
View File
@@ -0,0 +1,125 @@
/*
Unit tests for FullNodeRPCAdapter.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import axios from 'axios'
import FullNodeRPCAdapter from '../../../src/adapters/full-node-rpc.js'
describe('#full-node-rpc.js', () => {
let sandbox
let axiosCreateStub
let mockAxiosInstance
const baseConfig = {
fullNode: {
rpcBaseUrl: 'http://127.0.0.1:8332',
rpcUsername: 'user',
rpcPassword: 'pass',
rpcTimeoutMs: 1000,
rpcRequestIdPrefix: 'test'
}
}
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAxiosInstance = {
defaults: {
baseURL: baseConfig.fullNode.rpcBaseUrl
},
post: sandbox.stub()
}
axiosCreateStub = sandbox.stub(axios, 'create').returns(mockAxiosInstance)
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should throw if full node config is missing', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new FullNodeRPCAdapter({ config: {} })
}, /Full node RPC configuration is required/)
})
it('should create axios client with provided configuration', () => {
// eslint-disable-next-line no-new
new FullNodeRPCAdapter({ config: baseConfig })
assert.isTrue(axiosCreateStub.calledOnce)
const options = axiosCreateStub.getCall(0).args[0]
assert.equal(options.baseURL, baseConfig.fullNode.rpcBaseUrl)
assert.equal(options.timeout, baseConfig.fullNode.rpcTimeoutMs)
assert.deepEqual(options.auth, {
username: baseConfig.fullNode.rpcUsername,
password: baseConfig.fullNode.rpcPassword
})
})
})
describe('#call()', () => {
it('should call RPC method and return result', async () => {
mockAxiosInstance.post.resolves({ data: { result: 'hash' } })
const uut = new FullNodeRPCAdapter({ config: baseConfig })
const result = await uut.call('getbestblockhash', [])
assert.equal(result, 'hash')
assert.isTrue(mockAxiosInstance.post.calledOnce)
const [, payload] = mockAxiosInstance.post.getCall(0).args
assert.deepEqual(payload, {
jsonrpc: '1.0',
id: 'test-getbestblockhash',
method: 'getbestblockhash',
params: []
})
})
it('should use custom request id when provided', async () => {
mockAxiosInstance.post.resolves({ data: { result: 123 } })
const uut = new FullNodeRPCAdapter({ config: baseConfig })
await uut.call('getblockcount', [], 'custom-id')
const [, payload] = mockAxiosInstance.post.getCall(0).args
assert.equal(payload.id, 'custom-id')
})
it('should throw formatted error when RPC returns error', async () => {
mockAxiosInstance.post.resolves({
data: {
error: { message: 'RPC error' }
}
})
const uut = new FullNodeRPCAdapter({ config: baseConfig })
try {
await uut.call('failing', [])
assert.fail('Unexpected success')
} catch (err) {
assert.equal(err.message, 'RPC error')
assert.equal(err.status, 400)
}
})
it('should translate network errors into 503 status', async () => {
mockAxiosInstance.post.rejects(new Error('ENOTFOUND fullnode'))
const uut = new FullNodeRPCAdapter({ config: baseConfig })
try {
await uut.call('getblockcount', [])
assert.fail('Unexpected success')
} catch (err) {
assert.equal(
err.message,
'Network error: Could not communicate with full node or other external service.'
)
assert.equal(err.status, 503)
}
})
})
})
-304
View File
@@ -1,304 +0,0 @@
/*
Unit tests for NostrRelayAdapter.
*/
/*
// npm libraries
import { assert } from 'chai'
import sinon from 'sinon'
// Mocking data libraries
import {
mockKind1Event,
validEventId
} from '../mocks/event-mocks.js'
import {
mockOkAccepted,
mockEventMessage,
mockEoseMessage,
mockClosedMessage
} from '../mocks/nostr-relay-mocks.js'
// Unit under test
// Note: WebSocket mocking for ES modules is complex. These tests focus on
// testing the adapter's logic that can be tested without full WebSocket mocking.
import NostrRelayAdapter from '../../../src/adapters/nostr-relay.js'
describe('#nostr-relay.js', () => {
let sandbox
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
uut = new NostrRelayAdapter({
relayUrl: 'wss://test-relay.example.com'
})
})
afterEach(() => {
sandbox.restore()
})
describe('#connect()', () => {
it('should return immediately if already connected', async () => {
// Manually set connection state
uut.isConnected = true
uut.ws = { close: sandbox.stub() }
await uut.connect()
// Should not create new connection
assert.isTrue(uut.isConnected)
})
// Note: Full WebSocket connection testing requires integration tests
// due to ES module import limitations
})
describe('#sendEvent()', () => {
it('should queue message when disconnected', async () => {
uut.isConnected = false
uut.ws = null
// Mock connect to resolve immediately
uut.connect = sandbox.stub().resolves()
// Start sending (will queue)
uut.sendEvent(mockKind1Event).catch(() => {
// Expected to fail or timeout without real WebSocket
})
// Should queue message and attempt connection
// Wait a bit for async operations
await new Promise(resolve => setTimeout(resolve, 10))
assert.isTrue(uut.pendingMessages.length > 0 || uut.connect.called)
})
it('should set up event resolver', async () => {
uut.isConnected = true
uut.ws = { send: sandbox.stub() }
// Mock sendMessage to resolve immediately
uut.sendMessage = sandbox.stub().resolves()
// Start sending
const sendPromise = uut.sendEvent(mockKind1Event).catch(() => {
// Expected without real WebSocket response
})
// Wait a tick for Promise constructor to run
await new Promise(resolve => setImmediate(resolve))
// Verify resolver was set up
assert.isTrue(uut.eventResolvers.has(mockKind1Event.id))
// Clean up
uut.eventResolvers.delete(mockKind1Event.id)
// Prevent timeout error
sendPromise.catch(() => {})
})
// Note: Full sendEvent testing with WebSocket responses requires integration tests
})
describe('#sendReq()', () => {
it('should store handlers for subscription', async () => {
uut.isConnected = true
uut.ws = { send: sandbox.stub() }
uut.connect = sandbox.stub().resolves()
const subscriptionId = 'test-sub-123'
const filters = [{ kinds: [1] }]
const handlers = {
onEvent: sandbox.stub(),
onEose: sandbox.stub(),
onClosed: sandbox.stub()
}
await uut.sendReq(subscriptionId, filters, handlers)
// Assert handlers were stored
assert.isTrue(uut.subscriptionHandlers.has(subscriptionId))
assert.deepEqual(uut.subscriptionHandlers.get(subscriptionId), handlers)
})
it('should connect before sending if disconnected', async () => {
uut.isConnected = false
uut.connect = sandbox.stub().resolves()
const subscriptionId = 'test-sub-123'
const filters = [{ kinds: [1] }]
const handlers = {}
await uut.sendReq(subscriptionId, filters, handlers)
assert.isTrue(uut.connect.called)
})
})
describe('#sendClose()', () => {
it('should clean up handlers for subscription', async () => {
uut.isConnected = true
uut.ws = { send: sandbox.stub() }
const subscriptionId = 'test-sub-123'
uut.subscriptionHandlers.set(subscriptionId, {})
uut.messageHandlers.set(subscriptionId, {})
await uut.sendClose(subscriptionId)
// Assert handlers were cleaned up
assert.isFalse(uut.subscriptionHandlers.has(subscriptionId))
assert.isFalse(uut.messageHandlers.has(subscriptionId))
})
})
describe('#handleMessage()', () => {
it('should handle EVENT message', () => {
// Use the subscription ID from the mock message
const subscriptionId = 'subscription-id-123'
const onEventHandler = sandbox.stub()
uut.subscriptionHandlers.set(subscriptionId, {
onEvent: onEventHandler
})
const message = mockEventMessage
uut.handleMessage(message)
assert.isTrue(onEventHandler.calledOnce)
assert.deepEqual(onEventHandler.getCall(0).args[0], mockKind1Event)
})
it('should handle EOSE message', () => {
// Use the subscription ID from the mock message
const subscriptionId = 'subscription-id-123'
const onEoseHandler = sandbox.stub()
uut.subscriptionHandlers.set(subscriptionId, {
onEose: onEoseHandler
})
const message = mockEoseMessage
uut.handleMessage(message)
assert.isTrue(onEoseHandler.calledOnce)
})
it('should handle CLOSED message', () => {
// Use the subscription ID from the mock message
const subscriptionId = 'subscription-id-123'
const onClosedHandler = sandbox.stub()
uut.subscriptionHandlers.set(subscriptionId, {
onClosed: onClosedHandler
})
const message = mockClosedMessage
uut.handleMessage(message)
assert.isTrue(onClosedHandler.calledOnce)
assert.equal(onClosedHandler.getCall(0).args[0], 'subscription closed')
})
it('should handle OK message', () => {
const eventId = validEventId
let resolver = null
uut.eventResolvers.set(eventId, (result) => {
resolver = result
})
const message = mockOkAccepted
uut.handleMessage(message)
assert.isNotNull(resolver)
assert.isTrue(resolver.accepted)
assert.isFalse(uut.eventResolvers.has(eventId))
})
it('should handle NOTICE message', () => {
const message = ['NOTICE', 'rate limited']
// Should not throw
uut.handleMessage(message)
})
it('should ignore invalid message format', () => {
const message = 'invalid'
// Should not throw
uut.handleMessage(message)
})
it('should ignore empty messages', () => {
const message = []
// Should not throw
uut.handleMessage(message)
})
})
describe('#disconnect()', () => {
it('should disconnect from relay', async () => {
const mockWs = { close: sandbox.stub() }
uut.isConnected = true
uut.ws = mockWs
await uut.disconnect()
assert.isTrue(mockWs.close.called)
assert.isFalse(uut.isConnected)
assert.isNull(uut.ws)
})
it('should handle disconnect when already disconnected', async () => {
uut.isConnected = false
uut.ws = null
await uut.disconnect()
assert.isFalse(uut.isConnected)
})
})
describe('#handleError()', () => {
it('should handle WebSocket errors', () => {
uut.isConnected = true
const error = new Error('WebSocket error')
uut.handleError(error)
assert.isFalse(uut.isConnected)
})
})
describe('#handleClose()', () => {
it('should attempt reconnection on close', async () => {
uut.isConnected = true
uut.reconnectAttempts = 0
uut.maxReconnectAttempts = 5
// Mock connect to avoid actual connection
uut.connect = sandbox.stub().resolves()
uut.handleClose()
// Wait for reconnection attempt
await new Promise(resolve => setTimeout(resolve, 110))
// Should attempt reconnection
assert.equal(uut.reconnectAttempts, 1)
})
it('should stop reconnecting after max attempts', async () => {
uut.isConnected = true
uut.reconnectAttempts = 5
uut.maxReconnectAttempts = 5
uut.connect = sandbox.stub().resolves()
uut.handleClose()
await new Promise(resolve => setTimeout(resolve, 110))
// Should not increment beyond max
assert.equal(uut.reconnectAttempts, 5)
})
})
})
*/
@@ -0,0 +1,214 @@
/*
Unit tests for BlockchainRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import BlockchainRESTController from '../../../src/controllers/rest-api/full-node/blockchain/controller.js'
import {
createMockRequest,
createMockResponse
} from '../mocks/controller-mocks.js'
describe('#blockchain-controller.js', () => {
let sandbox
let mockUseCases
let mockAdapters
let uut
const createBlockchainUseCaseStubs = () => ({
getBestBlockHash: sandbox.stub().resolves('hash'),
getBlockchainInfo: sandbox.stub().resolves({}),
getBlockCount: sandbox.stub().resolves(123),
getBlockHeader: sandbox.stub().resolves({ header: true }),
getBlockHeaders: sandbox.stub().resolves(['header']),
getChainTips: sandbox.stub().resolves(['tip']),
getDifficulty: sandbox.stub().resolves(1),
getMempoolEntry: sandbox.stub().resolves({}),
getMempoolEntries: sandbox.stub().resolves([]),
getMempoolAncestors: sandbox.stub().resolves([]),
getMempoolInfo: sandbox.stub().resolves({ size: 1 }),
getRawMempool: sandbox.stub().resolves(['tx']),
getTxOut: sandbox.stub().resolves({ value: 1 }),
getTxOutProof: sandbox.stub().resolves('proof'),
getTxOutProofs: sandbox.stub().resolves(['proof']),
verifyTxOutProof: sandbox.stub().resolves(['txid']),
verifyTxOutProofs: sandbox.stub().resolves([['txid']]),
getBlock: sandbox.stub().resolves({ hash: 'abc' }),
getBlockHash: sandbox.stub().resolves('blockhash')
})
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {
fullNode: {
validateArraySize: sandbox.stub().returns(true)
}
}
mockUseCases = {
blockchain: createBlockchainUseCaseStubs()
}
uut = new BlockchainRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new BlockchainRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require blockchain use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new BlockchainRESTController({ adapters: mockAdapters, useCases: {} })
}, /Blockchain use cases required/)
})
})
describe('#root()', () => {
it('should return service status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'blockchain' })
})
})
describe('#getBestBlockHash()', () => {
it('should return hash on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getBestBlockHash(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.jsonData, 'hash')
assert.isTrue(mockUseCases.blockchain.getBestBlockHash.calledOnce)
})
it('should handle errors via handleError()', async () => {
const error = new Error('failure')
error.status = 422
mockUseCases.blockchain.getBestBlockHash.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getBestBlockHash(req, res)
assert.equal(res.statusValue, 422)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
describe('#getBlockHeaderSingle()', () => {
it('should return 400 if hash is missing', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getBlockHeaderSingle(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should call use case with verbose flag', async () => {
const hash = 'a'.repeat(64)
const req = createMockRequest({
params: { hash },
query: { verbose: 'true' }
})
const res = createMockResponse()
await uut.getBlockHeaderSingle(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(
mockUseCases.blockchain.getBlockHeader.calledOnceWithExactly({
hash,
verbose: true
})
)
})
})
describe('#getBlockHeaderBulk()', () => {
it('should return error if hashes is not array', async () => {
const req = createMockRequest({
body: { hashes: 'not-an-array' },
locals: {}
})
const res = createMockResponse()
await uut.getBlockHeaderBulk(req, res)
assert.equal(res.statusValue, 400)
assert.include(res.jsonData.error, 'hashes needs to be an array')
})
it('should validate array size and call use case', async () => {
const hash = 'a'.repeat(64)
const req = createMockRequest({
body: { hashes: [hash], verbose: true }
})
const res = createMockResponse()
mockUseCases.blockchain.getBlockHeaders.resolves(['result'])
await uut.getBlockHeaderBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, ['result'])
assert.isTrue(
mockAdapters.fullNode.validateArraySize.calledOnceWithExactly(1)
)
assert.isTrue(
mockUseCases.blockchain.getBlockHeaders.calledOnceWithExactly({
hashes: [hash],
verbose: true
})
)
})
it('should return error if array size invalid', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({
body: { hashes: ['a'.repeat(64)] },
locals: {}
})
const res = createMockResponse()
await uut.getBlockHeaderBulk(req, res)
assert.equal(res.statusValue, 400)
assert.equal(res.jsonData.error, 'Array too large.')
})
})
describe('#verifyTxOutProofBulk()', () => {
it('should flatten proof responses', async () => {
mockUseCases.blockchain.verifyTxOutProofs.resolves([['txid-a'], ['txid-b']])
const req = createMockRequest({
body: { proofs: ['proof-a', 'proof-b'] },
locals: {}
})
const res = createMockResponse()
await uut.verifyTxOutProofBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, ['txid-a', 'txid-b'])
})
})
})
@@ -0,0 +1,88 @@
/*
Unit tests for ControlRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import ControlRESTController from '../../../src/controllers/rest-api/full-node/control/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#control-controller.js', () => {
let sandbox
let mockAdapters
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {}
mockUseCases = {
control: {
getNetworkInfo: sandbox.stub().resolves({ version: 1 })
}
}
uut = new ControlRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new ControlRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require control use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new ControlRESTController({ adapters: mockAdapters, useCases: {} })
}, /Control use cases required/)
})
})
describe('#root()', () => {
it('should return control status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'control' })
})
})
describe('#getNetworkInfo()', () => {
it('should return network info on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getNetworkInfo(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { version: 1 })
})
it('should handle errors via handleError', async () => {
const error = new Error('failure')
error.status = 503
mockUseCases.control.getNetworkInfo.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getNetworkInfo(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
})
@@ -0,0 +1,106 @@
/*
Unit tests for DiscoveryController.
*/
import { assert } from 'chai'
import DiscoveryController from '../../../src/controllers/discovery/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#discovery-controller.js', () => {
const makeController = ({ enabled = true } = {}) => {
return new DiscoveryController({
apiPrefix: '/v6',
getX402Settings: () => ({
enabled,
facilitatorUrl: 'http://localhost:4345/facilitator',
serverAddress: 'bitcoincash:qtestaddress',
priceSat: 200
}),
getDiscoveryDocuments: () => ({
openapi: { openapi: '3.0.3', paths: { '/v6/price/bchusd': {} } },
swagger: { swagger: '2.0', paths: { '/v6/price/bchusd': {} } },
llms: '# psf-bch-api',
agent: { awp_version: '0.1', actions: [] }
})
})
}
describe('x402 disabled gating', () => {
it('should return 404 for all discovery endpoints when x402 disabled', async () => {
const uut = makeController({ enabled: false })
const req = createMockRequest()
const handlers = [
uut.x402Manifest,
uut.openapi,
uut.swagger,
uut.llmsTxt,
uut.agentManifest
]
for (const handler of handlers) {
const res = createMockResponse()
await handler(req, res)
assert.equal(res.statusValue, 404)
assert.deepEqual(res.jsonData, { error: 'Not found' })
}
})
})
describe('x402 enabled responses', () => {
it('should return x402 manifest schema fields', async () => {
const uut = makeController({ enabled: true })
const req = createMockRequest()
const res = createMockResponse()
await uut.x402Manifest(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.jsonData.x402Version, 2)
assert.isArray(res.jsonData.resources)
assert.equal(res.jsonData.resources[0].accepts[0].scheme, 'utxo')
assert.equal(res.jsonData.resources[0].accepts[0].amount, '200')
})
it('should return openapi and swagger docs', async () => {
const uut = makeController({ enabled: true })
const req = createMockRequest()
const openapiRes = createMockResponse()
await uut.openapi(req, openapiRes)
assert.equal(openapiRes.statusValue, 200)
assert.equal(openapiRes.jsonData.openapi, '3.0.3')
const swaggerRes = createMockResponse()
await uut.swagger(req, swaggerRes)
assert.equal(swaggerRes.statusValue, 200)
assert.equal(swaggerRes.jsonData.swagger, '2.0')
})
it('should return llms.txt as text/plain', async () => {
const uut = makeController({ enabled: true })
const req = createMockRequest()
const res = createMockResponse()
await uut.llmsTxt(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.headers['Content-Type'], 'text/plain; charset=utf-8')
assert.equal(res.writeData[0], '# psf-bch-api')
assert.isTrue(res.endCalled)
})
it('should return agent manifest json', async () => {
const uut = makeController({ enabled: true })
const req = createMockRequest()
const res = createMockResponse()
await uut.agentManifest(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.jsonData.awp_version, '0.1')
assert.isArray(res.jsonData.actions)
})
})
})
@@ -0,0 +1,25 @@
/*
Unit tests for discovery document builder.
*/
import { assert } from 'chai'
import { buildDiscoveryDocuments } from '../../../src/discovery/build-documents.js'
describe('#discovery-build-documents.js', () => {
it('should build openapi and swagger documents with v6 paths', () => {
const docs = buildDiscoveryDocuments()
assert.property(docs, 'openapi')
assert.property(docs, 'swagger')
assert.property(docs, 'llms')
assert.property(docs, 'agent')
assert.isString(docs.openapi.openapi)
assert.equal(docs.swagger.swagger, '2.0')
assert.isAbove(Object.keys(docs.openapi.paths).length, 0)
const hasV6Path = Object.keys(docs.openapi.paths).some(path => path.startsWith('/v6/'))
assert.isTrue(hasV6Path)
})
})
@@ -0,0 +1,43 @@
/*
Unit tests for DiscoveryRouter.
*/
import { assert } from 'chai'
import DiscoveryRouter from '../../../src/controllers/discovery/router.js'
describe('#discovery-router.js', () => {
it('should require app object in attach()', () => {
const uut = new DiscoveryRouter()
assert.throws(() => uut.attach(), /Must pass app object/)
})
it('should register all discovery routes', () => {
const calls = []
const app = {
use: () => {}
}
const mockRouter = {
get: (path, handler) => calls.push({ path, handler })
}
const mockController = {
x402Manifest: () => {},
openapi: () => {},
swagger: () => {},
llmsTxt: () => {},
agentManifest: () => {}
}
const uut = new DiscoveryRouter({ controller: mockController })
uut.router = mockRouter
uut.attach(app)
assert.equal(calls.length, 5)
assert.deepEqual(
calls.map(x => x.path),
['/.well-known/x402', '/openapi.json', '/swagger.json', '/llms.txt', '/.well-known/agent.json']
)
})
})
@@ -0,0 +1,117 @@
/*
Unit tests for DSProofRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import DSProofRESTController from '../../../src/controllers/rest-api/full-node/dsproof/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#dsproof-controller.js', () => {
let sandbox
let mockAdapters
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {}
mockUseCases = {
dsproof: {
getDSProof: sandbox.stub().resolves({ proof: true })
}
}
uut = new DSProofRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new DSProofRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require dsproof use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new DSProofRESTController({ adapters: mockAdapters, useCases: {} })
}, /DSProof use cases required/)
})
})
describe('#root()', () => {
it('should return dsproof status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'dsproof' })
})
})
describe('#getDSProof()', () => {
it('should validate txid presence', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getDSProof(req, res)
assert.equal(res.statusValue, 400)
assert.include(res.jsonData.error, 'txid can not be empty')
})
it('should validate txid length', async () => {
const req = createMockRequest({ params: { txid: 'abc' } })
const res = createMockResponse()
await uut.getDSProof(req, res)
assert.equal(res.statusValue, 400)
assert.include(res.jsonData.error, 'txid must be of length 64')
})
it('should call use case with derived verbose when valid', async () => {
const txid = 'a'.repeat(64)
const req = createMockRequest({
params: { txid },
query: { verbose: 'true' }
})
const res = createMockResponse()
await uut.getDSProof(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.dsproof.getDSProof.calledOnceWithExactly({
txid,
verbose: 3
}))
assert.deepEqual(res.jsonData, { proof: true })
})
it('should handle errors via handleError', async () => {
const txid = 'a'.repeat(64)
const error = new Error('failure')
error.status = 422
mockUseCases.dsproof.getDSProof.rejects(error)
const req = createMockRequest({ params: { txid } })
const res = createMockResponse()
await uut.getDSProof(req, res)
assert.equal(res.statusValue, 422)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
})
@@ -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'
})
})
})
})
@@ -1,187 +0,0 @@
/*
Unit tests for EventRESTControllerLib.
*/
// npm libraries
import { assert } from 'chai'
import sinon from 'sinon'
// Mocking data libraries
import {
mockKind1Event,
mockKind0Event
} from '../mocks/event-mocks.js'
import {
createMockRequestWithBody,
createMockResponse
} from '../mocks/controller-mocks.js'
// Unit under test
import EventRESTControllerLib from '../../../src/controllers/rest-api/event/controller.js'
describe('#event-controller.js', () => {
let sandbox
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
// Create mock use cases
mockUseCases = {
publishEvent: {
execute: sandbox.stub()
}
}
uut = new EventRESTControllerLib({
adapters: {},
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#publishEvent()', () => {
it('should successfully publish an event', async () => {
const req = createMockRequestWithBody(mockKind1Event)
const res = createMockResponse()
mockUseCases.publishEvent.execute.resolves({
accepted: true,
message: 'event saved',
eventId: mockKind1Event.id
})
await uut.publishEvent(req, res)
// Assert use case was called
assert.isTrue(mockUseCases.publishEvent.execute.calledOnce)
assert.deepEqual(mockUseCases.publishEvent.execute.getCall(0).args[0], mockKind1Event)
// Assert response
assert.equal(res.statusValue, 200)
assert.property(res.jsonData, 'accepted')
assert.isTrue(res.jsonData.accepted)
assert.equal(res.jsonData.eventId, mockKind1Event.id)
})
it('should return 400 when event is rejected', async () => {
const req = createMockRequestWithBody(mockKind1Event)
const res = createMockResponse()
mockUseCases.publishEvent.execute.resolves({
accepted: false,
message: 'duplicate: event already exists',
eventId: mockKind1Event.id
})
await uut.publishEvent(req, res)
// Assert response status is 400
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'accepted')
assert.isFalse(res.jsonData.accepted)
})
it('should return 400 when event data is missing', async () => {
const req = createMockRequestWithBody(null)
const res = createMockResponse()
await uut.publishEvent(req, res)
// Assert use case was not called
assert.isFalse(mockUseCases.publishEvent.execute.called)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Event data is required')
})
it('should handle use case errors', async () => {
const req = createMockRequestWithBody(mockKind1Event)
const res = createMockResponse()
mockUseCases.publishEvent.execute.rejects(new Error('Network error'))
await uut.publishEvent(req, res)
// Assert error response
assert.equal(res.statusValue, 500)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Network error')
})
it('should return 400 for validation errors', async () => {
const req = createMockRequestWithBody(mockKind1Event)
const res = createMockResponse()
mockUseCases.publishEvent.execute.rejects(new Error('Invalid event structure'))
await uut.publishEvent(req, res)
// Assert validation error returns 400
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Invalid event structure')
})
it('should handle errors with missing message', async () => {
const req = createMockRequestWithBody(mockKind1Event)
const res = createMockResponse()
const error = new Error()
error.message = undefined
mockUseCases.publishEvent.execute.rejects(error)
await uut.publishEvent(req, res)
// Assert error response with default message
assert.equal(res.statusValue, 500)
assert.property(res.jsonData, 'error')
assert.equal(res.jsonData.error, 'Internal server error')
})
it('should publish different event kinds', async () => {
const req = createMockRequestWithBody(mockKind0Event)
const res = createMockResponse()
mockUseCases.publishEvent.execute.resolves({
accepted: true,
message: 'event saved',
eventId: mockKind0Event.id
})
await uut.publishEvent(req, res)
assert.isTrue(mockUseCases.publishEvent.execute.calledOnce)
assert.equal(res.statusValue, 200)
assert.isTrue(res.jsonData.accepted)
})
})
describe('#constructor()', () => {
it('should require adapters instance', () => {
try {
// eslint-disable-next-line no-new
new EventRESTControllerLib({ useCases: mockUseCases })
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'Adapters library required')
}
})
it('should require useCases instance', () => {
try {
// eslint-disable-next-line no-new
new EventRESTControllerLib({ adapters: {} })
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'Use Cases library required')
}
})
})
})
@@ -0,0 +1,481 @@
/*
Unit tests for FulcrumRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import FulcrumRESTController from '../../../src/controllers/rest-api/fulcrum/controller.js'
import {
createMockRequest,
createMockResponse
} from '../mocks/controller-mocks.js'
// Valid mainnet cash address for testing
const VALID_MAINNET_ADDRESS = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
describe('#fulcrum-controller.js', () => {
let sandbox
let mockUseCases
let mockAdapters
let uut
const createFulcrumUseCaseStubs = () => ({
getBalance: sandbox.stub().resolves({ balance: 1000 }),
getBalances: sandbox.stub().resolves({ balances: [] }),
getUtxos: sandbox.stub().resolves({ utxos: [] }),
getUtxosBulk: sandbox.stub().resolves({ utxos: [] }),
getTransactionDetails: sandbox.stub().resolves({ txid: 'abc' }),
getTransactionDetailsBulk: sandbox.stub().resolves({ transactions: [] }),
broadcastTransaction: sandbox.stub().resolves({ txid: 'abc' }),
getBlockHeaders: sandbox.stub().resolves({ headers: [] }),
getBlockHeadersBulk: sandbox.stub().resolves({ headers: [] }),
getTransactions: sandbox.stub().resolves({ transactions: [] }),
getTransactionsBulk: sandbox.stub().resolves({ transactions: [] }),
getMempool: sandbox.stub().resolves({ mempool: [] }),
getMempoolBulk: sandbox.stub().resolves({ mempool: [] })
})
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {
fullNode: {
validateArraySize: sandbox.stub().returns(true)
}
}
mockUseCases = {
fulcrum: createFulcrumUseCaseStubs()
}
uut = new FulcrumRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new FulcrumRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require fulcrum use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new FulcrumRESTController({ adapters: mockAdapters, useCases: {} })
}, /Fulcrum use cases required/)
})
})
describe('#root()', () => {
it('should return service status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'fulcrum' })
})
})
describe('#getBalance()', () => {
it('should return balance on success', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getBalance(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { balance: 1000 })
assert.isTrue(mockUseCases.fulcrum.getBalance.calledOnce)
})
it('should return error if address is array', async () => {
const req = createMockRequest({
params: { address: [] }
})
const res = createMockResponse()
await uut.getBalance(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should handle errors via handleError', async () => {
const error = new Error('failure')
error.status = 503
mockUseCases.fulcrum.getBalance.rejects(error)
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getBalance(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
describe('#balanceBulk()', () => {
it('should return error if addresses is not array', async () => {
const req = createMockRequest({
body: { addresses: 'not-an-array' }
})
const res = createMockResponse()
await uut.balanceBulk(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should validate array size and call use case', async () => {
const req = createMockRequest({
body: { addresses: [VALID_MAINNET_ADDRESS] }
})
const res = createMockResponse()
await uut.balanceBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockAdapters.fullNode.validateArraySize.calledOnce)
assert.isTrue(mockUseCases.fulcrum.getBalances.calledOnce)
})
it('should return error if array size invalid', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({
body: { addresses: [VALID_MAINNET_ADDRESS] }
})
const res = createMockResponse()
await uut.balanceBulk(req, res)
assert.equal(res.statusValue, 400)
assert.equal(res.jsonData.error, 'Array too large.')
})
})
describe('#getUtxos()', () => {
it('should return utxos on success', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getUtxos(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { utxos: [] })
assert.isTrue(mockUseCases.fulcrum.getUtxos.calledOnce)
})
})
describe('#utxosBulk()', () => {
it('should validate array and call use case', async () => {
const req = createMockRequest({
body: { addresses: [VALID_MAINNET_ADDRESS] }
})
const res = createMockResponse()
await uut.utxosBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getUtxosBulk.calledOnce)
})
})
describe('#getTransactionDetails()', () => {
it('should return transaction details on success', async () => {
const txid = 'a'.repeat(64)
const req = createMockRequest({
params: { txid }
})
const res = createMockResponse()
await uut.getTransactionDetails(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { txid: 'abc' })
assert.isTrue(mockUseCases.fulcrum.getTransactionDetails.calledOnce)
})
it('should return error if txid is not string', async () => {
const req = createMockRequest({
params: { txid: 123 }
})
const res = createMockResponse()
await uut.getTransactionDetails(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
})
describe('#transactionDetailsBulk()', () => {
it('should validate array and call use case', async () => {
const req = createMockRequest({
body: { txids: ['a'.repeat(64)], verbose: true }
})
const res = createMockResponse()
await uut.transactionDetailsBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getTransactionDetailsBulk.calledOnce)
})
it('should default verbose to true', async () => {
const req = createMockRequest({
body: { txids: ['a'.repeat(64)] }
})
const res = createMockResponse()
await uut.transactionDetailsBulk(req, res)
assert.isTrue(
mockUseCases.fulcrum.getTransactionDetailsBulk.calledWithMatch({
txids: ['a'.repeat(64)],
verbose: true
})
)
})
})
describe('#broadcastTransaction()', () => {
it('should broadcast transaction on success', async () => {
const req = createMockRequest({
body: { txHex: '010203' }
})
const res = createMockResponse()
await uut.broadcastTransaction(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { txid: 'abc' })
assert.isTrue(mockUseCases.fulcrum.broadcastTransaction.calledOnce)
})
it('should return error if txHex is not string', async () => {
const req = createMockRequest({
body: { txHex: 123 }
})
const res = createMockResponse()
await uut.broadcastTransaction(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
})
describe('#getBlockHeaders()', () => {
it('should return block headers on success', async () => {
const req = createMockRequest({
params: { height: '100' },
query: { count: '2' }
})
const res = createMockResponse()
await uut.getBlockHeaders(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(
mockUseCases.fulcrum.getBlockHeaders.calledWithMatch({
height: 100,
count: 2
})
)
})
it('should default count to 1', async () => {
const req = createMockRequest({
params: { height: '100' }
})
const res = createMockResponse()
await uut.getBlockHeaders(req, res)
assert.isTrue(
mockUseCases.fulcrum.getBlockHeaders.calledWithMatch({
height: 100,
count: 1
})
)
})
it('should return error if height is invalid', async () => {
const req = createMockRequest({
params: { height: 'invalid' }
})
const res = createMockResponse()
await uut.getBlockHeaders(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
})
describe('#blockHeadersBulk()', () => {
it('should validate heights array and call use case', async () => {
const req = createMockRequest({
body: { heights: [{ height: 100, count: 2 }] }
})
const res = createMockResponse()
await uut.blockHeadersBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getBlockHeadersBulk.calledOnce)
})
it('should return error if heights is not array', async () => {
const req = createMockRequest({
body: { heights: 'not-an-array' }
})
const res = createMockResponse()
await uut.blockHeadersBulk(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should validate height objects', async () => {
const req = createMockRequest({
body: { heights: [{ height: 'invalid', count: 2 }] }
})
const res = createMockResponse()
await uut.blockHeadersBulk(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
})
describe('#getTransactions()', () => {
it('should return transactions on success', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getTransactions(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getTransactions.calledOnce)
})
it('should handle allTxs from params', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS, allTxs: 'true' }
})
const res = createMockResponse()
await uut.getTransactions(req, res)
assert.isTrue(
mockUseCases.fulcrum.getTransactions.calledWithMatch({
address: VALID_MAINNET_ADDRESS,
allTxs: true
})
)
})
it('should handle allTxs from query', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS },
query: { allTxs: 'true' }
})
const res = createMockResponse()
await uut.getTransactions(req, res)
assert.isTrue(
mockUseCases.fulcrum.getTransactions.calledWithMatch({
allTxs: true
})
)
})
})
describe('#transactionsBulk()', () => {
it('should validate addresses and call use case', async () => {
const req = createMockRequest({
body: { addresses: [VALID_MAINNET_ADDRESS], allTxs: true }
})
const res = createMockResponse()
await uut.transactionsBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getTransactionsBulk.calledOnce)
})
})
describe('#getMempool()', () => {
it('should return mempool on success', async () => {
const req = createMockRequest({
params: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getMempool(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { mempool: [] })
assert.isTrue(mockUseCases.fulcrum.getMempool.calledOnce)
})
})
describe('#mempoolBulk()', () => {
it('should validate addresses and call use case', async () => {
const req = createMockRequest({
body: { addresses: [VALID_MAINNET_ADDRESS] }
})
const res = createMockResponse()
await uut.mempoolBulk(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.fulcrum.getMempoolBulk.calledOnce)
})
})
describe('#handleError()', () => {
it('should handle errors with status', async () => {
const error = new Error('test error')
error.status = 400
const res = createMockResponse()
uut.handleError(error, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'test error' })
})
it('should default status to 500', async () => {
const error = new Error('test error')
const res = createMockResponse()
uut.handleError(error, res)
assert.equal(res.statusValue, 500)
assert.deepEqual(res.jsonData, { error: 'test error' })
})
})
})
@@ -0,0 +1,139 @@
/*
Unit tests for MiningRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import MiningRESTController from '../../../src/controllers/rest-api/full-node/mining/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#mining-controller.js', () => {
let sandbox
let mockAdapters
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {}
mockUseCases = {
mining: {
getMiningInfo: sandbox.stub().resolves({ blocks: 100, difficulty: 1.5 }),
getNetworkHashPS: sandbox.stub().resolves(1234567890)
}
}
uut = new MiningRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new MiningRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require mining use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new MiningRESTController({ adapters: mockAdapters, useCases: {} })
}, /Mining use cases required/)
})
})
describe('#root()', () => {
it('should return mining status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'mining' })
})
})
describe('#getMiningInfo()', () => {
it('should return mining info on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getMiningInfo(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { blocks: 100, difficulty: 1.5 })
assert.isTrue(mockUseCases.mining.getMiningInfo.calledOnce)
})
it('should handle errors via handleError', async () => {
const error = new Error('failure')
error.status = 503
mockUseCases.mining.getMiningInfo.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getMiningInfo(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
describe('#getNetworkHashPS()', () => {
it('should return network hash PS with default params', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getNetworkHashPS(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.jsonData, 1234567890)
assert.isTrue(mockUseCases.mining.getNetworkHashPS.calledOnce)
assert.deepEqual(mockUseCases.mining.getNetworkHashPS.firstCall.args[0], {
nblocks: 120,
height: -1
})
})
it('should parse query params for nblocks and height', async () => {
const req = createMockRequest({
query: {
nblocks: '240',
height: '1000'
}
})
const res = createMockResponse()
await uut.getNetworkHashPS(req, res)
assert.equal(res.statusValue, 200)
assert.isTrue(mockUseCases.mining.getNetworkHashPS.calledOnce)
assert.deepEqual(mockUseCases.mining.getNetworkHashPS.firstCall.args[0], {
nblocks: 240,
height: 1000
})
})
it('should handle errors via handleError', async () => {
const error = new Error('RPC error')
error.status = 500
mockUseCases.mining.getNetworkHashPS.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getNetworkHashPS(req, res)
assert.equal(res.statusValue, 500)
assert.deepEqual(res.jsonData, { error: 'RPC error' })
})
})
})
@@ -0,0 +1,153 @@
/*
Unit tests for PriceRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import PriceRESTController from '../../../src/controllers/rest-api/price/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#price-controller.js', () => {
let sandbox
let mockAdapters
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {}
mockUseCases = {
price: {
getBCHUSD: sandbox.stub().resolves(250.5),
getPsffppWritePrice: sandbox.stub().resolves(0.08335233),
getPsfLiquidityPrice: sandbox.stub().resolves({
usdPerBCH: 483.1,
bchBalance: 25.65337297,
tokenBalance: 39590.96686314,
usdPerToken: 0.50532753
})
}
}
uut = new PriceRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new PriceRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require price use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new PriceRESTController({ adapters: mockAdapters, useCases: {} })
}, /Price use cases required/)
})
})
describe('#root()', () => {
it('should return price status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'price' })
})
})
describe('#getBCHUSD()', () => {
it('should return BCH USD price on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getBCHUSD(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { usd: 250.5 })
assert.isTrue(mockUseCases.price.getBCHUSD.calledOnce)
})
it('should handle errors via handleError', async () => {
const error = new Error('API failure')
error.status = 503
mockUseCases.price.getBCHUSD.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getBCHUSD(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'API failure' })
})
})
describe('#getPsffppWritePrice()', () => {
it('should return PSFFPP write price on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getPsffppWritePrice(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { writePrice: 0.08335233 })
assert.isTrue(mockUseCases.price.getPsffppWritePrice.calledOnce)
})
it('should handle errors via handleError', async () => {
const error = new Error('PSFFPP failure')
error.status = 500
mockUseCases.price.getPsffppWritePrice.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getPsffppWritePrice(req, res)
assert.equal(res.statusValue, 500)
assert.deepEqual(res.jsonData, { error: 'PSFFPP failure' })
})
})
describe('#getPsfLiquidityPrice()', () => {
it('should return PSF liquidity price payload on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getPsfLiquidityPrice(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, {
usdPerBCH: 483.1,
bchBalance: 25.65337297,
tokenBalance: 39590.96686314,
usdPerToken: 0.50532753
})
assert.isTrue(mockUseCases.price.getPsfLiquidityPrice.calledOnce)
})
it('should handle errors via handleError', async () => {
const error = new Error('proxy off')
error.status = 503
mockUseCases.price.getPsfLiquidityPrice.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getPsfLiquidityPrice(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'proxy off' })
})
})
})
@@ -0,0 +1,388 @@
/*
Unit tests for RawTransactionsRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import RawTransactionsRESTController from '../../../src/controllers/rest-api/full-node/rawtransactions/controller.js'
import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js'
describe('#rawtransactions-controller.js', () => {
let sandbox
let mockAdapters
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {
fullNode: {
validateArraySize: sandbox.stub().returns(true)
}
}
mockUseCases = {
rawtransactions: {
decodeRawTransaction: sandbox.stub().resolves({ txid: 'abc123' }),
decodeRawTransactions: sandbox.stub().resolves([{ txid: 'abc123' }]),
decodeScript: sandbox.stub().resolves({ asm: 'OP_DUP' }),
decodeScripts: sandbox.stub().resolves([{ asm: 'OP_DUP' }]),
getRawTransaction: sandbox.stub().resolves({ txid: 'abc123' }),
getRawTransactionWithHeight: sandbox.stub().resolves({ txid: 'abc123', height: 100 }),
getRawTransactions: sandbox.stub().resolves([{ txid: 'abc123' }]),
sendRawTransaction: sandbox.stub().resolves('txid123'),
sendRawTransactions: sandbox.stub().resolves(['txid1', 'txid2'])
}
}
uut = new RawTransactionsRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new RawTransactionsRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require rawtransactions use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new RawTransactionsRESTController({ adapters: mockAdapters, useCases: {} })
}, /RawTransactions use cases required/)
})
})
describe('#root()', () => {
it('should return rawtransactions status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'rawtransactions' })
})
})
describe('#decodeRawTransactionSingle()', () => {
it('should return decoded transaction on success', async () => {
const req = createMockRequest({ params: { hex: '01000000' } })
const res = createMockResponse()
await uut.decodeRawTransactionSingle(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { txid: 'abc123' })
assert.isTrue(mockUseCases.rawtransactions.decodeRawTransaction.calledOnce)
assert.deepEqual(mockUseCases.rawtransactions.decodeRawTransaction.firstCall.args[0], { hex: '01000000' })
})
it('should return 400 if hex is empty', async () => {
const req = createMockRequest({ params: { hex: '' } })
const res = createMockResponse()
await uut.decodeRawTransactionSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'hex can not be empty' })
})
it('should handle errors via handleError', async () => {
const error = new Error('RPC error')
error.status = 500
mockUseCases.rawtransactions.decodeRawTransaction.rejects(error)
const req = createMockRequest({ params: { hex: '01000000' } })
const res = createMockResponse()
await uut.decodeRawTransactionSingle(req, res)
assert.equal(res.statusValue, 500)
assert.deepEqual(res.jsonData, { error: 'RPC error' })
})
})
describe('#decodeRawTransactionBulk()', () => {
it('should return decoded transactions on success', async () => {
const req = createMockRequest({ body: { hexes: ['hex1', 'hex2'] } })
const res = createMockResponse()
await uut.decodeRawTransactionBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, [{ txid: 'abc123' }])
assert.isTrue(mockUseCases.rawtransactions.decodeRawTransactions.calledOnce)
})
it('should return 400 if hexes is not an array', async () => {
const req = createMockRequest({ body: { hexes: 'not-array' } })
const res = createMockResponse()
await uut.decodeRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'hexes must be an array' })
})
it('should return 400 if array is too large', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({ body: { hexes: new Array(25).fill('hex') } })
const res = createMockResponse()
await uut.decodeRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Array too large.' })
})
it('should return 400 if empty hex encountered', async () => {
const req = createMockRequest({ body: { hexes: ['hex1', '', 'hex2'] } })
const res = createMockResponse()
await uut.decodeRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Encountered empty hex' })
})
})
describe('#decodeScriptSingle()', () => {
it('should return decoded script on success', async () => {
const req = createMockRequest({ params: { hex: '76a914' } })
const res = createMockResponse()
await uut.decodeScriptSingle(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { asm: 'OP_DUP' })
assert.isTrue(mockUseCases.rawtransactions.decodeScript.calledOnce)
})
it('should return 400 if hex is empty', async () => {
const req = createMockRequest({ params: { hex: '' } })
const res = createMockResponse()
await uut.decodeScriptSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'hex can not be empty' })
})
})
describe('#decodeScriptBulk()', () => {
it('should return decoded scripts on success', async () => {
const req = createMockRequest({ body: { hexes: ['script1', 'script2'] } })
const res = createMockResponse()
await uut.decodeScriptBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, [{ asm: 'OP_DUP' }])
})
it('should return 400 if array is too large', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({ body: { hexes: new Array(25).fill('script') } })
const res = createMockResponse()
await uut.decodeScriptBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Array too large.' })
})
})
describe('#getRawTransactionSingle()', () => {
it('should return raw transaction on success', async () => {
const req = createMockRequest({ params: { txid: 'a'.repeat(64) }, query: {} })
const res = createMockResponse()
await uut.getRawTransactionSingle(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { txid: 'abc123', height: 100 })
assert.isTrue(mockUseCases.rawtransactions.getRawTransactionWithHeight.calledOnce)
})
it('should pass verbose=true when query param is set', async () => {
const req = createMockRequest({ params: { txid: 'a'.repeat(64) }, query: { verbose: 'true' } })
const res = createMockResponse()
await uut.getRawTransactionSingle(req, res)
assert.isTrue(mockUseCases.rawtransactions.getRawTransactionWithHeight.calledOnce)
assert.deepEqual(mockUseCases.rawtransactions.getRawTransactionWithHeight.firstCall.args[0], {
txid: 'a'.repeat(64),
verbose: true
})
})
it('should return 400 if txid is empty', async () => {
const req = createMockRequest({ params: { txid: '' } })
const res = createMockResponse()
await uut.getRawTransactionSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'txid can not be empty' })
})
it('should return 400 if txid length is not 64', async () => {
const req = createMockRequest({ params: { txid: 'short' } })
const res = createMockResponse()
await uut.getRawTransactionSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'parameter 1 must be of length 64 (not 5)' })
})
})
describe('#getRawTransactionBulk()', () => {
it('should return raw transactions on success', async () => {
const req = createMockRequest({
body: {
txids: ['a'.repeat(64), 'b'.repeat(64)],
verbose: true
}
})
const res = createMockResponse()
await uut.getRawTransactionBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, [{ txid: 'abc123' }])
assert.isTrue(mockUseCases.rawtransactions.getRawTransactions.calledOnce)
assert.deepEqual(mockUseCases.rawtransactions.getRawTransactions.firstCall.args[0], {
txids: ['a'.repeat(64), 'b'.repeat(64)],
verbose: true
})
})
it('should return 400 if txids is not an array', async () => {
const req = createMockRequest({ body: { txids: 'not-array' } })
const res = createMockResponse()
await uut.getRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'txids must be an array' })
})
it('should return 400 if array is too large', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({ body: { txids: new Array(25).fill('a'.repeat(64)) } })
const res = createMockResponse()
await uut.getRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Array too large.' })
})
it('should return 400 if empty txid encountered', async () => {
const req = createMockRequest({ body: { txids: ['a'.repeat(64), ''] } })
const res = createMockResponse()
await uut.getRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Encountered empty TXID' })
})
it('should return 400 if txid length is not 64', async () => {
const req = createMockRequest({ body: { txids: ['short'] } })
const res = createMockResponse()
await uut.getRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'parameter 1 must be of length 64 (not 5)' })
})
})
describe('#sendRawTransactionSingle()', () => {
it('should return txid on success', async () => {
const req = createMockRequest({ params: { hex: '01000000' } })
const res = createMockResponse()
await uut.sendRawTransactionSingle(req, res)
assert.equal(res.statusValue, 200)
assert.equal(res.jsonData, 'txid123')
assert.isTrue(mockUseCases.rawtransactions.sendRawTransaction.calledOnce)
})
it('should return 400 if hex is empty', async () => {
const req = createMockRequest({ params: { hex: '' } })
const res = createMockResponse()
await uut.sendRawTransactionSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Encountered empty hex' })
})
it('should return 400 if hex is not a string', async () => {
const req = createMockRequest({ params: { hex: 123 } })
const res = createMockResponse()
await uut.sendRawTransactionSingle(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'hex must be a string' })
})
})
describe('#sendRawTransactionBulk()', () => {
it('should return txids on success', async () => {
const req = createMockRequest({ body: { hexes: ['hex1', 'hex2'] } })
const res = createMockResponse()
await uut.sendRawTransactionBulk(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, ['txid1', 'txid2'])
assert.isTrue(mockUseCases.rawtransactions.sendRawTransactions.calledOnce)
})
it('should return 400 if hexes is not an array', async () => {
const req = createMockRequest({ body: { hexes: 'not-array' } })
const res = createMockResponse()
await uut.sendRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'hex must be an array' })
})
it('should return 400 if array is too large', async () => {
mockAdapters.fullNode.validateArraySize.returns(false)
const req = createMockRequest({ body: { hexes: new Array(25).fill('hex') } })
const res = createMockResponse()
await uut.sendRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Array too large.' })
})
it('should return 400 if empty hex encountered', async () => {
const req = createMockRequest({ body: { hexes: ['hex1', '', 'hex2'] } })
const res = createMockResponse()
await uut.sendRawTransactionBulk(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Encountered empty hex' })
})
})
})
@@ -1,344 +0,0 @@
/*
Unit tests for ReqRESTControllerLib.
*/
// npm libraries
import { assert } from 'chai'
import sinon from 'sinon'
// Mocking data libraries
import { mockEventsArray } from '../mocks/nostr-relay-mocks.js'
import {
createMockRequestWithParams,
createMockResponse
} from '../mocks/controller-mocks.js'
// Unit under test
import ReqRESTControllerLib from '../../../src/controllers/rest-api/req/controller.js'
describe('#req-controller.js', () => {
let sandbox
let mockUseCases
let uut
beforeEach(() => {
sandbox = sinon.createSandbox()
// Create mock use cases
mockUseCases = {
queryEvents: {
execute: sandbox.stub()
},
manageSubscription: {
createSubscription: sandbox.stub(),
closeSubscription: sandbox.stub()
}
}
uut = new ReqRESTControllerLib({
adapters: {},
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#queryEvents()', () => {
it('should successfully query events with filters as JSON string', async () => {
const filters = [{ kinds: [1], limit: 10 }]
const filtersJson = JSON.stringify(filters)
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.query = { filters: filtersJson }
const res = createMockResponse()
mockUseCases.queryEvents.execute.resolves(mockEventsArray)
await uut.queryEvents(req, res)
// Assert use case was called with parsed filters
assert.isTrue(mockUseCases.queryEvents.execute.calledOnce)
const executeArgs = mockUseCases.queryEvents.execute.getCall(0).args
assert.deepEqual(executeArgs[0], filters)
assert.equal(executeArgs[1], 'test-sub-123')
// Assert response
assert.equal(res.statusValue, 200)
assert.isArray(res.jsonData)
assert.equal(res.jsonData.length, mockEventsArray.length)
})
it('should successfully query events with individual query params', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.query = {
kinds: JSON.stringify([1]),
authors: JSON.stringify(['abc123']),
limit: '10'
}
const res = createMockResponse()
mockUseCases.queryEvents.execute.resolves(mockEventsArray)
await uut.queryEvents(req, res)
// Assert use case was called
assert.isTrue(mockUseCases.queryEvents.execute.calledOnce)
const executeArgs = mockUseCases.queryEvents.execute.getCall(0).args
assert.isArray(executeArgs[0])
assert.equal(executeArgs[0][0].kinds[0], 1)
assert.equal(executeArgs[0][0].authors[0], 'abc123')
assert.equal(executeArgs[0][0].limit, 10)
})
it('should handle empty filters', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.query = {}
const res = createMockResponse()
mockUseCases.queryEvents.execute.resolves([])
await uut.queryEvents(req, res)
// Assert use case was called with empty filters array
assert.isTrue(mockUseCases.queryEvents.execute.calledOnce)
const executeArgs = mockUseCases.queryEvents.execute.getCall(0).args
assert.deepEqual(executeArgs[0], [{}])
})
it('should return 400 when subscription ID is missing', async () => {
const req = createMockRequestWithParams({})
const res = createMockResponse()
await uut.queryEvents(req, res)
// Assert use case was not called
assert.isFalse(mockUseCases.queryEvents.execute.called)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Subscription ID is required')
})
it('should return 400 when filters JSON is invalid', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.query = { filters: 'invalid-json{' }
const res = createMockResponse()
await uut.queryEvents(req, res)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Invalid filters JSON')
})
it('should handle use case errors', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.query = { filters: JSON.stringify([{ kinds: [1] }]) }
const res = createMockResponse()
mockUseCases.queryEvents.execute.rejects(new Error('Query failed'))
await uut.queryEvents(req, res)
// Assert error response
assert.equal(res.statusValue, 500)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Query failed')
})
})
describe('#createSubscription()', () => {
it('should successfully create SSE subscription', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.body = { kinds: [1] }
const res = createMockResponse()
mockUseCases.manageSubscription.createSubscription.resolves()
await uut.createSubscription(req, res)
// Assert use case was called
assert.isTrue(mockUseCases.manageSubscription.createSubscription.calledOnce)
const createArgs = mockUseCases.manageSubscription.createSubscription.getCall(0).args
assert.equal(createArgs[0], 'test-sub-123')
assert.isArray(createArgs[1])
assert.equal(createArgs[1][0].kinds[0], 1)
assert.isFunction(createArgs[2]) // onEvent
assert.isFunction(createArgs[3]) // onEose
assert.isFunction(createArgs[4]) // onClosed
// Assert SSE headers
assert.equal(res.headers['Content-Type'], 'text/event-stream')
assert.equal(res.headers['Cache-Control'], 'no-cache')
assert.equal(res.headers.Connection, 'keep-alive')
// Assert initial connection message was written
assert.isTrue(res.writeData.length > 0)
})
it('should return 400 when subscription ID is missing', async () => {
const req = createMockRequestWithParams({})
req.body = { kinds: [1] }
const res = createMockResponse()
await uut.createSubscription(req, res)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Subscription ID is required')
})
it('should return 400 when filters are missing', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.body = {}
const res = createMockResponse()
await uut.createSubscription(req, res)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Filters are required')
})
it('should handle filters as array', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.body = [{ kinds: [1] }, { kinds: [3] }]
const res = createMockResponse()
mockUseCases.manageSubscription.createSubscription.resolves()
await uut.createSubscription(req, res)
// Assert filters array was passed correctly
const createArgs = mockUseCases.manageSubscription.createSubscription.getCall(0).args
assert.isArray(createArgs[1])
assert.equal(createArgs[1].length, 2)
})
it('should handle client disconnect', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.body = { kinds: [1] }
req.on = sinon.stub()
const res = createMockResponse()
mockUseCases.manageSubscription.createSubscription.resolves()
mockUseCases.manageSubscription.closeSubscription.resolves()
await uut.createSubscription(req, res)
// Assert close handler was set up
assert.isTrue(req.on.calledWith('close'))
// Simulate client disconnect
const closeCallback = req.on.getCall(0).args[1]
await closeCallback()
// Assert closeSubscription was called
assert.isTrue(mockUseCases.manageSubscription.closeSubscription.calledOnce)
assert.equal(mockUseCases.manageSubscription.closeSubscription.getCall(0).args[0], 'test-sub-123')
})
})
describe('#closeSubscription()', () => {
it('should successfully close a subscription', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
const res = createMockResponse()
mockUseCases.manageSubscription.closeSubscription.resolves()
await uut.closeSubscription(req, res)
// Assert use case was called
assert.isTrue(mockUseCases.manageSubscription.closeSubscription.calledOnce)
assert.equal(mockUseCases.manageSubscription.closeSubscription.getCall(0).args[0], 'test-sub-123')
// Assert response
assert.equal(res.statusValue, 200)
assert.property(res.jsonData, 'message')
assert.include(res.jsonData.message, 'closed successfully')
})
it('should return 400 when subscription ID is missing', async () => {
const req = createMockRequestWithParams({})
const res = createMockResponse()
await uut.closeSubscription(req, res)
// Assert error response
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Subscription ID is required')
})
it('should handle use case errors', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
const res = createMockResponse()
mockUseCases.manageSubscription.closeSubscription.rejects(new Error('Relay connection error'))
await uut.closeSubscription(req, res)
// Assert error response
assert.equal(res.statusValue, 500)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'Relay connection error')
})
it('should handle idempotent close (subscription already closed)', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
const res = createMockResponse()
// closeSubscription resolves successfully even if subscription doesn't exist
mockUseCases.manageSubscription.closeSubscription.resolves()
await uut.closeSubscription(req, res)
// Assert success response even for already-closed subscription
assert.equal(res.statusValue, 200)
assert.property(res.jsonData, 'message')
assert.include(res.jsonData.message, 'closed successfully')
})
})
describe('#createSubscriptionPut()', () => {
it('should call createSubscription', async () => {
const req = createMockRequestWithParams({ subId: 'test-sub-123' })
req.body = { kinds: [1] }
const res = createMockResponse()
mockUseCases.manageSubscription.createSubscription.resolves()
await uut.createSubscriptionPut(req, res)
// Assert createSubscription was called
assert.isTrue(mockUseCases.manageSubscription.createSubscription.calledOnce)
})
})
describe('#constructor()', () => {
it('should require adapters instance', () => {
try {
// eslint-disable-next-line no-new
new ReqRESTControllerLib({ useCases: mockUseCases })
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'Adapters library required')
}
})
it('should require useCases instance', () => {
try {
// eslint-disable-next-line no-new
new ReqRESTControllerLib({ adapters: {} })
assert.equal(true, false, 'unexpected result')
} catch (err) {
assert.include(err.message, 'Use Cases library required')
}
})
})
})
@@ -0,0 +1,170 @@
/*
Unit tests for RESTControllers index.
*/
import { assert } from 'chai'
import sinon from 'sinon'
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'
import FulcrumRouter from '../../../src/controllers/rest-api/fulcrum/router.js'
import SlpRouter from '../../../src/controllers/rest-api/slp/router.js'
describe('#controllers/rest-api/index.js', () => {
let sandbox
let mockAdapters
let mockUseCases
const createBlockchainUseCaseStubs = () => ({
getBestBlockHash: () => {},
getBlockchainInfo: () => {},
getBlockCount: () => {},
getBlockHeader: () => {},
getBlockHeaders: () => {},
getChainTips: () => {},
getDifficulty: () => {},
getMempoolEntry: () => {},
getMempoolEntries: () => {},
getMempoolAncestors: () => {},
getMempoolInfo: () => {},
getRawMempool: () => {},
getTxOut: () => {},
getTxOutProof: () => {},
getTxOutProofs: () => {},
verifyTxOutProof: () => {},
verifyTxOutProofs: () => {},
getBlock: () => {},
getBlockHash: () => {}
})
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {
fullNode: {
validateArraySize: sandbox.stub().returns(true)
}
}
mockUseCases = {
blockchain: createBlockchainUseCaseStubs(),
control: {
getNetworkInfo: () => {}
},
dsproof: {
getDSProof: () => {}
},
fulcrum: {
getBalance: () => {},
getBalances: () => {},
getUtxos: () => {},
getUtxosBulk: () => {},
getTransactionDetails: () => {},
getTransactionDetailsBulk: () => {},
broadcastTransaction: () => {},
getBlockHeaders: () => {},
getBlockHeadersBulk: () => {},
getTransactions: () => {},
getTransactionsBulk: () => {},
getMempool: () => {},
getMempoolBulk: () => {}
},
mining: {
getMiningInfo: () => {},
getNetworkHashPS: () => {}
},
price: {
getBCHUSD: () => {},
getPsffppWritePrice: () => {}
},
rawtransactions: {
decodeRawTransaction: () => {},
decodeRawTransactions: () => {},
decodeScript: () => {},
decodeScripts: () => {},
getRawTransaction: () => {},
getRawTransactionWithHeight: () => {},
getRawTransactions: () => {},
sendRawTransaction: () => {},
sendRawTransactions: () => {}
},
slp: {
getStatus: () => {},
getAddress: () => {},
getTxid: () => {},
getTokenStats: () => {},
getTokenData: () => {},
getMutableCid: () => {},
decodeOpReturn: () => {},
getCIDData: () => {}
},
encryption: {
getPublicKey: () => {}
}
}
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters instance', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new RESTControllers({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require useCases instance', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new RESTControllers({ adapters: mockAdapters })
}, /Use Cases library required/)
})
})
describe('#attachRESTControllers()', () => {
it('should instantiate routers and attach to app', () => {
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')
const rawtransactionsAttachStub = sandbox.stub(RawTransactionsRouter.prototype, 'attach')
const slpAttachStub = sandbox.stub(SlpRouter.prototype, 'attach')
const restControllers = new RESTControllers({
adapters: mockAdapters,
useCases: mockUseCases
})
const app = {}
restControllers.attachRESTControllers(app)
assert.isTrue(blockchainAttachStub.calledOnce)
assert.equal(blockchainAttachStub.getCall(0).args[0], app)
assert.isTrue(controlAttachStub.calledOnce)
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)
assert.equal(miningAttachStub.getCall(0).args[0], app)
assert.isTrue(priceAttachStub.calledOnce)
assert.equal(priceAttachStub.getCall(0).args[0], app)
assert.isTrue(rawtransactionsAttachStub.calledOnce)
assert.equal(rawtransactionsAttachStub.getCall(0).args[0], app)
assert.isTrue(slpAttachStub.calledOnce)
assert.equal(slpAttachStub.getCall(0).args[0], app)
})
})
})
@@ -0,0 +1,312 @@
/*
Unit tests for SlpRESTController.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import SlpRESTController from '../../../src/controllers/rest-api/slp/controller.js'
import {
createMockRequest,
createMockResponse
} from '../mocks/controller-mocks.js'
// Valid mainnet cash address for testing
const VALID_MAINNET_ADDRESS = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
describe('#slp-controller.js', () => {
let sandbox
let mockUseCases
let mockAdapters
let uut
const createSlpUseCaseStubs = () => ({
getStatus: sandbox.stub().resolves({ status: 'ok' }),
getAddress: sandbox.stub().resolves({ balance: 1000 }),
getTxid: sandbox.stub().resolves({ txid: 'abc' }),
getTokenStats: sandbox.stub().resolves({ tokenData: {} }),
getTokenData: sandbox.stub().resolves({ genesisData: {}, immutableData: '', mutableData: '' })
})
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {}
mockUseCases = {
slp: createSlpUseCaseStubs()
}
uut = new SlpRESTController({
adapters: mockAdapters,
useCases: mockUseCases
})
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new SlpRESTController({ useCases: mockUseCases })
}, /Adapters library required/)
})
it('should require slp use cases', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new SlpRESTController({ adapters: mockAdapters, useCases: {} })
}, /SLP use cases required/)
})
})
describe('#root()', () => {
it('should return service status', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.root(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'psf-slp-indexer' })
})
})
describe('#getStatus()', () => {
it('should return status on success', async () => {
const req = createMockRequest()
const res = createMockResponse()
await uut.getStatus(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { status: 'ok' })
assert.isTrue(mockUseCases.slp.getStatus.calledOnce)
})
it('should handle errors via handleError', async () => {
const error = new Error('failure')
error.status = 503
mockUseCases.slp.getStatus.rejects(error)
const req = createMockRequest()
const res = createMockResponse()
await uut.getStatus(req, res)
assert.equal(res.statusValue, 503)
assert.deepEqual(res.jsonData, { error: 'failure' })
})
})
describe('#getAddress()', () => {
it('should return address balance on success', async () => {
const req = createMockRequest({
body: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getAddress(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { balance: 1000 })
assert.isTrue(mockUseCases.slp.getAddress.calledOnce)
})
it('should return error if address is empty', async () => {
const req = createMockRequest({
body: { address: '' }
})
const res = createMockResponse()
await uut.getAddress(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'can not be empty')
})
it('should return error if address is missing', async () => {
const req = createMockRequest({
body: {}
})
const res = createMockResponse()
await uut.getAddress(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should handle errors via handleError', async () => {
const error = new Error('Invalid address')
error.status = 400
mockUseCases.slp.getAddress.rejects(error)
const req = createMockRequest({
body: { address: VALID_MAINNET_ADDRESS }
})
const res = createMockResponse()
await uut.getAddress(req, res)
assert.equal(res.statusValue, 400)
assert.deepEqual(res.jsonData, { error: 'Invalid address' })
})
})
describe('#getTxid()', () => {
it('should return transaction data on success', async () => {
const req = createMockRequest({
body: { txid: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTxid(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { txid: 'abc' })
assert.isTrue(mockUseCases.slp.getTxid.calledOnce)
})
it('should return error if txid is empty', async () => {
const req = createMockRequest({
body: { txid: '' }
})
const res = createMockResponse()
await uut.getTxid(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'can not be empty')
})
it('should return error if txid is not 64 characters', async () => {
const req = createMockRequest({
body: { txid: 'abc' }
})
const res = createMockResponse()
await uut.getTxid(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
assert.include(res.jsonData.error, 'not a txid')
})
it('should handle errors via handleError', async () => {
const error = new Error('Transaction not found')
error.status = 404
mockUseCases.slp.getTxid.rejects(error)
const req = createMockRequest({
body: { txid: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTxid(req, res)
assert.equal(res.statusValue, 404)
assert.deepEqual(res.jsonData, { error: 'Transaction not found' })
})
})
describe('#getTokenStats()', () => {
it('should return token stats on success', async () => {
const req = createMockRequest({
body: { tokenId: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTokenStats(req, res)
assert.equal(res.statusValue, 200)
assert.deepEqual(res.jsonData, { tokenData: {} })
assert.isTrue(mockUseCases.slp.getTokenStats.calledOnce)
})
it('should pass withTxHistory flag', async () => {
const req = createMockRequest({
body: { tokenId: 'a'.repeat(64), withTxHistory: true }
})
const res = createMockResponse()
await uut.getTokenStats(req, res)
assert.isTrue(mockUseCases.slp.getTokenStats.calledWith({
tokenId: 'a'.repeat(64),
withTxHistory: true
}))
})
it('should return error if tokenId is empty', async () => {
const req = createMockRequest({
body: { tokenId: '' }
})
const res = createMockResponse()
await uut.getTokenStats(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should handle errors via handleError', async () => {
const error = new Error('Token not found')
error.status = 404
mockUseCases.slp.getTokenStats.rejects(error)
const req = createMockRequest({
body: { tokenId: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTokenStats(req, res)
assert.equal(res.statusValue, 404)
assert.deepEqual(res.jsonData, { error: 'Token not found' })
})
})
describe('#getTokenData()', () => {
it('should return token data on success', async () => {
const req = createMockRequest({
body: { tokenId: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTokenData(req, res)
assert.equal(res.statusValue, 200)
assert.property(res.jsonData, 'genesisData')
assert.property(res.jsonData, 'immutableData')
assert.property(res.jsonData, 'mutableData')
assert.isTrue(mockUseCases.slp.getTokenData.calledOnce)
})
it('should return error if tokenId is empty', async () => {
const req = createMockRequest({
body: { tokenId: '' }
})
const res = createMockResponse()
await uut.getTokenData(req, res)
assert.equal(res.statusValue, 400)
assert.property(res.jsonData, 'error')
})
it('should handle errors via handleError', async () => {
const error = new Error('Token data not found')
error.status = 404
mockUseCases.slp.getTokenData.rejects(error)
const req = createMockRequest({
body: { tokenId: 'a'.repeat(64) }
})
const res = createMockResponse()
await uut.getTokenData(req, res)
assert.equal(res.statusValue, 404)
assert.deepEqual(res.jsonData, { error: 'Token data not found' })
})
})
})
-139
View File
@@ -1,139 +0,0 @@
/*
Unit tests for the Event entity.
*/
// npm libraries
import { assert } from 'chai'
// Mocking data libraries
import {
mockKind0Event,
mockKind1Event,
mockKind3Event,
mockKind7Event,
mockInvalidEventMissingId,
mockInvalidEventWrongIdLength,
mockInvalidEventMissingPubkey,
mockInvalidEventWrongPubkeyLength,
mockInvalidEventMissingCreatedAt,
mockInvalidEventWrongCreatedAtType,
mockInvalidEventMissingKind,
mockInvalidEventKindOutOfRange,
mockInvalidEventMissingSig,
mockInvalidEventWrongSigLength,
mockInvalidEventTagsNotArray
} from '../mocks/event-mocks.js'
// Unit under test
import Event from '../../../src/entities/event.js'
describe('#event.js', () => {
describe('#isValid()', () => {
it('should return true for valid kind 0 event', () => {
const event = new Event(mockKind0Event)
assert.isTrue(event.isValid())
})
it('should return true for valid kind 1 event', () => {
const event = new Event(mockKind1Event)
assert.isTrue(event.isValid())
})
it('should return true for valid kind 3 event', () => {
const event = new Event(mockKind3Event)
assert.isTrue(event.isValid())
})
it('should return true for valid kind 7 event', () => {
const event = new Event(mockKind7Event)
assert.isTrue(event.isValid())
})
it('should return false for event missing id', () => {
const event = new Event(mockInvalidEventMissingId)
assert.isFalse(event.isValid())
})
it('should return false for event with wrong id length', () => {
const event = new Event(mockInvalidEventWrongIdLength)
assert.isFalse(event.isValid())
})
it('should return false for event missing pubkey', () => {
const event = new Event(mockInvalidEventMissingPubkey)
assert.isFalse(event.isValid())
})
it('should return false for event with wrong pubkey length', () => {
const event = new Event(mockInvalidEventWrongPubkeyLength)
assert.isFalse(event.isValid())
})
it('should return false for event missing created_at', () => {
const event = new Event(mockInvalidEventMissingCreatedAt)
assert.isFalse(event.isValid())
})
it('should return false for event with wrong created_at type', () => {
const event = new Event(mockInvalidEventWrongCreatedAtType)
assert.isFalse(event.isValid())
})
it('should return false for event missing kind', () => {
const event = new Event(mockInvalidEventMissingKind)
assert.isFalse(event.isValid())
})
it('should return false for event with kind out of range', () => {
const event = new Event(mockInvalidEventKindOutOfRange)
assert.isFalse(event.isValid())
})
it('should return false for event missing sig', () => {
const event = new Event(mockInvalidEventMissingSig)
assert.isFalse(event.isValid())
})
it('should return false for event with wrong sig length', () => {
const event = new Event(mockInvalidEventWrongSigLength)
assert.isFalse(event.isValid())
})
it('should return false for event with tags not an array', () => {
const event = new Event(mockInvalidEventTagsNotArray)
assert.isFalse(event.isValid())
})
})
describe('#toJSON()', () => {
it('should serialize event to JSON correctly', () => {
const event = new Event(mockKind1Event)
const json = event.toJSON()
assert.property(json, 'id')
assert.property(json, 'pubkey')
assert.property(json, 'created_at')
assert.property(json, 'kind')
assert.property(json, 'tags')
assert.property(json, 'content')
assert.property(json, 'sig')
assert.equal(json.id, mockKind1Event.id)
assert.equal(json.pubkey, mockKind1Event.pubkey)
assert.equal(json.created_at, mockKind1Event.created_at)
assert.equal(json.kind, mockKind1Event.kind)
assert.deepEqual(json.tags, mockKind1Event.tags)
assert.equal(json.content, mockKind1Event.content)
assert.equal(json.sig, mockKind1Event.sig)
})
it('should serialize event with tags correctly', () => {
const event = new Event(mockKind3Event)
const json = event.toJSON()
assert.isArray(json.tags)
assert.equal(json.tags.length, 1)
assert.deepEqual(json.tags, mockKind3Event.tags)
})
})
})
-58
View File
@@ -1,58 +0,0 @@
/*
Mock responses from Nostr relay for unit tests.
Contains mock messages that would come from a Nostr relay WebSocket.
*/
import { mockKind1Event, validEventId } from './event-mocks.js'
// Mock OK response (event accepted)
const mockOkAccepted = ['OK', validEventId, true, 'event saved']
// Mock OK response (event rejected)
const mockOkRejected = ['OK', validEventId, false, 'duplicate: event already exists']
// Mock EVENT message (from relay)
const mockEventMessage = ['EVENT', 'subscription-id-123', mockKind1Event]
// Mock EOSE message (end of stored events)
const mockEoseMessage = ['EOSE', 'subscription-id-123']
// Mock CLOSED message
const mockClosedMessage = ['CLOSED', 'subscription-id-123', 'subscription closed']
// Mock NOTICE message
const mockNoticeMessage = ['NOTICE', 'rate limited: slow down']
// Mock successful sendEvent response
const mockSendEventSuccess = {
accepted: true,
message: 'event saved'
}
// Mock failed sendEvent response
const mockSendEventFailure = {
accepted: false,
message: 'duplicate: event already exists'
}
// Mock events array for query tests
const mockEventsArray = [
mockKind1Event,
{
...mockKind1Event,
id: 'b'.repeat(64),
content: 'Another test message'
}
]
export {
mockOkAccepted,
mockOkRejected,
mockEventMessage,
mockEoseMessage,
mockClosedMessage,
mockNoticeMessage,
mockSendEventSuccess,
mockSendEventFailure,
mockEventsArray
}
@@ -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')
}
})
})
})
@@ -0,0 +1,297 @@
/*
Unit tests for FulcrumUseCases.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import BCHJS from '@psf/bch-js'
import FulcrumUseCases from '../../../src/use-cases/fulcrum-use-cases.js'
describe('#fulcrum-use-cases.js', () => {
let sandbox
let mockAdapters
let uut
let sortAllTxsStub
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = {
fulcrum: {
get: sandbox.stub().resolves({}),
post: sandbox.stub().resolves({})
}
}
// Create a mock BCHJS instance with stubbed sortAllTxs method
const mockBchjs = new BCHJS({ restURL: 'http://localhost:5942/v6/' })
if (!mockBchjs.Electrumx) {
mockBchjs.Electrumx = {}
}
// Create a stub that sorts transactions
sortAllTxsStub = sandbox.stub(mockBchjs.Electrumx, 'sortAllTxs')
sortAllTxsStub.callsFake(async (txs, order) => {
const sorted = [...txs].sort((a, b) => {
if (order === 'DESCENDING') {
return (b.height || 0) - (a.height || 0)
}
return (a.height || 0) - (b.height || 0)
})
return sorted
})
// Inject the mocked bchjs instance into the use cases
uut = new FulcrumUseCases({ adapters: mockAdapters, bchjs: mockBchjs })
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new FulcrumUseCases()
}, /Adapters instance required/)
})
it('should require fulcrum adapter', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new FulcrumUseCases({ adapters: {} })
}, /Fulcrum adapter required/)
})
})
describe('#getBalance()', () => {
it('should call fulcrum adapter get method', async () => {
const address = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
mockAdapters.fulcrum.get.resolves({ balance: 1000 })
const result = await uut.getBalance({ address })
assert.isTrue(mockAdapters.fulcrum.get.calledOnceWith(`electrumx/balance/${address}`))
assert.deepEqual(result, { balance: 1000 })
})
})
describe('#getBalances()', () => {
it('should call fulcrum adapter post method', async () => {
const addresses = ['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf']
mockAdapters.fulcrum.post.resolves({ balances: [] })
const result = await uut.getBalances({ addresses })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/balance/', { addresses })
)
assert.deepEqual(result, { balances: [] })
})
})
describe('#getUtxos()', () => {
it('should call fulcrum adapter get method', async () => {
const address = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
mockAdapters.fulcrum.get.resolves({ utxos: [] })
const result = await uut.getUtxos({ address })
assert.isTrue(mockAdapters.fulcrum.get.calledOnceWith(`electrumx/utxos/${address}`))
assert.deepEqual(result, { utxos: [] })
})
})
describe('#getUtxosBulk()', () => {
it('should call fulcrum adapter post method', async () => {
const addresses = ['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf']
mockAdapters.fulcrum.post.resolves({ utxos: [] })
const result = await uut.getUtxosBulk({ addresses })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/utxos/', { addresses })
)
assert.deepEqual(result, { utxos: [] })
})
})
describe('#getTransactionDetails()', () => {
it('should call fulcrum adapter get method', async () => {
const txid = 'a'.repeat(64)
mockAdapters.fulcrum.get.resolves({ txid })
const result = await uut.getTransactionDetails({ txid })
assert.isTrue(mockAdapters.fulcrum.get.calledOnceWith(`electrumx/tx/data/${txid}`))
assert.deepEqual(result, { txid })
})
})
describe('#getTransactionDetailsBulk()', () => {
it('should call fulcrum adapter post method with verbose', async () => {
const txids = ['a'.repeat(64)]
const verbose = true
mockAdapters.fulcrum.post.resolves({ transactions: [] })
const result = await uut.getTransactionDetailsBulk({ txids, verbose })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/tx/data', { txids, verbose })
)
assert.deepEqual(result, { transactions: [] })
})
})
describe('#broadcastTransaction()', () => {
it('should call fulcrum adapter post method', async () => {
const txHex = '010203'
mockAdapters.fulcrum.post.resolves({ txid: 'abc' })
const result = await uut.broadcastTransaction({ txHex })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/tx/broadcast', { txHex })
)
assert.deepEqual(result, { txid: 'abc' })
})
})
describe('#getBlockHeaders()', () => {
it('should call fulcrum adapter get method with height and count', async () => {
const height = 100
const count = 2
mockAdapters.fulcrum.get.resolves({ headers: [] })
const result = await uut.getBlockHeaders({ height, count })
assert.isTrue(
mockAdapters.fulcrum.get.calledOnceWith(`electrumx/block/headers/${height}?count=${count}`)
)
assert.deepEqual(result, { headers: [] })
})
})
describe('#getBlockHeadersBulk()', () => {
it('should call fulcrum adapter post method', async () => {
const heights = [{ height: 100, count: 2 }]
mockAdapters.fulcrum.post.resolves({ headers: [] })
const result = await uut.getBlockHeadersBulk({ heights })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/block/headers', { heights })
)
assert.deepEqual(result, { headers: [] })
})
})
describe('#getTransactions()', () => {
it('should call fulcrum adapter and sort transactions when allTxs is false', async () => {
const address = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
const allTxs = false
const mockTransactions = [
{ tx_hash: 'aaa', height: 100 },
{ tx_hash: 'bbb', height: 200 },
{ tx_hash: 'ccc', height: 150 }
]
mockAdapters.fulcrum.get.resolves({
transactions: mockTransactions
})
const result = await uut.getTransactions({ address, allTxs })
assert.isTrue(mockAdapters.fulcrum.get.calledOnceWith(`electrumx/transactions/${address}`))
assert.property(result, 'transactions')
// Transactions should be sorted and limited to 100
if (result.transactions && result.transactions.length > 100) {
assert.isAtMost(result.transactions.length, 100)
}
})
it('should return all transactions when allTxs is true', async () => {
const address = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
const allTxs = true
const mockTransactions = Array(150).fill({ tx_hash: 'aaa', height: 100 })
mockAdapters.fulcrum.get.resolves({
transactions: mockTransactions
})
const result = await uut.getTransactions({ address, allTxs })
assert.property(result, 'transactions')
// All transactions should be returned when allTxs is true
assert.equal(result.transactions.length, 150)
})
})
describe('#getTransactionsBulk()', () => {
it('should call fulcrum adapter and sort transactions for each address', async () => {
const addresses = ['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf']
const allTxs = false
const mockResponse = {
transactions: [
{
transactions: [
{ tx_hash: 'aaa', height: 100 },
{ tx_hash: 'bbb', height: 200 }
]
}
]
}
mockAdapters.fulcrum.post.resolves(mockResponse)
const result = await uut.getTransactionsBulk({ addresses, allTxs })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/transactions/', { addresses })
)
assert.property(result, 'transactions')
})
it('should limit to 100 transactions when allTxs is false', async () => {
const addresses = ['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf']
const allTxs = false
const mockTransactions = Array(150).fill({ tx_hash: 'aaa', height: 100 })
const mockResponse = {
transactions: [
{
transactions: mockTransactions
}
]
}
mockAdapters.fulcrum.post.resolves(mockResponse)
const result = await uut.getTransactionsBulk({ addresses, allTxs })
assert.isAtMost(result.transactions[0].transactions.length, 100)
})
})
describe('#getMempool()', () => {
it('should call fulcrum adapter get method', async () => {
const address = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
mockAdapters.fulcrum.get.resolves({ mempool: [] })
const result = await uut.getMempool({ address })
assert.isTrue(mockAdapters.fulcrum.get.calledOnceWith(`electrumx/unconfirmed/${address}`))
assert.deepEqual(result, { mempool: [] })
})
})
describe('#getMempoolBulk()', () => {
it('should call fulcrum adapter post method', async () => {
const addresses = ['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf']
mockAdapters.fulcrum.post.resolves({ mempool: [] })
const result = await uut.getMempoolBulk({ addresses })
assert.isTrue(
mockAdapters.fulcrum.post.calledOnceWith('electrumx/unconfirmed/', { addresses })
)
assert.deepEqual(result, { mempool: [] })
})
})
})
@@ -0,0 +1,137 @@
/*
Unit tests for BlockchainUseCases.
*/
import { assert } from 'chai'
import sinon from 'sinon'
import BlockchainUseCases from '../../../src/use-cases/full-node-blockchain-use-cases.js'
describe('#full-node-blockchain-use-cases.js', () => {
let sandbox
let mockAdapters
let uut
const createAdapters = () => {
return {
fullNode: {
call: sandbox.stub()
}
}
}
beforeEach(() => {
sandbox = sinon.createSandbox()
mockAdapters = createAdapters()
uut = new BlockchainUseCases({ adapters: mockAdapters })
})
afterEach(() => {
sandbox.restore()
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new BlockchainUseCases()
}, /Adapters instance required/)
})
it('should require full node adapter', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new BlockchainUseCases({ adapters: {} })
}, /Full node adapter required/)
})
})
describe('#getBestBlockHash()', () => {
it('should call full node adapter without parameters', async () => {
mockAdapters.fullNode.call.resolves('hash')
const result = await uut.getBestBlockHash()
assert.equal(result, 'hash')
assert.isTrue(mockAdapters.fullNode.call.calledOnceWithExactly('getbestblockhash'))
})
})
describe('#getBlockHeaders()', () => {
it('should call adapter for each hash and return aggregated result', async () => {
const hashes = ['a'.repeat(64), 'b'.repeat(64)]
mockAdapters.fullNode.call
.onFirstCall().resolves('header-1')
.onSecondCall().resolves('header-2')
const result = await uut.getBlockHeaders({ hashes, verbose: true })
assert.deepEqual(result, ['header-1', 'header-2'])
assert.isTrue(
mockAdapters.fullNode.call.calledWithExactly(
'getblockheader',
[hashes[0], true],
`getblockheader-${hashes[0]}`
)
)
assert.isTrue(
mockAdapters.fullNode.call.calledWithExactly(
'getblockheader',
[hashes[1], true],
`getblockheader-${hashes[1]}`
)
)
})
it('should rethrow errors from adapter', async () => {
const hashes = ['a'.repeat(64)]
mockAdapters.fullNode.call.rejects(new Error('failure'))
try {
await uut.getBlockHeaders({ hashes })
assert.fail('Unexpected success')
} catch (err) {
assert.equal(err.message, 'failure')
}
})
})
describe('#getTxOut()', () => {
it('should pass parameters to full node call', async () => {
mockAdapters.fullNode.call.resolves({ value: 1 })
const result = await uut.getTxOut({
txid: 'txid',
n: 0,
includeMempool: true
})
assert.deepEqual(result, { value: 1 })
assert.isTrue(
mockAdapters.fullNode.call.calledOnceWithExactly(
'gettxout',
['txid', 0, true]
)
)
})
})
describe('#verifyTxOutProofs()', () => {
it('should call adapter for each proof and return aggregated results', async () => {
const proofs = ['proof-1', 'proof-2']
mockAdapters.fullNode.call.onFirstCall().resolves(['txid-1'])
mockAdapters.fullNode.call.onSecondCall().resolves(['txid-2'])
const result = await uut.verifyTxOutProofs({ proofs })
assert.deepEqual(result, [['txid-1'], ['txid-2']])
assert.isTrue(
mockAdapters.fullNode.call.calledWithExactly(
'verifytxoutproof',
['proof-1'],
`verifytxoutproof-${proofs[0].slice(0, 16)}`
)
)
})
})
})
@@ -0,0 +1,53 @@
/*
Unit tests for ControlUseCases.
*/
import { assert } from 'chai'
import ControlUseCases from '../../../src/use-cases/full-node-control-use-cases.js'
describe('#full-node-control-use-cases.js', () => {
let mockAdapters
let uut
beforeEach(() => {
mockAdapters = {
fullNode: {
call: async () => ({})
}
}
uut = new ControlUseCases({ adapters: mockAdapters })
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new ControlUseCases()
}, /Adapters instance required/)
})
it('should require full node adapter', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new ControlUseCases({ adapters: {} })
}, /Full node adapter required/)
})
})
describe('#getNetworkInfo()', () => {
it('should call full node adapter with correct method', async () => {
let capturedMethod = ''
mockAdapters.fullNode.call = async method => {
capturedMethod = method
return { version: 1 }
}
const result = await uut.getNetworkInfo()
assert.equal(capturedMethod, 'getnetworkinfo')
assert.deepEqual(result, { version: 1 })
})
})
})
@@ -0,0 +1,54 @@
/*
Unit tests for DSProofUseCases.
*/
import { assert } from 'chai'
import DSProofUseCases from '../../../src/use-cases/full-node-dsproof-use-cases.js'
describe('#full-node-dsproof-use-cases.js', () => {
let mockAdapters
let uut
beforeEach(() => {
mockAdapters = {
fullNode: {
call: async () => ({})
}
}
uut = new DSProofUseCases({ adapters: mockAdapters })
})
describe('#constructor()', () => {
it('should require adapters', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new DSProofUseCases()
}, /Adapters instance required/)
})
it('should require full node adapter', () => {
assert.throws(() => {
// eslint-disable-next-line no-new
new DSProofUseCases({ adapters: {} })
}, /Full node adapter required/)
})
})
describe('#getDSProof()', () => {
it('should pass txid and verbose parameters to adapter', async () => {
let capturedArgs = null
mockAdapters.fullNode.call = async (method, params) => {
capturedArgs = { method, params }
return { success: true }
}
const result = await uut.getDSProof({ txid: 'a'.repeat(64), verbose: 2 })
assert.equal(capturedArgs.method, 'getdsproof')
assert.deepEqual(capturedArgs.params, ['a'.repeat(64), 2])
assert.deepEqual(result, { success: true })
})
})
})

Some files were not shown because too many files have changed in this diff Show More