mirror of
https://github.com/benjamin-wilson/public-pool.git
synced 2026-09-29 09:05:06 -07:00
Compare commits
202
Commits
master
...
3d58802feb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d58802feb | ||
|
|
bc6f2eebd8 | ||
|
|
4f29269fed | ||
|
|
126b05224f | ||
|
|
12f3983c8f | ||
|
|
9998c93eae | ||
|
|
bdd3c7c3ae | ||
|
|
1943ea7768 | ||
|
|
6dcbb8436d | ||
|
|
d5c5a90aa6 | ||
|
|
bc8eba3c49 | ||
|
|
bed275fe7b | ||
|
|
d1fb186e5d | ||
|
|
cd0cb9bfe0 | ||
|
|
c3ad01a38f | ||
|
|
f20bb37509 | ||
|
|
10cd17076e | ||
|
|
a9d425f32f | ||
|
|
a33c530268 | ||
|
|
bcd6bb0aa7 | ||
|
|
1c5a3d9a94 | ||
|
|
efbd95e464 | ||
|
|
bb0acf0395 | ||
|
|
9b99c5153a | ||
|
|
a693501648 | ||
|
|
f259af947e | ||
|
|
f29081de36 | ||
|
|
0acc1910db | ||
|
|
d847e2666a | ||
|
|
294c4a6825 | ||
|
|
8252111c32 | ||
|
|
deaf3e56bd | ||
|
|
9b73e33b13 | ||
|
|
0560b874dc | ||
|
|
7f6f42c5c9 | ||
|
|
4c59797886 | ||
|
|
4c91e69ca8 | ||
|
|
7b7dc87242 | ||
|
|
df35549f27 | ||
|
|
8c795a3fa2 | ||
|
|
ac7827a944 | ||
|
|
17ba4afc1a | ||
|
|
b612b50f3e | ||
|
|
b6a951bdee | ||
|
|
817f416b79 | ||
|
|
d05d5f0b37 | ||
|
|
3da95b964b | ||
|
|
4155335bb5 | ||
|
|
13106347b2 | ||
|
|
96e0e36755 | ||
|
|
93dde1a899 | ||
|
|
eac0fe65ab | ||
|
|
f14d76c2ea | ||
|
|
51e3afb7e7 | ||
|
|
3c33fcd3c4 | ||
|
|
78fbf12f8f | ||
|
|
3e1c303fa0 | ||
|
|
4f51a4d05c | ||
|
|
2d6b01691c | ||
|
|
4a5d4bbb71 | ||
|
|
c0604aaf2a | ||
|
|
ec69f5fb6c | ||
|
|
fb367ac5f0 | ||
|
|
3d6c8b3134 | ||
|
|
2a37cb1f06 | ||
|
|
f2d2283b47 | ||
|
|
4cab56a1a0 | ||
|
|
c5169e105e | ||
|
|
2d6d2afacb | ||
|
|
327be48ade | ||
|
|
cc0ca3979e | ||
|
|
9bf3dde862 | ||
|
|
8b2bea702a | ||
|
|
63a1618f26 | ||
|
|
1b0f3f52d8 | ||
|
|
78c00fd25c | ||
|
|
dd45c60eff | ||
|
|
0481dfda6e | ||
|
|
6f6abe5e2d | ||
|
|
ff84d8284f | ||
|
|
cdf6eb807b | ||
|
|
d9c89347e1 | ||
|
|
c1d8341c22 | ||
|
|
f39c0dc059 | ||
|
|
3dab14e3b7 | ||
|
|
5060345809 | ||
|
|
b44f09848e | ||
|
|
9b5402f1b0 | ||
|
|
17881f70d6 | ||
|
|
e9949f4038 | ||
|
|
7c3b31f7b3 | ||
|
|
78deb3a375 | ||
|
|
c5c8810da6 | ||
|
|
8584c442dc | ||
|
|
fd24807c55 | ||
|
|
bd5333a725 | ||
|
|
419eb09853 | ||
|
|
74f5783dc3 | ||
|
|
34a27d0f2f | ||
|
|
d8e087f720 | ||
|
|
34eb0ca0f2 | ||
|
|
a33d7e07b3 | ||
|
|
f8d1c61c1c | ||
|
|
326a5a7b33 | ||
|
|
903aa2628c | ||
|
|
19f49b74e6 | ||
|
|
864867ffd4 | ||
|
|
f465b837f5 | ||
|
|
637d30f1a5 | ||
|
|
df87214de9 | ||
|
|
66ce822faa | ||
|
|
78ef48b805 | ||
|
|
b545e74d4f | ||
|
|
5702e20dc0 | ||
|
|
74dd5ba66f | ||
|
|
674b02ca9d | ||
|
|
40ee610600 | ||
|
|
7e0de263f2 | ||
|
|
65232da901 | ||
|
|
220a1d1558 | ||
|
|
ae7ed021a3 | ||
|
|
056fe7af4f | ||
|
|
912ae9fe85 | ||
|
|
d513dab932 | ||
|
|
3a1f3bba10 | ||
|
|
8fdf1e839e | ||
|
|
76d92d84b4 | ||
|
|
4928f34daf | ||
|
|
88e7f5f3fb | ||
|
|
d97843af3d | ||
|
|
c1ab6a152e | ||
|
|
717a5c7878 | ||
|
|
6038af8448 | ||
|
|
d6863fad28 | ||
|
|
b9b5fe2cf5 | ||
|
|
9db0afd9df | ||
|
|
fb8715c23d | ||
|
|
ff6d446c12 | ||
|
|
02d718934d | ||
|
|
d40742ef71 | ||
|
|
38ecbdc7ec | ||
|
|
8905409880 | ||
|
|
2bfbc2d79a | ||
|
|
2ee82a269c | ||
|
|
fe4d58a60d | ||
|
|
b858a594b8 | ||
|
|
3e4cb4ff5d | ||
|
|
14f95a7fa4 | ||
|
|
522ef126d9 | ||
|
|
0c34f23284 | ||
|
|
e52d14b0a9 | ||
|
|
3727773a2e | ||
|
|
ad3035b908 | ||
|
|
3e279ee662 | ||
|
|
deeb40967e | ||
|
|
f1221651f6 | ||
|
|
32a604e745 | ||
|
|
6442bb45e0 | ||
|
|
f2930681d3 | ||
|
|
3d3d1a55a8 | ||
|
|
01adb0a997 | ||
|
|
5ead6c605b | ||
|
|
4fd8d9ceb6 | ||
|
|
9d4c3ad35e | ||
|
|
aab69b65fc | ||
|
|
9895e80a01 | ||
|
|
9617ec5685 | ||
|
|
aefb180fb4 | ||
|
|
87508bfb69 | ||
|
|
39e537a00c | ||
|
|
9ecfc68155 | ||
|
|
3e2de62259 | ||
|
|
8e977c21a1 | ||
|
|
5fd9f98807 | ||
|
|
6bc42defef | ||
|
|
bbc14e2272 | ||
|
|
fc767fa770 | ||
|
|
40e32d6e1a | ||
|
|
df6ec07c58 | ||
|
|
df245f396e | ||
|
|
42fc863c7c | ||
|
|
e46bb24155 | ||
|
|
cb4a173733 | ||
|
|
83c769849d | ||
|
|
ee5fea1df5 | ||
|
|
06acad6770 | ||
|
|
f7b22bb310 | ||
|
|
6cf6a007d9 | ||
|
|
5b71632f8a | ||
|
|
c5ff8521ac | ||
|
|
53ee510a1e | ||
|
|
7be554a358 | ||
|
|
eb5d434157 | ||
|
|
893c7c2003 | ||
|
|
4736eadf7b | ||
|
|
1089e6210c | ||
|
|
017978d250 | ||
|
|
5a17528b8f | ||
|
|
0b147ea5db | ||
|
|
bffcf6c74c | ||
|
|
96a38f9d9b | ||
|
|
39c4c033e2 |
+132
-8
@@ -10,12 +10,102 @@ BITCOIN_RPC_PASSWORD=
|
|||||||
BITCOIN_RPC_PORT=8332
|
BITCOIN_RPC_PORT=8332
|
||||||
BITCOIN_RPC_TIMEOUT=10000
|
BITCOIN_RPC_TIMEOUT=10000
|
||||||
|
|
||||||
# Enable in bitcoin.conf with
|
# Keep an authoritative getblocktemplate longpoll outstanding so new-tip work
|
||||||
# zmqpubrawblock=tcp://*:3000
|
# does not wait for the ZMQ -> RPC round trip. The normal ZMQ feed remains a watchdog.
|
||||||
# BITCOIN_ZMQ_HOST="tcp://192.168.1.100:3000"
|
BLOCK_TEMPLATE_LONGPOLL_TIMEOUT_MS=600000
|
||||||
|
BLOCK_TEMPLATE_RETRY_INITIAL_MS=25
|
||||||
|
BLOCK_TEMPLATE_RETRY_MAX_MS=1000
|
||||||
|
|
||||||
|
# Enable in bitcoin.conf with:
|
||||||
|
# zmqpubrawblock=tcp://0.0.0.0:3000
|
||||||
|
BITCOIN_ZMQ_HOST=tcp://192.168.1.100:3000
|
||||||
|
|
||||||
API_PORT=3334
|
API_PORT=3334
|
||||||
STRATUM_PORT=3333
|
# Docker host/IP and public host port for the API listener.
|
||||||
|
# Keep API_BIND_HOST as 127.0.0.1 when a reverse proxy terminates public traffic.
|
||||||
|
API_BIND_HOST=127.0.0.1
|
||||||
|
API_PUBLIC_PORT=3334
|
||||||
|
API_WORKERS=4
|
||||||
|
|
||||||
|
# Docker json-file log rotation. Applies when using the compose files.
|
||||||
|
DOCKER_LOG_MAX_SIZE=100m
|
||||||
|
DOCKER_LOG_MAX_FILES=5
|
||||||
|
|
||||||
|
# Keep high-volume production logging off by default. Enable only during a
|
||||||
|
# focused diagnostic window.
|
||||||
|
STRATUM_FANOUT_LOG_ENABLED=false
|
||||||
|
BLOCK_NOTIFICATION_TRACE_LOG_ENABLED=false
|
||||||
|
DATUM_VERBOSE_LOGGING=false
|
||||||
|
SV2_AUTH_FAILURE_LOG_ENABLED=false
|
||||||
|
|
||||||
|
# Plain TCP Stratum ports accept both SV1 JSON-RPC and SV2 Noise/binary traffic.
|
||||||
|
# Legacy/default ports mine in solo mode.
|
||||||
|
STRATUM_PORTS=3333,3332,3331,3330
|
||||||
|
# Optional PPLNS-mode SV1/SV2 autodetect ports.
|
||||||
|
#PPLNS_STRATUM_PORTS=
|
||||||
|
STRATUM_WORKERS=2
|
||||||
|
STRATUM_WORKER_MAX_MEMORY_RESTART=4096M
|
||||||
|
# High-byte base for pool-assigned SV2 extranonce prefixes. PM2 reserves two
|
||||||
|
# values per NODE_APP_INSTANCE so an old/new reload pair cannot overlap. Keep
|
||||||
|
# base + (2 * worker index) + reload parity <= 255. Separate pool containers
|
||||||
|
# sharing work must use non-overlapping ranges of 2 * STRATUM_WORKERS values.
|
||||||
|
SV2_EXTRANONCE_NAMESPACE_BASE=0
|
||||||
|
STRATUM_MIN_DIFFICULTY=1
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS=3600000
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS=60000
|
||||||
|
# Disconnect slow/non-reading SV1 clients before their per-socket write queue
|
||||||
|
# can grow without bound. Includes bytes already buffered by Node.js.
|
||||||
|
STRATUM_MAX_SOCKET_BUFFER_BYTES=262144
|
||||||
|
# Immediately publish a consensus-valid, subsidy-only solo job before the full
|
||||||
|
# transaction template. SV2 uses the same activation to select its pre-staged
|
||||||
|
# future job; the full job then follows on the active tip.
|
||||||
|
SV1_SUBSIDY_BRIDGE_ENABLED=true
|
||||||
|
# Comma-separated: solo,pplns. PPLNS requires a fresh precomputed snapshot;
|
||||||
|
# solo remains the safe default and is always published first when both are set.
|
||||||
|
SV1_SUBSIDY_BRIDGE_PAYOUT_MODES=solo
|
||||||
|
SV1_SUBSIDY_BRIDGE_PPLNS_SEED_MAX_AGE_MS=300000
|
||||||
|
STRATUM_JOB_RETENTION_MS=300000
|
||||||
|
STRATUM_SUBMISSION_DEDUP_TTL_MS=300000
|
||||||
|
STRATUM_SUBMISSION_DEDUP_MAX_ENTRIES=10000
|
||||||
|
|
||||||
|
# Optional additional SV2-only mining ports. Usually unnecessary when STRATUM_PORTS are exposed.
|
||||||
|
#STRATUM_V2_PORTS=
|
||||||
|
#PPLNS_STRATUM_V2_PORTS=
|
||||||
|
#SV2_START_DIFFICULTY=100000
|
||||||
|
#SV2_TARGET_SHARES_PER_MINUTE=2
|
||||||
|
#SV2_DIFFICULTY_CHECK_INTERVAL_MS=60000
|
||||||
|
#STRATUM_V2_SOCKET_TIMEOUT_MS=3600000
|
||||||
|
# Per-client lifecycle bounds. Obsolete queued jobs are coalesced; clients are
|
||||||
|
# disconnected instead of dropping still-recoverable candidates or buffering forever.
|
||||||
|
SV2_JOB_RETENTION_MS=300000
|
||||||
|
SV2_MAX_RETAINED_JOBS_PER_CHANNEL=16
|
||||||
|
SV2_MAX_QUEUED_JOB_OPERATIONS=4
|
||||||
|
SV2_MAX_SOCKET_BUFFER_BYTES=262144
|
||||||
|
SV2_SOCKET_WRITE_TIMEOUT_MS=2000
|
||||||
|
#SV2_AUTHORITY_PRIVKEY=
|
||||||
|
#SV2_JDP_PORTS=
|
||||||
|
#PPLNS_SV2_JDP_PORTS=
|
||||||
|
#SV2_JDP_POOL_PAYOUT_ADDRESS=
|
||||||
|
#SV2_JDP_TOKEN_TTL_MS=600000
|
||||||
|
#SV2_TDP_PORTS=
|
||||||
|
#PPLNS_SV2_TDP_PORTS=
|
||||||
|
#SV2_TDP_POOL_PAYOUT_ADDRESS=
|
||||||
|
|
||||||
|
# Optional DATUM Prime-compatible listener. DATUM_POOL_PAYOUT_ADDRESS is the
|
||||||
|
# required pool coinbase output DATUM gateways must include in custom templates.
|
||||||
|
#DATUM_PORTS=
|
||||||
|
#PPLNS_DATUM_PORTS=
|
||||||
|
#DATUM_POOL_PAYOUT_ADDRESS=
|
||||||
|
#DATUM_SHARE_DIFFICULTY=1
|
||||||
|
# 32-byte hex seed for the DATUM server identity key. DATUM clients must be
|
||||||
|
# configured with the matching logged public key.
|
||||||
|
#DATUM_IDENTITY_SEED=
|
||||||
|
|
||||||
|
STRATUM_SECURE=true
|
||||||
|
SECURE_STRATUM_PORTS=4333,4332,4331,4330
|
||||||
|
#PPLNS_SECURE_STRATUM_PORTS=
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
|
||||||
|
|
||||||
#optional telegram bot
|
#optional telegram bot
|
||||||
#TELEGRAM_BOT_TOKEN=
|
#TELEGRAM_BOT_TOKEN=
|
||||||
@@ -32,9 +122,43 @@ NETWORK=mainnet
|
|||||||
|
|
||||||
API_SECURE=false
|
API_SECURE=false
|
||||||
|
|
||||||
ENABLE_SOLO=false
|
#postgresql
|
||||||
ENABLE_PROXY=true
|
DB_HOST=timescaledb
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_USERNAME=public_pool
|
||||||
|
DB_PASSWORD=public_pool
|
||||||
|
DB_DATABASE=public_pool
|
||||||
|
DB_POOL_SIZE=10
|
||||||
|
DB_SSL=false
|
||||||
|
DB_SSL_REJECT_UNAUTHORIZED=true
|
||||||
|
|
||||||
BRAIINS_ACCESS_TOKEN=
|
#accepted share accounting
|
||||||
|
SHARE_ACCOUNTING_BATCH_SIZE=500
|
||||||
|
SHARE_ACCOUNTING_FLUSH_INTERVAL_MS=25
|
||||||
|
SHARE_ACCOUNTING_MAX_QUEUE_SIZE=50000
|
||||||
|
SHARE_ACCOUNTING_SUMMARY_CACHE_MS=2500
|
||||||
|
SHARE_ACCOUNTING_SUMMARY_CACHE_MAX=10000
|
||||||
|
CLIENT_HASHRATE_PERSIST_INTERVAL_MS=60000
|
||||||
|
SHARE_ROLLUP_ENABLED=true
|
||||||
|
SHARE_ROLLUP_INTERVAL_MS=60000
|
||||||
|
SHARE_ROLLUP_SAFETY_LAG_SECONDS=30
|
||||||
|
SHARE_ROLLUP_MAX_SHARES_PER_BATCH=5000000
|
||||||
|
|
||||||
PROXY_PORT=3333
|
# payout snapshot accounting
|
||||||
|
PAYOUT_SNAPSHOT_ENABLED=true
|
||||||
|
PAYOUT_METHOD=pplns
|
||||||
|
PAYOUT_WINDOW_FACTOR=4
|
||||||
|
PAYOUT_BOOTSTRAP_WINDOW=true
|
||||||
|
# solo preserves current one-address coinbase payouts. Set to snapshot to pay
|
||||||
|
# the latest payout snapshot directly in coinbase outputs.
|
||||||
|
PAYOUT_COINBASE_MODE=solo
|
||||||
|
PAYOUT_MAX_COINBASE_OUTPUTS=200
|
||||||
|
PAYOUT_MIN_OUTPUT_SATS=546
|
||||||
|
PAYOUT_FEE_ADDRESS=
|
||||||
|
PAYOUT_FEE_PERCENT=0
|
||||||
|
PAYOUT_COINBASE_WEIGHT_BUDGET=26000
|
||||||
|
|
||||||
|
#redis
|
||||||
|
REDIS_URL=redis://redis:6379
|
||||||
|
|
||||||
|
PRODUCTION=false
|
||||||
|
|||||||
+6
-1
@@ -13,10 +13,15 @@ lerna-debug.log*
|
|||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
._*
|
||||||
|
|
||||||
# Tests
|
# Tests
|
||||||
/coverage
|
/coverage
|
||||||
/.nyc_output
|
/.nyc_output
|
||||||
|
/.baseline-*.json
|
||||||
|
/.test-artifacts
|
||||||
|
/.profiles
|
||||||
|
/.local-runtime
|
||||||
|
|
||||||
# IDEs and editors
|
# IDEs and editors
|
||||||
/.idea
|
/.idea
|
||||||
@@ -38,7 +43,7 @@ settings.json
|
|||||||
|
|
||||||
#DB
|
#DB
|
||||||
**.sqlite**
|
**.sqlite**
|
||||||
./full-setup/data/*
|
/full-setup/data/
|
||||||
|
|
||||||
#https
|
#https
|
||||||
**.pem
|
**.pem
|
||||||
+6
-4
@@ -2,7 +2,7 @@
|
|||||||
# Docker build environment #
|
# Docker build environment #
|
||||||
############################
|
############################
|
||||||
|
|
||||||
FROM node:18.16.1-bookworm-slim AS build
|
FROM node:24.16.0-bookworm-slim AS build
|
||||||
|
|
||||||
# Upgrade all packages and install dependencies
|
# Upgrade all packages and install dependencies
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
@@ -11,6 +11,8 @@ RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
|||||||
python3 \
|
python3 \
|
||||||
build-essential \
|
build-essential \
|
||||||
cmake \
|
cmake \
|
||||||
|
curl \
|
||||||
|
ca-certificates \
|
||||||
&& apt clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
&& apt clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
@@ -18,13 +20,13 @@ WORKDIR /build
|
|||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Build Public Pool using NPM
|
# Build Public Pool using NPM
|
||||||
RUN npm i && npm run build
|
RUN npm ci && npm run build && npm prune --omit=dev
|
||||||
|
|
||||||
############################
|
############################
|
||||||
# Docker final environment #
|
# Docker final environment #
|
||||||
############################
|
############################
|
||||||
|
|
||||||
FROM node:18.16.1-bookworm-slim
|
FROM node:24.16.0-bookworm-slim
|
||||||
|
|
||||||
# Expose ports for Stratum and Bitcoin RPC
|
# Expose ports for Stratum and Bitcoin RPC
|
||||||
EXPOSE 3333 3334 8332
|
EXPOSE 3333 3334 8332
|
||||||
@@ -35,4 +37,4 @@ WORKDIR /public-pool
|
|||||||
COPY --from=build /build .
|
COPY --from=build /build .
|
||||||
#COPY .env.example .env
|
#COPY .env.example .env
|
||||||
|
|
||||||
CMD ["/usr/local/bin/node", "dist/main"]
|
CMD ["npm", "run", "start:docker"]
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:24.16.0-bookworm
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
python3 \
|
||||||
|
build-essential \
|
||||||
|
cmake \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
CMD ["npm", "run", "test:integration"]
|
||||||
+101
-540
@@ -1,674 +1,235 @@
|
|||||||
GNU GENERAL PUBLIC LICENSE
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
Version 3, 29 June 2007
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Preamble
|
Preamble
|
||||||
|
|
||||||
The GNU General Public License is a free, copyleft license for
|
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||||
software and other kinds of works.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||||
to take away your freedom to share and change the works. By contrast,
|
|
||||||
the GNU General Public License is intended to guarantee your freedom to
|
|
||||||
share and change all versions of a program--to make sure it remains free
|
|
||||||
software for all its users. We, the Free Software Foundation, use the
|
|
||||||
GNU General Public License for most of our software; it applies also to
|
|
||||||
any other work released this way by its authors. You can apply it to
|
|
||||||
your programs, too.
|
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
|
||||||
have the freedom to distribute copies of free software (and charge for
|
|
||||||
them if you wish), that you receive source code or can get it if you
|
|
||||||
want it, that you can change the software or use pieces of it in new
|
|
||||||
free programs, and that you know you can do these things.
|
|
||||||
|
|
||||||
To protect your rights, we need to prevent others from denying you
|
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||||
these rights or asking you to surrender the rights. Therefore, you have
|
|
||||||
certain responsibilities if you distribute copies of the software, or if
|
|
||||||
you modify it: responsibilities to respect the freedom of others.
|
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether
|
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||||
gratis or for a fee, you must pass on to the recipients the same
|
|
||||||
freedoms that you received. You must make sure that they, too, receive
|
|
||||||
or can get the source code. And you must show them these terms so they
|
|
||||||
know their rights.
|
|
||||||
|
|
||||||
Developers that use the GNU GPL protect your rights with two steps:
|
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||||
(1) assert copyright on the software, and (2) offer you this License
|
|
||||||
giving you legal permission to copy, distribute and/or modify it.
|
|
||||||
|
|
||||||
For the developers' and authors' protection, the GPL clearly explains
|
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||||
that there is no warranty for this free software. For both users' and
|
|
||||||
authors' sake, the GPL requires that modified versions be marked as
|
|
||||||
changed, so that their problems will not be attributed erroneously to
|
|
||||||
authors of previous versions.
|
|
||||||
|
|
||||||
Some devices are designed to deny users access to install or run
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
modified versions of the software inside them, although the manufacturer
|
|
||||||
can do so. This is fundamentally incompatible with the aim of
|
|
||||||
protecting users' freedom to change the software. The systematic
|
|
||||||
pattern of such abuse occurs in the area of products for individuals to
|
|
||||||
use, which is precisely where it is most unacceptable. Therefore, we
|
|
||||||
have designed this version of the GPL to prohibit the practice for those
|
|
||||||
products. If such problems arise substantially in other domains, we
|
|
||||||
stand ready to extend this provision to those domains in future versions
|
|
||||||
of the GPL, as needed to protect the freedom of users.
|
|
||||||
|
|
||||||
Finally, every program is threatened constantly by software patents.
|
|
||||||
States should not allow patents to restrict development and use of
|
|
||||||
software on general-purpose computers, but in those that do, we wish to
|
|
||||||
avoid the special danger that patents applied to a free program could
|
|
||||||
make it effectively proprietary. To prevent this, the GPL assures that
|
|
||||||
patents cannot be used to render the program non-free.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
|
||||||
modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
0. Definitions.
|
0. Definitions.
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU General Public License.
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this
|
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||||
License. Each licensee is addressed as "you". "Licensees" and
|
|
||||||
"recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work
|
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||||
in a fashion requiring copyright permission, other than the making of an
|
|
||||||
exact copy. The resulting work is called a "modified version" of the
|
|
||||||
earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based
|
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||||
on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without
|
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
permission, would make you directly or secondarily liable for
|
|
||||||
infringement under applicable copyright law, except executing it on a
|
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
|
||||||
distribution (with or without modification), making available to the
|
|
||||||
public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other
|
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
parties to make or receive copies. Mere interaction with a user through
|
|
||||||
a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices"
|
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
to the extent that it includes a convenient and prominently visible
|
|
||||||
feature that (1) displays an appropriate copyright notice, and (2)
|
|
||||||
tells the user that there is no warranty for the work (except to the
|
|
||||||
extent that warranties are provided), that licensees may convey the
|
|
||||||
work under this License, and how to view a copy of this License. If
|
|
||||||
the interface presents a list of user commands or options, such as a
|
|
||||||
menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
1. Source Code.
|
||||||
|
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||||
|
|
||||||
The "source code" for a work means the preferred form of the work
|
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
for making modifications to it. "Object code" means any non-source
|
|
||||||
form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official
|
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
standard defined by a recognized standards body, or, in the case of
|
|
||||||
interfaces specified for a particular programming language, one that
|
|
||||||
is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other
|
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||||
than the work as a whole, that (a) is included in the normal form of
|
|
||||||
packaging a Major Component, but which is not part of that Major
|
|
||||||
Component, and (b) serves only to enable use of the work with that
|
|
||||||
Major Component, or to implement a Standard Interface for which an
|
|
||||||
implementation is available to the public in source code form. A
|
|
||||||
"Major Component", in this context, means a major essential component
|
|
||||||
(kernel, window system, and so on) of the specific operating system
|
|
||||||
(if any) on which the executable work runs, or a compiler used to
|
|
||||||
produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all
|
|
||||||
the source code needed to generate, install, and (for an executable
|
|
||||||
work) run the object code and to modify the work, including scripts to
|
|
||||||
control those activities. However, it does not include the work's
|
|
||||||
System Libraries, or general-purpose tools or generally available free
|
|
||||||
programs which are used unmodified in performing those activities but
|
|
||||||
which are not part of the work. For example, Corresponding Source
|
|
||||||
includes interface definition files associated with source files for
|
|
||||||
the work, and the source code for shared libraries and dynamically
|
|
||||||
linked subprograms that the work is specifically designed to require,
|
|
||||||
such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
can regenerate automatically from other parts of the Corresponding
|
|
||||||
Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
All rights granted under this License are granted for the term of
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
copyright on the Program, and are irrevocable provided the stated
|
|
||||||
conditions are met. This License explicitly affirms your unlimited
|
|
||||||
permission to run the unmodified Program. The output from running a
|
|
||||||
covered work is covered by this License only if the output, given its
|
|
||||||
content, constitutes a covered work. This License acknowledges your
|
|
||||||
rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
convey, without conditions so long as your license otherwise remains
|
|
||||||
in force. You may convey covered works to others for the sole purpose
|
|
||||||
of having them make modifications exclusively for you, or provide you
|
|
||||||
with facilities for running those works, provided that you comply with
|
|
||||||
the terms of this License in conveying all material for which you do
|
|
||||||
not control copyright. Those thus making or running the covered works
|
|
||||||
for you must do so exclusively on your behalf, under your direction
|
|
||||||
and control, on terms that prohibit them from making any copies of
|
|
||||||
your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under
|
|
||||||
the conditions stated below. Sublicensing is not allowed; section 10
|
|
||||||
makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
No covered work shall be deemed part of an effective technological
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
measure under any applicable law fulfilling obligations under article
|
|
||||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
|
||||||
similar laws prohibiting or restricting circumvention of such
|
|
||||||
measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid
|
|
||||||
circumvention of technological measures to the extent such circumvention
|
|
||||||
is effected by exercising rights under this License with respect to
|
|
||||||
the covered work, and you disclaim any intention to limit operation or
|
|
||||||
modification of the work as a means of enforcing, against the work's
|
|
||||||
users, your or third parties' legal rights to forbid circumvention of
|
|
||||||
technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
You may convey verbatim copies of the Program's source code as you
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
receive it, in any medium, provided that you conspicuously and
|
|
||||||
appropriately publish on each copy an appropriate copyright notice;
|
|
||||||
keep intact all notices stating that this License and any
|
|
||||||
non-permissive terms added in accord with section 7 apply to the code;
|
|
||||||
keep intact all notices of the absence of any warranty; and give all
|
|
||||||
recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey,
|
|
||||||
and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
You may convey a work based on the Program, or the modifications to
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
produce it from the Program, in the form of source code under the
|
|
||||||
terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||||
it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
released under this License and any conditions added under section
|
|
||||||
7. This requirement modifies the requirement in section 4 to
|
|
||||||
"keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
License to anyone who comes into possession of a copy. This
|
|
||||||
License will therefore apply, along with any applicable section 7
|
|
||||||
additional terms, to the whole of the work, and all its parts,
|
|
||||||
regardless of how they are packaged. This License gives no
|
|
||||||
permission to license the work in any other way, but it does not
|
|
||||||
invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
Appropriate Legal Notices; however, if the Program has interactive
|
|
||||||
interfaces that do not display Appropriate Legal Notices, your
|
|
||||||
work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent
|
|
||||||
works, which are not by their nature extensions of the covered work,
|
|
||||||
and which are not combined with it such as to form a larger program,
|
|
||||||
in or on a volume of a storage or distribution medium, is called an
|
|
||||||
"aggregate" if the compilation and its resulting copyright are not
|
|
||||||
used to limit the access or legal rights of the compilation's users
|
|
||||||
beyond what the individual works permit. Inclusion of a covered work
|
|
||||||
in an aggregate does not cause this License to apply to the other
|
|
||||||
parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
You may convey a covered work in object code form under the terms
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
of sections 4 and 5, provided that you also convey the
|
|
||||||
machine-readable Corresponding Source under the terms of this License,
|
|
||||||
in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
(including a physical distribution medium), accompanied by the
|
|
||||||
Corresponding Source fixed on a durable physical medium
|
|
||||||
customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
(including a physical distribution medium), accompanied by a
|
|
||||||
written offer, valid for at least three years and valid for as
|
|
||||||
long as you offer spare parts or customer support for that product
|
|
||||||
model, to give anyone who possesses the object code either (1) a
|
|
||||||
copy of the Corresponding Source for all the software in the
|
|
||||||
product that is covered by this License, on a durable physical
|
|
||||||
medium customarily used for software interchange, for a price no
|
|
||||||
more than your reasonable cost of physically performing this
|
|
||||||
conveying of source, or (2) access to copy the
|
|
||||||
Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
written offer to provide the Corresponding Source. This
|
|
||||||
alternative is allowed only occasionally and noncommercially, and
|
|
||||||
only if you received the object code with such an offer, in accord
|
|
||||||
with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
place (gratis or for a charge), and offer equivalent access to the
|
|
||||||
Corresponding Source in the same way through the same place at no
|
|
||||||
further charge. You need not require recipients to copy the
|
|
||||||
Corresponding Source along with the object code. If the place to
|
|
||||||
copy the object code is a network server, the Corresponding Source
|
|
||||||
may be on a different server (operated by you or a third party)
|
|
||||||
that supports equivalent copying facilities, provided you maintain
|
|
||||||
clear directions next to the object code saying where to find the
|
|
||||||
Corresponding Source. Regardless of what server hosts the
|
|
||||||
Corresponding Source, you remain obligated to ensure that it is
|
|
||||||
available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
you inform other peers where the object code and Corresponding
|
|
||||||
Source of the work are being offered to the general public at no
|
|
||||||
charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded
|
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
from the Corresponding Source as a System Library, need not be
|
|
||||||
included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any
|
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
tangible personal property which is normally used for personal, family,
|
|
||||||
or household purposes, or (2) anything designed or sold for incorporation
|
|
||||||
into a dwelling. In determining whether a product is a consumer product,
|
|
||||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
|
||||||
product received by a particular user, "normally used" refers to a
|
|
||||||
typical or common use of that class of product, regardless of the status
|
|
||||||
of the particular user or of the way in which the particular user
|
|
||||||
actually uses, or expects or is expected to use, the product. A product
|
|
||||||
is a consumer product regardless of whether the product has substantial
|
|
||||||
commercial, industrial or non-consumer uses, unless such uses represent
|
|
||||||
the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods,
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
procedures, authorization keys, or other information required to install
|
|
||||||
and execute modified versions of a covered work in that User Product from
|
|
||||||
a modified version of its Corresponding Source. The information must
|
|
||||||
suffice to ensure that the continued functioning of the modified object
|
|
||||||
code is in no case prevented or interfered with solely because
|
|
||||||
modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
specifically for use in, a User Product, and the conveying occurs as
|
|
||||||
part of a transaction in which the right of possession and use of the
|
|
||||||
User Product is transferred to the recipient in perpetuity or for a
|
|
||||||
fixed term (regardless of how the transaction is characterized), the
|
|
||||||
Corresponding Source conveyed under this section must be accompanied
|
|
||||||
by the Installation Information. But this requirement does not apply
|
|
||||||
if neither you nor any third party retains the ability to install
|
|
||||||
modified object code on the User Product (for example, the work has
|
|
||||||
been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
requirement to continue to provide support service, warranty, or updates
|
|
||||||
for a work that has been modified or installed by the recipient, or for
|
|
||||||
the User Product in which it has been modified or installed. Access to a
|
|
||||||
network may be denied when the modification itself materially and
|
|
||||||
adversely affects the operation of the network or violates the rules and
|
|
||||||
protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided,
|
|
||||||
in accord with this section must be in a format that is publicly
|
|
||||||
documented (and with an implementation available to the public in
|
|
||||||
source code form), and must require no special password or key for
|
|
||||||
unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
7. Additional Terms.
|
||||||
|
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
"Additional permissions" are terms that supplement the terms of this
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
License by making exceptions from one or more of its conditions.
|
|
||||||
Additional permissions that are applicable to the entire Program shall
|
|
||||||
be treated as though they were included in this License, to the extent
|
|
||||||
that they are valid under applicable law. If additional permissions
|
|
||||||
apply only to part of the Program, that part may be used separately
|
|
||||||
under those permissions, but the entire Program remains governed by
|
|
||||||
this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
remove any additional permissions from that copy, or from any part of
|
|
||||||
it. (Additional permissions may be written to require their own
|
|
||||||
removal in certain cases when you modify the work.) You may place
|
|
||||||
additional permissions on material, added by you to a covered work,
|
|
||||||
for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
add to a covered work, you may (if authorized by the copyright holders of
|
|
||||||
that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
author attributions in that material or in the Appropriate Legal
|
|
||||||
Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
requiring that modified versions of such material be marked in
|
|
||||||
reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that
|
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
material by anyone who conveys the material (or modified versions of
|
|
||||||
it) with contractual assumptions of liability to the recipient, for
|
|
||||||
any liability that these contractual assumptions directly impose on
|
|
||||||
those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
restrictions" within the meaning of section 10. If the Program as you
|
|
||||||
received it, or any part of it, contains a notice stating that it is
|
|
||||||
governed by this License along with a term that is a further
|
|
||||||
restriction, you may remove that term. If a license document contains
|
|
||||||
a further restriction but permits relicensing or conveying under this
|
|
||||||
License, you may add to a covered work material governed by the terms
|
|
||||||
of that license document, provided that the further restriction does
|
|
||||||
not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
must place, in the relevant source files, a statement of the
|
|
||||||
additional terms that apply to those files, or a notice indicating
|
|
||||||
where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the
|
|
||||||
form of a separately written license, or stated as exceptions;
|
|
||||||
the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
8. Termination.
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
provided under this License. Any attempt otherwise to propagate or
|
|
||||||
modify it is void, and will automatically terminate your rights under
|
|
||||||
this License (including any patent licenses granted under the third
|
|
||||||
paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
license from a particular copyright holder is reinstated (a)
|
|
||||||
provisionally, unless and until the copyright holder explicitly and
|
|
||||||
finally terminates your license, and (b) permanently, if the copyright
|
|
||||||
holder fails to notify you of the violation by some reasonable means
|
|
||||||
prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
reinstated permanently if the copyright holder notifies you of the
|
|
||||||
violation by some reasonable means, this is the first time you have
|
|
||||||
received notice of violation of this License (for any work) from that
|
|
||||||
copyright holder, and you cure the violation prior to 30 days after
|
|
||||||
your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
licenses of parties who have received copies or rights from you under
|
|
||||||
this License. If your rights have been terminated and not permanently
|
|
||||||
reinstated, you do not qualify to receive new licenses for the same
|
|
||||||
material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
run a copy of the Program. Ancillary propagation of a covered work
|
|
||||||
occurring solely as a consequence of using peer-to-peer transmission
|
|
||||||
to receive a copy likewise does not require acceptance. However,
|
|
||||||
nothing other than this License grants you permission to propagate or
|
|
||||||
modify any covered work. These actions infringe copyright if you do
|
|
||||||
not accept this License. Therefore, by modifying or propagating a
|
|
||||||
covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
receives a license from the original licensors, to run, modify and
|
|
||||||
propagate that work, subject to this License. You are not responsible
|
|
||||||
for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an
|
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
organization, or substantially all assets of one, or subdividing an
|
|
||||||
organization, or merging organizations. If propagation of a covered
|
|
||||||
work results from an entity transaction, each party to that
|
|
||||||
transaction who receives a copy of the work also receives whatever
|
|
||||||
licenses to the work the party's predecessor in interest had or could
|
|
||||||
give under the previous paragraph, plus a right to possession of the
|
|
||||||
Corresponding Source of the work from the predecessor in interest, if
|
|
||||||
the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
rights granted or affirmed under this License. For example, you may
|
|
||||||
not impose a license fee, royalty, or other charge for exercise of
|
|
||||||
rights granted under this License, and you may not initiate litigation
|
|
||||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
|
||||||
any patent claim is infringed by making, using, selling, offering for
|
|
||||||
sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
11. Patents.
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this
|
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||||
License of the Program or a work on which the Program is based. The
|
|
||||||
work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims
|
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
owned or controlled by the contributor, whether already acquired or
|
|
||||||
hereafter acquired, that would be infringed by some manner, permitted
|
|
||||||
by this License, of making, using, or selling its contributor version,
|
|
||||||
but do not include claims that would be infringed only as a
|
|
||||||
consequence of further modification of the contributor version. For
|
|
||||||
purposes of this definition, "control" includes the right to grant
|
|
||||||
patent sublicenses in a manner consistent with the requirements of
|
|
||||||
this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
patent license under the contributor's essential patent claims, to
|
|
||||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
|
||||||
propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express
|
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
agreement or commitment, however denominated, not to enforce a patent
|
|
||||||
(such as an express permission to practice a patent or covenant not to
|
|
||||||
sue for patent infringement). To "grant" such a patent license to a
|
|
||||||
party means to make such an agreement or commitment not to enforce a
|
|
||||||
patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license,
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||||
and the Corresponding Source of the work is not available for anyone
|
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
to copy, free of charge and under the terms of this License, through a
|
|
||||||
publicly available network server or other readily accessible means,
|
|
||||||
then you must either (1) cause the Corresponding Source to be so
|
|
||||||
available, or (2) arrange to deprive yourself of the benefit of the
|
|
||||||
patent license for this particular work, or (3) arrange, in a manner
|
|
||||||
consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have
|
|
||||||
actual knowledge that, but for the patent license, your conveying the
|
|
||||||
covered work in a country, or your recipient's use of the covered work
|
|
||||||
in a country, would infringe one or more identifiable patents in that
|
|
||||||
country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
|
||||||
covered work, and grant a patent license to some of the parties
|
|
||||||
receiving the covered work authorizing them to use, propagate, modify
|
|
||||||
or convey a specific copy of the covered work, then the patent license
|
|
||||||
you grant is automatically extended to all recipients of the covered
|
|
||||||
work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within
|
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
the scope of its coverage, prohibits the exercise of, or is
|
|
||||||
conditioned on the non-exercise of one or more of the rights that are
|
|
||||||
specifically granted under this License. You may not convey a covered
|
|
||||||
work if you are a party to an arrangement with a third party that is
|
|
||||||
in the business of distributing software, under which you make payment
|
|
||||||
to the third party based on the extent of your activity of conveying
|
|
||||||
the work, and under which the third party grants, to any of the
|
|
||||||
parties who would receive the covered work from you, a discriminatory
|
|
||||||
patent license (a) in connection with copies of the covered work
|
|
||||||
conveyed by you (or copies made from those copies), or (b) primarily
|
|
||||||
for and in connection with specific products or compilations that
|
|
||||||
contain the covered work, unless you entered into that arrangement,
|
|
||||||
or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
any implied license or other defenses to infringement that may
|
|
||||||
otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
excuse you from the conditions of this License. If you cannot convey a
|
|
||||||
covered work so as to satisfy simultaneously your obligations under this
|
|
||||||
License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you
|
|
||||||
to collect a royalty for further conveying from those to whom you convey
|
|
||||||
the Program, the only way you could satisfy both those terms and this
|
|
||||||
License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Use with the GNU Affero General Public License.
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have
|
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||||
permission to link or combine any covered work with a work licensed
|
|
||||||
under version 3 of the GNU Affero General Public License into a single
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||||
combined work, and to convey the resulting work. The terms of this
|
|
||||||
License will continue to apply to the part which is the covered work,
|
|
||||||
but the special requirements of the GNU Affero General Public License,
|
|
||||||
section 13, concerning interaction through a network will apply to the
|
|
||||||
combination as such.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
the GNU General Public License from time to time. Such new versions will
|
|
||||||
be similar in spirit to the present version, but may differ in detail to
|
|
||||||
address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
Program specifies that a certain numbered version of the GNU General
|
|
||||||
Public License "or any later version" applies to it, you have the
|
|
||||||
option of following the terms and conditions either of that numbered
|
|
||||||
version or of any later version published by the Free Software
|
|
||||||
Foundation. If the Program does not specify a version number of the
|
|
||||||
GNU General Public License, you may choose any version ever published
|
|
||||||
by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future
|
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
versions of the GNU General Public License can be used, that proxy's
|
|
||||||
public statement of acceptance of a version permanently authorizes you
|
|
||||||
to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
permissions. However, no additional obligations are imposed on any
|
|
||||||
author or copyright holder as a result of your choosing to follow a
|
|
||||||
later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
|
||||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
|
||||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
|
||||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
|
||||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
|
||||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
|
||||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
16. Limitation of Liability.
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
|
||||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
|
||||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
|
||||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
|
||||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
|
||||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
|
||||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
|
||||||
SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
above cannot be given local legal effect according to their terms,
|
|
||||||
reviewing courts shall apply local law that most closely approximates
|
|
||||||
an absolute waiver of all civil liability in connection with the
|
|
||||||
Program, unless a warranty or assumption of liability accompanies a
|
|
||||||
copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
possible use to the public, the best way to achieve this is to make it
|
|
||||||
free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||||
to attach them to the start of each source file to most effectively
|
|
||||||
state the exclusion of warranty; and each file should have at least
|
|
||||||
the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) <year> <name of author>
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
it under the terms of the GNU General Public License as published by
|
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
If the program does terminal interaction, make it output a short
|
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||||
notice like this when it starts in an interactive mode:
|
|
||||||
|
|
||||||
<program> Copyright (C) <year> <name of author>
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
|
||||||
This is free software, and you are welcome to redistribute it
|
|
||||||
under certain conditions; type `show c' for details.
|
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
|
||||||
parts of the General Public License. Of course, your program's commands
|
|
||||||
might be different; for a GUI interface, you would use an "about box".
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school,
|
|
||||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
|
||||||
For more information on this, and how to apply and follow the GNU GPL, see
|
|
||||||
<https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
The GNU General Public License does not permit incorporating your program
|
|
||||||
into proprietary programs. If your program is a subroutine library, you
|
|
||||||
may consider it more useful to permit linking proprietary applications with
|
|
||||||
the library. If this is what you want to do, use the GNU Lesser General
|
|
||||||
Public License instead of this License. But first, please read
|
|
||||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
||||||
|
|||||||
@@ -39,51 +39,190 @@ See [public-pool-ui](https://github.com/benjamin-wilson/public-pool-ui)
|
|||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
|
|
||||||
Install pm2 (https://pm2.keymetrics.io/)
|
The production Docker image runs database migrations and then starts PM2
|
||||||
|
automatically. For a manual host deployment, install pm2
|
||||||
|
(https://pm2.keymetrics.io/), run migrations, then start the app.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
$ npm run build
|
||||||
|
$ npm run migration:run:prod
|
||||||
$ pm2 start dist/main.js
|
$ pm2 start dist/main.js
|
||||||
```
|
```
|
||||||
|
|
||||||
|
When running the worker app in PM2 cluster mode, start the PM2 daemon with OS-level
|
||||||
|
connection scheduling. The environment variable must be present when the PM2 daemon
|
||||||
|
starts, not only in the worker configuration.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ NODE_CLUSTER_SCHED_POLICY=none pm2 start ecosystem.config.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Cluster-mode connection dropping requires Node.js `22.12.0` or newer.
|
||||||
|
|
||||||
|
`STRATUM_MAX_CONNECTIONS_PER_LISTENER` is enforced per worker and Stratum port.
|
||||||
|
Size it using the busiest port: `worker count * limit`. For example, 28 workers
|
||||||
|
with the default limit of `10000` allow up to `280000` connections on one port.
|
||||||
|
|
||||||
|
SV2 pool-assigned extranonces reserve the first of their four prefix bytes for
|
||||||
|
a process namespace and share the remaining 24-bit allocation space across
|
||||||
|
standard and extended channels. Under PM2, the namespace uses
|
||||||
|
`NODE_APP_INSTANCE` (falling back to `pm_id`) plus `restart_time` parity, which
|
||||||
|
keeps workers and overlapping zero-downtime reload generations disjoint without
|
||||||
|
changing the advertised prefix or total extranonce sizes. The effective value is
|
||||||
|
`SV2_EXTRANONCE_NAMESPACE_BASE + 2 * worker + (restart_time % 2)` and must be at
|
||||||
|
most `255` (up to 128 worker lanes at base zero). Startup fails if a PM2 worker
|
||||||
|
identity is missing or the namespace cannot fit. Independent containers or PM2
|
||||||
|
worker apps that share mining work must be assigned non-overlapping base ranges;
|
||||||
|
reserve two namespace values per configured Stratum worker.
|
||||||
|
|
||||||
|
### New-block notification path
|
||||||
|
|
||||||
|
The master keeps an authoritative Bitcoin Core `getblocktemplate` longpoll open;
|
||||||
|
rawblock ZMQ remains a watchdog and duplicate results are discarded. On a new tip,
|
||||||
|
the master publishes a compact subsidy-only SV1 job before serializing the full
|
||||||
|
transaction template. Workers fan that job out through one process-level socket
|
||||||
|
broadcaster, then issue the full fee-paying job as a second clean switch. Payout
|
||||||
|
snapshot creation and Postgres persistence run after the immediate solo publish.
|
||||||
|
|
||||||
|
SV2 solo channels pre-stage a native subsidy-only future job for the next height.
|
||||||
|
When the authoritative header arrives, the pool activates that job with only
|
||||||
|
`SetNewPrevHash`; the same-tip full job follows without a second prevhash switch.
|
||||||
|
Standard and extended candidates retain exact header/body reconstruction, and
|
||||||
|
late network-target candidates remain recoverable without crediting stale shares.
|
||||||
|
Pending SV2 canonical jobs are coalesced per client, while a new-tip activation
|
||||||
|
is moved ahead of any not-yet-started canonical work for that tip. The finite
|
||||||
|
defaults are 16 retained jobs per channel, four queued operations, 256 KiB of
|
||||||
|
outstanding socket writes, and a two-second write-callback deadline. A client is
|
||||||
|
disconnected if `SV2_MAX_RETAINED_JOBS_PER_CHANNEL`,
|
||||||
|
`SV2_MAX_QUEUED_JOB_OPERATIONS`, `SV2_MAX_SOCKET_BUFFER_BYTES`, or
|
||||||
|
`SV2_SOCKET_WRITE_TIMEOUT_MS` is exceeded; `SV2_JOB_RETENTION_MS` controls how
|
||||||
|
long stale network candidates remain reconstructable.
|
||||||
|
|
||||||
|
`SV1_SUBSIDY_BRIDGE_ENABLED=true` enables the solo bridge (the default). PPLNS is
|
||||||
|
never allowed to fall back to a miner-address coinbase; optional PPLNS bridge
|
||||||
|
support requires a precomputed subsidy-valued payout snapshot. Retained jobs are
|
||||||
|
kept for `STRATUM_JOB_RETENTION_MS` so a late network-target candidate can still
|
||||||
|
be reconstructed and submitted, while ordinary old-tip shares are rejected.
|
||||||
|
PPLNS seeds use a non-active snapshot status and are skipped if the next
|
||||||
|
authoritative `nBits` differs from their preparation basis.
|
||||||
|
|
||||||
|
The Redis protocol remains rolling-deploy compatible: new workers retain the
|
||||||
|
legacy mining-info reload path, while the master writes the historical latest
|
||||||
|
key as JSON only after a PPLNS-safe compatibility template is ready. Deploying
|
||||||
|
workers before the master is still the preferred rollout order. When any PPLNS
|
||||||
|
listener is configured and snapshot preparation fails, legacy workers are held
|
||||||
|
on their prior job instead of being woken with a miner-address fallback job.
|
||||||
|
|
||||||
|
Two structured log events expose the end-to-end timing:
|
||||||
|
|
||||||
|
- `block_notification_trace` reports Core, bridge, Redis, PPLNS, and persistence stages, separated by payout mode and job type.
|
||||||
|
- `stratum_job_fanout` reports client count, bytes, backpressure, and p50/p95/p99/last enqueue time, correlated by `eventId`.
|
||||||
|
|
||||||
## Docker
|
## Docker
|
||||||
|
|
||||||
Build container:
|
The default compose stack includes Public Pool, TimescaleDB, and Redis. TimescaleDB
|
||||||
|
stores normal Postgres tables plus immutable accepted-share rows in a hypertable.
|
||||||
|
Chart and hashrate APIs read from Timescale continuous aggregates plus recent raw
|
||||||
|
shares for realtime buckets. Redis is used only for process messaging and latest
|
||||||
|
mining-template replay.
|
||||||
|
|
||||||
|
Start the stack:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ docker build -t public-pool .
|
$ docker compose up --build -d
|
||||||
```
|
```
|
||||||
|
|
||||||
Run container:
|
Use an external TimescaleDB/Postgres server:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ docker container run --name public-pool --rm -p 3333:3333 -p 3334:3334 -p 8332:8332 -v .env:/public-pool/.env public-pool
|
$ DB_HOST=postgres.example.com \
|
||||||
|
DB_PORT=5432 \
|
||||||
|
DB_USERNAME=public_pool \
|
||||||
|
DB_PASSWORD='change-me' \
|
||||||
|
DB_DATABASE=public_pool \
|
||||||
|
DB_SSL=false \
|
||||||
|
docker compose -f docker-compose.external-db.yml up --build -d
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker Compose
|
The external database must be TimescaleDB-compatible and reachable from the
|
||||||
|
Public Pool container. The startup script waits for the remote `DB_HOST:DB_PORT`,
|
||||||
|
runs migrations, then starts PM2. Redis still runs locally in this compose file
|
||||||
|
unless `REDIS_URL` is pointed at an external Redis instance.
|
||||||
|
|
||||||
|
Set `DB_SSL=true` if the external database requires TLS. For private CA or
|
||||||
|
self-signed test deployments, `DB_SSL_REJECT_UNAUTHORIZED=false` disables
|
||||||
|
certificate verification; do not use that setting for normal internet-facing
|
||||||
|
production databases.
|
||||||
|
|
||||||
|
For a fresh external database, create the role/database first:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE USER public_pool WITH PASSWORD 'change-me';
|
||||||
|
CREATE DATABASE public_pool OWNER public_pool;
|
||||||
|
\c public_pool
|
||||||
|
CREATE EXTENSION IF NOT EXISTS timescaledb;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||||
|
```
|
||||||
|
|
||||||
|
If TimescaleDB is managed by another operator, make sure the `public_pool` role
|
||||||
|
can create tables, indexes, continuous aggregates, and Timescale policies in the
|
||||||
|
target database.
|
||||||
|
|
||||||
|
Run only the database migrations:
|
||||||
|
|
||||||
Build container:
|
|
||||||
```bash
|
```bash
|
||||||
$ docker compose build
|
$ docker compose run --rm public-pool npm run migration:run:prod
|
||||||
```
|
```
|
||||||
|
|
||||||
Run container:
|
Watch logs:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ docker compose up -d
|
$ docker compose logs --tail 100 -f public-pool
|
||||||
```
|
```
|
||||||
|
|
||||||
The docker-compose binds to `127.0.0.1` by default. To expose the Stratum services on your server change:
|
Back up TimescaleDB:
|
||||||
```diff
|
|
||||||
ports:
|
```bash
|
||||||
- - "127.0.0.1:3333:3333/tcp"
|
$ docker compose exec timescaledb pg_dump -U public_pool public_pool > public-pool.sql
|
||||||
- - "127.0.0.1:3334:3334/tcp"
|
|
||||||
+ - "3333"
|
|
||||||
+ - "3334"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Redis does not hold durable accounting data. Losing Redis requires workers to
|
||||||
|
replay the latest template from Redis after reconnect or fall back to the saved
|
||||||
|
RPC block template table.
|
||||||
|
|
||||||
**note**: To successfully connect to the bitcoin RPC you will need to add
|
**note**: To successfully connect to the bitcoin RPC you will need to add
|
||||||
|
|
||||||
```
|
```
|
||||||
rpcallowip=172.16.0.0/12
|
rpcallowip=172.16.0.0/12
|
||||||
|
zmqpubrawblock=tcp://0.0.0.0:3000
|
||||||
```
|
```
|
||||||
|
|
||||||
to your bitcoin.conf.
|
to your bitcoin.conf.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Baseline unit regression capture:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm run test:baseline
|
||||||
|
```
|
||||||
|
|
||||||
|
Unit tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
Integration tests against real TimescaleDB and Redis:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ docker compose -f docker-compose.test.yml up --build --abort-on-container-exit
|
||||||
|
```
|
||||||
|
|
||||||
|
With the full-setup regtest Bitcoin Core running, validate reconstructed empty
|
||||||
|
and full blocks through BIP23 proposal mode:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ RUN_BITCOIN_REGTEST_INTEGRATION=true \
|
||||||
|
npm run test:integration -- bitcoin-regtest-proposal
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
|
services:
|
||||||
|
redis:
|
||||||
|
image: redis:8-alpine
|
||||||
|
container_name: public-pool-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${REDIS_PORT:-6379}:6379/tcp"
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
public-pool:
|
||||||
|
container_name: public-pool
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
extra_hosts:
|
||||||
|
- "host.docker.internal:host-gateway"
|
||||||
|
ports:
|
||||||
|
- "0.0.0.0:3333:3333/tcp"
|
||||||
|
- "0.0.0.0:3332:3332/tcp"
|
||||||
|
- "0.0.0.0:3331:3331/tcp"
|
||||||
|
- "0.0.0.0:3330:3330/tcp"
|
||||||
|
- "0.0.0.0:4333:4333/tcp"
|
||||||
|
- "0.0.0.0:4332:4332/tcp"
|
||||||
|
- "0.0.0.0:4331:4331/tcp"
|
||||||
|
- "0.0.0.0:4330:4330/tcp"
|
||||||
|
- "0.0.0.0:13333:13333/tcp"
|
||||||
|
- "0.0.0.0:13332:13332/tcp"
|
||||||
|
- "0.0.0.0:13331:13331/tcp"
|
||||||
|
- "0.0.0.0:13330:13330/tcp"
|
||||||
|
- "0.0.0.0:14333:14333/tcp"
|
||||||
|
- "0.0.0.0:14332:14332/tcp"
|
||||||
|
- "0.0.0.0:14331:14331/tcp"
|
||||||
|
- "0.0.0.0:14330:14330/tcp"
|
||||||
|
- "0.0.0.0:23330:23330/tcp"
|
||||||
|
- "0.0.0.0:23331:23331/tcp"
|
||||||
|
- "0.0.0.0:23332:23332/tcp"
|
||||||
|
- "0.0.0.0:23333:23333/tcp"
|
||||||
|
- "0.0.0.0:23334:23334/tcp"
|
||||||
|
- "0.0.0.0:23335:23335/tcp"
|
||||||
|
- "0.0.0.0:23336:23336/tcp"
|
||||||
|
- "${API_BIND_HOST:-127.0.0.1}:${API_PUBLIC_PORT:-3334}:3334/tcp"
|
||||||
|
volumes:
|
||||||
|
- "./.env:/public-pool/.env:ro"
|
||||||
|
- "./secrets:/public-pool/secrets:ro"
|
||||||
|
environment:
|
||||||
|
NODE_ENV: production
|
||||||
|
DB_HOST: ${DB_HOST:?set DB_HOST to your external TimescaleDB/Postgres host}
|
||||||
|
DB_PORT: ${DB_PORT:-5432}
|
||||||
|
DB_USERNAME: ${DB_USERNAME:-public_pool}
|
||||||
|
DB_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD for your external database}
|
||||||
|
DB_DATABASE: ${DB_DATABASE:-public_pool}
|
||||||
|
DB_POOL_SIZE: ${DB_POOL_SIZE:-10}
|
||||||
|
DB_SSL: ${DB_SSL:-false}
|
||||||
|
DB_SSL_REJECT_UNAUTHORIZED: ${DB_SSL_REJECT_UNAUTHORIZED:-true}
|
||||||
|
REDIS_URL: ${REDIS_URL:-redis://redis:6379}
|
||||||
|
API_PORT: ${API_PORT:-3334}
|
||||||
|
API_SECURE: ${API_SECURE:-false}
|
||||||
|
API_WORKERS: ${API_WORKERS:-4}
|
||||||
|
PM2_ENABLED: ${PM2_ENABLED:-true}
|
||||||
|
STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
|
||||||
|
STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330}
|
||||||
|
PPLNS_STRATUM_PORTS: ${PPLNS_STRATUM_PORTS:-}
|
||||||
|
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
|
||||||
|
STRATUM_SECURE: ${STRATUM_SECURE:-true}
|
||||||
|
SECURE_STRATUM_PORTS: ${SECURE_STRATUM_PORTS:-4333,4332,4331,4330}
|
||||||
|
PPLNS_SECURE_STRATUM_PORTS: ${PPLNS_SECURE_STRATUM_PORTS:-}
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER: ${STRATUM_MAX_CONNECTIONS_PER_LISTENER:-10000}
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000}
|
||||||
|
STRATUM_BACKPRESSURE_ENABLED: "${STRATUM_BACKPRESSURE_ENABLED:-false}"
|
||||||
|
STRATUM_V2_PORTS: ${STRATUM_V2_PORTS:-}
|
||||||
|
PPLNS_STRATUM_V2_PORTS: ${PPLNS_STRATUM_V2_PORTS:-}
|
||||||
|
SV2_JDP_PORTS: ${SV2_JDP_PORTS:-}
|
||||||
|
PPLNS_SV2_JDP_PORTS: ${PPLNS_SV2_JDP_PORTS:-}
|
||||||
|
SV2_TDP_PORTS: ${SV2_TDP_PORTS:-}
|
||||||
|
PPLNS_SV2_TDP_PORTS: ${PPLNS_SV2_TDP_PORTS:-}
|
||||||
|
DATUM_PORTS: ${DATUM_PORTS:-}
|
||||||
|
PPLNS_DATUM_PORTS: ${PPLNS_DATUM_PORTS:-}
|
||||||
|
SHARE_ACCOUNTING_BATCH_SIZE: ${SHARE_ACCOUNTING_BATCH_SIZE:-500}
|
||||||
|
SHARE_ACCOUNTING_FLUSH_INTERVAL_MS: ${SHARE_ACCOUNTING_FLUSH_INTERVAL_MS:-25}
|
||||||
|
SHARE_ACCOUNTING_MAX_QUEUE_SIZE: ${SHARE_ACCOUNTING_MAX_QUEUE_SIZE:-50000}
|
||||||
|
SHARE_ACCOUNTING_SUMMARY_CACHE_MS: ${SHARE_ACCOUNTING_SUMMARY_CACHE_MS:-2500}
|
||||||
|
SHARE_ACCOUNTING_SUMMARY_CACHE_MAX: ${SHARE_ACCOUNTING_SUMMARY_CACHE_MAX:-10000}
|
||||||
|
SHARE_ROLLUP_ENABLED: ${SHARE_ROLLUP_ENABLED:-true}
|
||||||
|
SHARE_ROLLUP_INTERVAL_MS: ${SHARE_ROLLUP_INTERVAL_MS:-60000}
|
||||||
|
SHARE_ROLLUP_SAFETY_LAG_SECONDS: ${SHARE_ROLLUP_SAFETY_LAG_SECONDS:-30}
|
||||||
|
SHARE_ROLLUP_MAX_SHARES_PER_BATCH: ${SHARE_ROLLUP_MAX_SHARES_PER_BATCH:-5000000}
|
||||||
|
PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true}
|
||||||
|
PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns}
|
||||||
|
PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4}
|
||||||
|
PAYOUT_BOOTSTRAP_WINDOW: ${PAYOUT_BOOTSTRAP_WINDOW:-true}
|
||||||
|
PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-200}
|
||||||
|
PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546}
|
||||||
|
PAYOUT_FEE_ADDRESS: ${PAYOUT_FEE_ADDRESS:-}
|
||||||
|
PAYOUT_FEE_PERCENT: ${PAYOUT_FEE_PERCENT:-0}
|
||||||
|
PAYOUT_COINBASE_WEIGHT_BUDGET: ${PAYOUT_COINBASE_WEIGHT_BUDGET:-26000}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "node -e \"const http=require('http'); const https=require('https'); const secure=process.env.API_SECURE==='true'; const client=secure?https:http; const req=client.get({hostname:'127.0.0.1',port:process.env.API_PORT||3334,path:'/api/network',rejectUnauthorized:false},res=>process.exit(res.statusCode<500?0:1)); req.on('error',()=>process.exit(1)); req.setTimeout(5000,()=>{req.destroy(); process.exit(1);});\""]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
redis-data:
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
name: public-pool-test
|
||||||
|
|
||||||
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
|
services:
|
||||||
|
timescaledb:
|
||||||
|
image: timescale/timescaledb:latest-pg17
|
||||||
|
logging: *log-limits
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: public_pool_test
|
||||||
|
POSTGRES_USER: public_pool
|
||||||
|
POSTGRES_PASSWORD: public_pool
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- max_wal_size=16GB
|
||||||
|
- -c
|
||||||
|
- min_wal_size=2GB
|
||||||
|
- -c
|
||||||
|
- checkpoint_timeout=15min
|
||||||
|
- -c
|
||||||
|
- checkpoint_completion_target=0.9
|
||||||
|
- -c
|
||||||
|
- wal_compression=on
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:15432:5432/tcp"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U public_pool -d public_pool_test"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 20
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:8-alpine
|
||||||
|
logging: *log-limits
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:16379:6379/tcp"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 20
|
||||||
|
|
||||||
|
integration-tests:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.test
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
timescaledb:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
NODE_ENV: integration
|
||||||
|
DB_HOST: timescaledb
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USERNAME: public_pool
|
||||||
|
DB_PASSWORD: public_pool
|
||||||
|
DB_DATABASE: public_pool_test
|
||||||
|
REDIS_URL: redis://redis:6379
|
||||||
+120
-5
@@ -1,20 +1,135 @@
|
|||||||
version: '3.8'
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
|
timescaledb:
|
||||||
|
image: timescale/timescaledb:latest-pg17
|
||||||
|
container_name: public-pool-timescaledb
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${DB_DATABASE:-public_pool}
|
||||||
|
POSTGRES_USER: ${DB_USERNAME:-public_pool}
|
||||||
|
POSTGRES_PASSWORD: ${DB_PASSWORD:-public_pool}
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- max_wal_size=16GB
|
||||||
|
- -c
|
||||||
|
- min_wal_size=2GB
|
||||||
|
- -c
|
||||||
|
- checkpoint_timeout=15min
|
||||||
|
- -c
|
||||||
|
- checkpoint_completion_target=0.9
|
||||||
|
- -c
|
||||||
|
- wal_compression=on
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${DB_PORT:-5432}:5432/tcp"
|
||||||
|
volumes:
|
||||||
|
- timescaledb-data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-public_pool} -d ${DB_DATABASE:-public_pool}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:8-alpine
|
||||||
|
container_name: public-pool-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${REDIS_PORT:-6379}:6379/tcp"
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
public-pool:
|
public-pool:
|
||||||
container_name: public-pool
|
container_name: public-pool
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
timescaledb:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:${STRATUM_PORT}:${STRATUM_PORT}/tcp"
|
- "0.0.0.0:3333:3333/tcp"
|
||||||
- "127.0.0.1:${API_PORT}:${API_PORT}/tcp"
|
- "0.0.0.0:3332:3332/tcp"
|
||||||
|
- "0.0.0.0:3331:3331/tcp"
|
||||||
|
- "0.0.0.0:3330:3330/tcp"
|
||||||
|
- "0.0.0.0:4333:4333/tcp"
|
||||||
|
- "0.0.0.0:4332:4332/tcp"
|
||||||
|
- "0.0.0.0:4331:4331/tcp"
|
||||||
|
- "0.0.0.0:4330:4330/tcp"
|
||||||
|
- "0.0.0.0:13333:13333/tcp"
|
||||||
|
- "0.0.0.0:13332:13332/tcp"
|
||||||
|
- "0.0.0.0:13331:13331/tcp"
|
||||||
|
- "0.0.0.0:13330:13330/tcp"
|
||||||
|
- "0.0.0.0:14333:14333/tcp"
|
||||||
|
- "0.0.0.0:14332:14332/tcp"
|
||||||
|
- "0.0.0.0:14331:14331/tcp"
|
||||||
|
- "0.0.0.0:14330:14330/tcp"
|
||||||
|
- "0.0.0.0:23330:23330/tcp"
|
||||||
|
- "0.0.0.0:23331:23331/tcp"
|
||||||
|
- "0.0.0.0:23332:23332/tcp"
|
||||||
|
- "0.0.0.0:23333:23333/tcp"
|
||||||
|
- "0.0.0.0:23334:23334/tcp"
|
||||||
|
- "0.0.0.0:23335:23335/tcp"
|
||||||
|
- "0.0.0.0:23336:23336/tcp"
|
||||||
|
- "${API_BIND_HOST:-127.0.0.1}:${API_PUBLIC_PORT:-3334}:3334/tcp"
|
||||||
volumes:
|
volumes:
|
||||||
- "./${NETWORK}-DB:/public-pool/DB"
|
|
||||||
- "./.env:/public-pool/.env:ro"
|
- "./.env:/public-pool/.env:ro"
|
||||||
|
- "./secrets:/public-pool/secrets:ro"
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
NODE_ENV: production
|
||||||
|
DB_HOST: timescaledb
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USERNAME: ${DB_USERNAME:-public_pool}
|
||||||
|
DB_PASSWORD: ${DB_PASSWORD:-public_pool}
|
||||||
|
DB_DATABASE: ${DB_DATABASE:-public_pool}
|
||||||
|
REDIS_URL: redis://redis:6379
|
||||||
|
API_PORT: ${API_PORT:-3334}
|
||||||
|
API_SECURE: ${API_SECURE:-false}
|
||||||
|
API_WORKERS: ${API_WORKERS:-4}
|
||||||
|
PM2_ENABLED: ${PM2_ENABLED:-true}
|
||||||
|
STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
|
||||||
|
STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330}
|
||||||
|
PPLNS_STRATUM_PORTS: ${PPLNS_STRATUM_PORTS:-}
|
||||||
|
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
|
||||||
|
STRATUM_SECURE: ${STRATUM_SECURE:-true}
|
||||||
|
SECURE_STRATUM_PORTS: ${SECURE_STRATUM_PORTS:-4333,4332,4331,4330}
|
||||||
|
PPLNS_SECURE_STRATUM_PORTS: ${PPLNS_SECURE_STRATUM_PORTS:-}
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER: ${STRATUM_MAX_CONNECTIONS_PER_LISTENER:-10000}
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000}
|
||||||
|
STRATUM_V2_PORTS: ${STRATUM_V2_PORTS:-}
|
||||||
|
PPLNS_STRATUM_V2_PORTS: ${PPLNS_STRATUM_V2_PORTS:-}
|
||||||
|
SV2_JDP_PORTS: ${SV2_JDP_PORTS:-}
|
||||||
|
PPLNS_SV2_JDP_PORTS: ${PPLNS_SV2_JDP_PORTS:-}
|
||||||
|
SV2_TDP_PORTS: ${SV2_TDP_PORTS:-}
|
||||||
|
PPLNS_SV2_TDP_PORTS: ${PPLNS_SV2_TDP_PORTS:-}
|
||||||
|
DATUM_PORTS: ${DATUM_PORTS:-}
|
||||||
|
PPLNS_DATUM_PORTS: ${PPLNS_DATUM_PORTS:-}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "node -e \"const http=require('http'); const https=require('https'); const secure=process.env.API_SECURE==='true'; const client=secure?https:http; const req=client.get({hostname:'127.0.0.1',port:process.env.API_PORT||3334,path:'/api/network',rejectUnauthorized:false},res=>process.exit(res.statusCode<500?0:1)); req.on('error',()=>process.exit(1)); req.setTimeout(5000,()=>{req.destroy(); process.exit(1);});\""]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
timescaledb-data:
|
||||||
|
redis-data:
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
const dockerLogConfig = {
|
||||||
|
out_file: '/dev/stdout',
|
||||||
|
error_file: '/dev/stderr',
|
||||||
|
merge_logs: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
// API instance
|
||||||
|
{
|
||||||
|
...dockerLogConfig,
|
||||||
|
name: 'api',
|
||||||
|
script: './dist/main.js',
|
||||||
|
instances: parseInt(process.env.API_WORKERS || '4', 10),
|
||||||
|
exec_mode: 'cluster',
|
||||||
|
env: {
|
||||||
|
MASTER: 'false',
|
||||||
|
API_ONLY: 'true',
|
||||||
|
API_ENABLED: 'true',
|
||||||
|
NODE_CLUSTER_SCHED_POLICY: 'none',
|
||||||
|
},
|
||||||
|
time: true
|
||||||
|
},
|
||||||
|
// Master instance
|
||||||
|
{
|
||||||
|
...dockerLogConfig,
|
||||||
|
name: 'master',
|
||||||
|
script: './dist/main.js',
|
||||||
|
instances: 1,
|
||||||
|
exec_mode: 'fork',
|
||||||
|
env: {
|
||||||
|
MASTER: 'true',
|
||||||
|
API_ENABLED: 'false',
|
||||||
|
NODE_CLUSTER_SCHED_POLICY: 'none',
|
||||||
|
},
|
||||||
|
time: true
|
||||||
|
},
|
||||||
|
// Worker instances
|
||||||
|
{
|
||||||
|
...dockerLogConfig,
|
||||||
|
name: 'workers',
|
||||||
|
script: './dist/main.js',
|
||||||
|
instances: parseInt(process.env.STRATUM_WORKERS || '2', 10),
|
||||||
|
exec_mode: "cluster",
|
||||||
|
max_memory_restart: process.env.STRATUM_WORKER_MAX_MEMORY_RESTART || '4096M',
|
||||||
|
env: {
|
||||||
|
MASTER: 'false',
|
||||||
|
API_ENABLED: 'false',
|
||||||
|
NODE_CLUSTER_SCHED_POLICY: 'none',
|
||||||
|
},
|
||||||
|
time: true
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
+25
-1
@@ -1,6 +1,7 @@
|
|||||||
# Full Setup for public pool
|
# Full Setup for public pool
|
||||||
|
|
||||||
This setup provides a docker-compose setup consisting of Bitcoin Core Node and Public-Pool running in Mainnet or Testnet.
|
This setup provides Docker Compose stacks for Bitcoin Core, Public Pool,
|
||||||
|
TimescaleDB, and Redis on mainnet, testnet, and regtest.
|
||||||
|
|
||||||
It exposes following ports:
|
It exposes following ports:
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ It exposes following ports:
|
|||||||
- `8333/18333` Bitcoin peering on `0.0.0.0`
|
- `8333/18333` Bitcoin peering on `0.0.0.0`
|
||||||
- `3333/13333` Public-Pool Stratum port on `0.0.0.0`
|
- `3333/13333` Public-Pool Stratum port on `0.0.0.0`
|
||||||
- `3334/13334` Public-Pool API port on `localhost`
|
- `3334/13334` Public-Pool API port on `localhost`
|
||||||
|
- TimescaleDB and Redis only on the internal compose network
|
||||||
|
|
||||||
The docker-compose setups for Mainnet and Testnet can be run in parallel without any problems.
|
The docker-compose setups for Mainnet and Testnet can be run in parallel without any problems.
|
||||||
|
|
||||||
@@ -42,6 +44,9 @@ There are 4 config files for Mainnet and Testnet
|
|||||||
- `bitcoin-testnet.conf`
|
- `bitcoin-testnet.conf`
|
||||||
|
|
||||||
**note: pruning (`prune=550`) is enabled by default in the config**
|
**note: pruning (`prune=550`) is enabled by default in the config**
|
||||||
|
**note: Bitcoin ZMQ raw block publishing is enabled on the internal compose
|
||||||
|
network so the Public Pool master can refresh templates immediately after new
|
||||||
|
blocks.**
|
||||||
# Running the setup
|
# Running the setup
|
||||||
|
|
||||||
To start the setup in foreground mode:
|
To start the setup in foreground mode:
|
||||||
@@ -65,6 +70,25 @@ To stop the setup use:
|
|||||||
docker compose -f docker-compose-mainnet.yml down
|
docker compose -f docker-compose-mainnet.yml down
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Database and Redis data are stored under `full-setup/data/<network>/`. To remove
|
||||||
|
all runtime data, stop the stack and delete the relevant `bitcoin`,
|
||||||
|
`timescaledb`, and `redis` directories.
|
||||||
|
|
||||||
|
# Migrations and backups
|
||||||
|
|
||||||
|
The Public Pool container waits for TimescaleDB and Redis, runs migrations, and
|
||||||
|
then starts PM2. To run migrations manually:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose-mainnet.yml run --rm public-pool npm run migration:run:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
To back up mainnet accounting data:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose-mainnet.yml exec timescaledb pg_dump -U public_pool public_pool_mainnet > public-pool-mainnet.sql
|
||||||
|
```
|
||||||
|
|
||||||
# Regtest
|
# Regtest
|
||||||
|
|
||||||
After running the `regtest` setup a couple of blocks need to be generated:
|
After running the `regtest` setup a couple of blocks need to be generated:
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ rpcuser=bitcoin
|
|||||||
# enable server
|
# enable server
|
||||||
server=1
|
server=1
|
||||||
|
|
||||||
|
# notify pool master about new blocks
|
||||||
|
zmqpubrawblock=tcp://0.0.0.0:3000
|
||||||
|
|
||||||
[main]
|
[main]
|
||||||
[test]
|
[test]
|
||||||
rpcbind=0.0.0.0
|
rpcbind=0.0.0.0
|
||||||
|
|||||||
@@ -20,3 +20,6 @@ rpcuser=bitcoin
|
|||||||
|
|
||||||
# set pruning
|
# set pruning
|
||||||
prune=550
|
prune=550
|
||||||
|
|
||||||
|
# notify pool master about new blocks
|
||||||
|
zmqpubrawblock=tcp://0.0.0.0:3000
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ rpcuser=bitcoin
|
|||||||
# enable server
|
# enable server
|
||||||
server=1
|
server=1
|
||||||
|
|
||||||
|
# notify pool master about new blocks
|
||||||
|
zmqpubrawblock=tcp://0.0.0.0:3000
|
||||||
|
|
||||||
[main]
|
[main]
|
||||||
[test]
|
[test]
|
||||||
rpcbind=0.0.0.0
|
rpcbind=0.0.0.0
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
version: '3.8'
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
bitcoin:
|
bitcoin:
|
||||||
@@ -8,6 +12,7 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
networks:
|
networks:
|
||||||
- bitcoin
|
- bitcoin
|
||||||
ports:
|
ports:
|
||||||
@@ -20,6 +25,52 @@ services:
|
|||||||
- "./data/mainnet/bitcoin:/app/data"
|
- "./data/mainnet/bitcoin:/app/data"
|
||||||
- "./bitcoin-mainnet.conf:/app/data/bitcoin.conf:ro"
|
- "./bitcoin-mainnet.conf:/app/data/bitcoin.conf:ro"
|
||||||
|
|
||||||
|
timescaledb:
|
||||||
|
image: timescale/timescaledb:latest-pg17
|
||||||
|
container_name: public-pool-mainnet-timescaledb
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: public_pool_mainnet
|
||||||
|
POSTGRES_USER: public_pool
|
||||||
|
POSTGRES_PASSWORD: public_pool
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- max_wal_size=16GB
|
||||||
|
- -c
|
||||||
|
- min_wal_size=2GB
|
||||||
|
- -c
|
||||||
|
- checkpoint_timeout=15min
|
||||||
|
- -c
|
||||||
|
- checkpoint_completion_target=0.9
|
||||||
|
- -c
|
||||||
|
- wal_compression=on
|
||||||
|
volumes:
|
||||||
|
- "./data/mainnet/timescaledb:/var/lib/postgresql/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U public_pool -d public_pool_mainnet"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:8-alpine
|
||||||
|
container_name: public-pool-mainnet-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin
|
||||||
|
volumes:
|
||||||
|
- "./data/mainnet/redis:/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
public-pool:
|
public-pool:
|
||||||
container_name: public-pool
|
container_name: public-pool
|
||||||
build:
|
build:
|
||||||
@@ -27,16 +78,55 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
timescaledb:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
networks:
|
networks:
|
||||||
- bitcoin
|
- bitcoin
|
||||||
ports:
|
ports:
|
||||||
- "0.0.0.0:3333:3333/tcp"
|
- "0.0.0.0:3333:3333/tcp"
|
||||||
- "127.0.0.1:3334:3334/tcp"
|
- "0.0.0.0:3332:3332/tcp"
|
||||||
|
- "0.0.0.0:3331:3331/tcp"
|
||||||
|
- "0.0.0.0:3330:3330/tcp"
|
||||||
|
- "0.0.0.0:4333:4333/tcp"
|
||||||
|
- "0.0.0.0:4332:4332/tcp"
|
||||||
|
- "0.0.0.0:4331:4331/tcp"
|
||||||
|
- "0.0.0.0:4330:4330/tcp"
|
||||||
|
- "${API_BIND_HOST:-127.0.0.1}:${API_PUBLIC_PORT:-3334}:3334/tcp"
|
||||||
volumes:
|
volumes:
|
||||||
- "./data/mainnet/public-pool:/public-pool/DB"
|
|
||||||
- "./public-pool-mainnet.env:/public-pool/.env:ro"
|
- "./public-pool-mainnet.env:/public-pool/.env:ro"
|
||||||
|
- "../secrets:/public-pool/secrets:ro"
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
NODE_ENV: production
|
||||||
|
DB_HOST: timescaledb
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USERNAME: public_pool
|
||||||
|
DB_PASSWORD: public_pool
|
||||||
|
DB_DATABASE: public_pool_mainnet
|
||||||
|
REDIS_URL: redis://redis:6379
|
||||||
|
API_WORKERS: ${API_WORKERS:-4}
|
||||||
|
PM2_ENABLED: "true"
|
||||||
|
STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
|
||||||
|
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
|
||||||
|
SHARE_ROLLUP_ENABLED: ${SHARE_ROLLUP_ENABLED:-true}
|
||||||
|
SHARE_ROLLUP_INTERVAL_MS: ${SHARE_ROLLUP_INTERVAL_MS:-60000}
|
||||||
|
SHARE_ROLLUP_SAFETY_LAG_SECONDS: ${SHARE_ROLLUP_SAFETY_LAG_SECONDS:-30}
|
||||||
|
SHARE_ROLLUP_MAX_SHARES_PER_BATCH: ${SHARE_ROLLUP_MAX_SHARES_PER_BATCH:-5000000}
|
||||||
|
PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true}
|
||||||
|
PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns}
|
||||||
|
PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4}
|
||||||
|
PAYOUT_BOOTSTRAP_WINDOW: ${PAYOUT_BOOTSTRAP_WINDOW:-true}
|
||||||
|
PAYOUT_COINBASE_MODE: ${PAYOUT_COINBASE_MODE:-solo}
|
||||||
|
PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-200}
|
||||||
|
PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546}
|
||||||
|
PAYOUT_FEE_ADDRESS: ${PAYOUT_FEE_ADDRESS:-}
|
||||||
|
PAYOUT_FEE_PERCENT: ${PAYOUT_FEE_PERCENT:-0}
|
||||||
|
PAYOUT_COINBASE_WEIGHT_BUDGET: ${PAYOUT_COINBASE_WEIGHT_BUDGET:-26000}
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
bitcoin:
|
bitcoin:
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
version: '3.8'
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
bitcoin-regtest:
|
bitcoin-regtest:
|
||||||
@@ -8,6 +12,7 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
networks:
|
networks:
|
||||||
- bitcoin-regtest
|
- bitcoin-regtest
|
||||||
ports:
|
ports:
|
||||||
@@ -22,6 +27,52 @@ services:
|
|||||||
- "./data/regtest/bitcoin:/app/data"
|
- "./data/regtest/bitcoin:/app/data"
|
||||||
- "./bitcoin-regtest.conf:/app/data/bitcoin.conf:ro"
|
- "./bitcoin-regtest.conf:/app/data/bitcoin.conf:ro"
|
||||||
|
|
||||||
|
timescaledb-regtest:
|
||||||
|
image: timescale/timescaledb:latest-pg17
|
||||||
|
container_name: public-pool-regtest-timescaledb
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin-regtest
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: public_pool_regtest
|
||||||
|
POSTGRES_USER: public_pool
|
||||||
|
POSTGRES_PASSWORD: public_pool
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- max_wal_size=16GB
|
||||||
|
- -c
|
||||||
|
- min_wal_size=2GB
|
||||||
|
- -c
|
||||||
|
- checkpoint_timeout=15min
|
||||||
|
- -c
|
||||||
|
- checkpoint_completion_target=0.9
|
||||||
|
- -c
|
||||||
|
- wal_compression=on
|
||||||
|
volumes:
|
||||||
|
- "./data/regtest/timescaledb:/var/lib/postgresql/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U public_pool -d public_pool_regtest"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
redis-regtest:
|
||||||
|
image: redis:8-alpine
|
||||||
|
container_name: public-pool-regtest-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin-regtest
|
||||||
|
volumes:
|
||||||
|
- "./data/regtest/redis:/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
public-pool-regtest:
|
public-pool-regtest:
|
||||||
container_name: public-pool-regtest
|
container_name: public-pool-regtest
|
||||||
build:
|
build:
|
||||||
@@ -29,16 +80,36 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
timescaledb-regtest:
|
||||||
|
condition: service_healthy
|
||||||
|
redis-regtest:
|
||||||
|
condition: service_healthy
|
||||||
networks:
|
networks:
|
||||||
- bitcoin-regtest
|
- bitcoin-regtest
|
||||||
ports:
|
ports:
|
||||||
- "0.0.0.0:23333:23333/tcp"
|
- "0.0.0.0:23333:23333/tcp"
|
||||||
|
- "0.0.0.0:23332:23332/tcp"
|
||||||
|
- "0.0.0.0:23331:23331/tcp"
|
||||||
|
- "0.0.0.0:23330:23330/tcp"
|
||||||
- "127.0.0.1:23334:23334/tcp"
|
- "127.0.0.1:23334:23334/tcp"
|
||||||
volumes:
|
volumes:
|
||||||
- "./data/regtest/public-pool:/public-pool/DB"
|
|
||||||
- "./public-pool-regtest.env:/public-pool/.env:ro"
|
- "./public-pool-regtest.env:/public-pool/.env:ro"
|
||||||
|
- "../secrets:/public-pool/secrets:ro"
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
NODE_ENV: production
|
||||||
|
DB_HOST: timescaledb-regtest
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USERNAME: public_pool
|
||||||
|
DB_PASSWORD: public_pool
|
||||||
|
DB_DATABASE: public_pool_regtest
|
||||||
|
REDIS_URL: redis://redis-regtest:6379
|
||||||
|
PM2_ENABLED: "true"
|
||||||
|
STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
|
||||||
|
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
bitcoin-regtest:
|
bitcoin-regtest:
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
version: '3.8'
|
x-log-limits: &log-limits
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: ${DOCKER_LOG_MAX_SIZE:-100m}
|
||||||
|
max-file: "${DOCKER_LOG_MAX_FILES:-5}"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
bitcoin-testnet:
|
bitcoin-testnet:
|
||||||
@@ -8,6 +12,7 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
networks:
|
networks:
|
||||||
- bitcoin-testnet
|
- bitcoin-testnet
|
||||||
ports:
|
ports:
|
||||||
@@ -21,6 +26,52 @@ services:
|
|||||||
- "./data/testnet/bitcoin:/app/data"
|
- "./data/testnet/bitcoin:/app/data"
|
||||||
- "./bitcoin-testnet.conf:/app/data/bitcoin.conf:ro"
|
- "./bitcoin-testnet.conf:/app/data/bitcoin.conf:ro"
|
||||||
|
|
||||||
|
timescaledb-testnet:
|
||||||
|
image: timescale/timescaledb:latest-pg17
|
||||||
|
container_name: public-pool-testnet-timescaledb
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin-testnet
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: public_pool_testnet
|
||||||
|
POSTGRES_USER: public_pool
|
||||||
|
POSTGRES_PASSWORD: public_pool
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- max_wal_size=16GB
|
||||||
|
- -c
|
||||||
|
- min_wal_size=2GB
|
||||||
|
- -c
|
||||||
|
- checkpoint_timeout=15min
|
||||||
|
- -c
|
||||||
|
- checkpoint_completion_target=0.9
|
||||||
|
- -c
|
||||||
|
- wal_compression=on
|
||||||
|
volumes:
|
||||||
|
- "./data/testnet/timescaledb:/var/lib/postgresql/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U public_pool -d public_pool_testnet"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
redis-testnet:
|
||||||
|
image: redis:8-alpine
|
||||||
|
container_name: public-pool-testnet-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *log-limits
|
||||||
|
networks:
|
||||||
|
- bitcoin-testnet
|
||||||
|
volumes:
|
||||||
|
- "./data/testnet/redis:/data"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
public-pool-testnet:
|
public-pool-testnet:
|
||||||
container_name: public-pool-testnet
|
container_name: public-pool-testnet
|
||||||
build:
|
build:
|
||||||
@@ -28,16 +79,36 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
stop_grace_period: 30s
|
stop_grace_period: 30s
|
||||||
|
logging: *log-limits
|
||||||
|
depends_on:
|
||||||
|
timescaledb-testnet:
|
||||||
|
condition: service_healthy
|
||||||
|
redis-testnet:
|
||||||
|
condition: service_healthy
|
||||||
networks:
|
networks:
|
||||||
- bitcoin-testnet
|
- bitcoin-testnet
|
||||||
ports:
|
ports:
|
||||||
- "0.0.0.0:13333:13333/tcp"
|
- "0.0.0.0:13333:13333/tcp"
|
||||||
|
- "0.0.0.0:13332:13332/tcp"
|
||||||
|
- "0.0.0.0:13331:13331/tcp"
|
||||||
|
- "0.0.0.0:13330:13330/tcp"
|
||||||
- "127.0.0.1:13334:13334/tcp"
|
- "127.0.0.1:13334:13334/tcp"
|
||||||
volumes:
|
volumes:
|
||||||
- "./data/testnet/public-pool:/public-pool/DB"
|
|
||||||
- "./public-pool-testnet.env:/public-pool/.env:ro"
|
- "./public-pool-testnet.env:/public-pool/.env:ro"
|
||||||
|
- "../secrets:/public-pool/secrets:ro"
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
NODE_ENV: production
|
||||||
|
DB_HOST: timescaledb-testnet
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USERNAME: public_pool
|
||||||
|
DB_PASSWORD: public_pool
|
||||||
|
DB_DATABASE: public_pool_testnet
|
||||||
|
REDIS_URL: redis://redis-testnet:6379
|
||||||
|
PM2_ENABLED: "true"
|
||||||
|
STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
|
||||||
|
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
|
||||||
|
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
|
||||||
|
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
bitcoin-testnet:
|
bitcoin-testnet:
|
||||||
|
|||||||
@@ -4,12 +4,24 @@ BITCOIN_RPC_PASSWORD=bitcoin
|
|||||||
BITCOIN_RPC_PORT=8332
|
BITCOIN_RPC_PORT=8332
|
||||||
BITCOIN_RPC_TIMEOUT=10000
|
BITCOIN_RPC_TIMEOUT=10000
|
||||||
|
|
||||||
# Enable in bitcoin.conf with
|
BITCOIN_ZMQ_HOST=tcp://bitcoin:3000
|
||||||
# zmqpubrawblock=tcp://*:3000
|
|
||||||
# BITCOIN_ZMQ_HOST="tcp://192.168.1.100:3000"
|
|
||||||
|
|
||||||
API_PORT=3334
|
API_PORT=3334
|
||||||
STRATUM_PORT=3333
|
STRATUM_PORTS=3333,3332,3331,3330
|
||||||
|
PPLNS_STRATUM_PORTS=
|
||||||
|
STRATUM_V2_PORTS=
|
||||||
|
PPLNS_STRATUM_V2_PORTS=
|
||||||
|
DATUM_PORTS=
|
||||||
|
PPLNS_DATUM_PORTS=
|
||||||
|
SV2_JDP_PORTS=
|
||||||
|
PPLNS_SV2_JDP_PORTS=
|
||||||
|
SV2_TDP_PORTS=
|
||||||
|
PPLNS_SV2_TDP_PORTS=
|
||||||
|
STRATUM_SECURE=true
|
||||||
|
SECURE_STRATUM_PORTS=4333,4332,4331,4330
|
||||||
|
PPLNS_SECURE_STRATUM_PORTS=
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
|
||||||
|
|
||||||
#optional telegram bot
|
#optional telegram bot
|
||||||
#TELEGRAM_BOT_TOKEN=
|
#TELEGRAM_BOT_TOKEN=
|
||||||
@@ -26,9 +38,10 @@ NETWORK=mainnet
|
|||||||
|
|
||||||
API_SECURE=false
|
API_SECURE=false
|
||||||
|
|
||||||
ENABLE_SOLO=true
|
DB_HOST=timescaledb
|
||||||
ENABLE_PROXY=false
|
DB_PORT=5432
|
||||||
|
DB_USERNAME=public_pool
|
||||||
BRAIINS_ACCESS_TOKEN=
|
DB_PASSWORD=public_pool
|
||||||
|
DB_DATABASE=public_pool_mainnet
|
||||||
PROXY_PORT=3333
|
REDIS_URL=redis://redis:6379
|
||||||
|
PRODUCTION=true
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ BITCOIN_RPC_PASSWORD=bitcoin
|
|||||||
BITCOIN_RPC_PORT=28332
|
BITCOIN_RPC_PORT=28332
|
||||||
BITCOIN_RPC_TIMEOUT=10000
|
BITCOIN_RPC_TIMEOUT=10000
|
||||||
|
|
||||||
# Enable in bitcoin.conf with
|
BITCOIN_ZMQ_HOST=tcp://bitcoin-regtest:3000
|
||||||
# zmqpubrawblock=tcp://*:3000
|
|
||||||
# BITCOIN_ZMQ_HOST="tcp://192.168.1.100:3000"
|
|
||||||
|
|
||||||
API_PORT=23334
|
API_PORT=23334
|
||||||
STRATUM_PORT=23333
|
STRATUM_PORTS=23333,23332,23331,23330
|
||||||
|
STRATUM_SECURE=false
|
||||||
|
SECURE_STRATUM_PORTS=
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
|
||||||
|
|
||||||
#optional telegram bot
|
#optional telegram bot
|
||||||
#TELEGRAM_BOT_TOKEN=
|
#TELEGRAM_BOT_TOKEN=
|
||||||
@@ -26,9 +28,10 @@ NETWORK=regtest
|
|||||||
|
|
||||||
API_SECURE=false
|
API_SECURE=false
|
||||||
|
|
||||||
ENABLE_SOLO=true
|
DB_HOST=timescaledb-regtest
|
||||||
ENABLE_PROXY=false
|
DB_PORT=5432
|
||||||
|
DB_USERNAME=public_pool
|
||||||
BRAIINS_ACCESS_TOKEN=
|
DB_PASSWORD=public_pool
|
||||||
|
DB_DATABASE=public_pool_regtest
|
||||||
PROXY_PORT=3333
|
REDIS_URL=redis://redis-regtest:6379
|
||||||
|
PRODUCTION=true
|
||||||
|
|||||||
@@ -4,12 +4,24 @@ BITCOIN_RPC_PASSWORD=bitcoin
|
|||||||
BITCOIN_RPC_PORT=18332
|
BITCOIN_RPC_PORT=18332
|
||||||
BITCOIN_RPC_TIMEOUT=10000
|
BITCOIN_RPC_TIMEOUT=10000
|
||||||
|
|
||||||
# Enable in bitcoin.conf with
|
BITCOIN_ZMQ_HOST=tcp://bitcoin-testnet:3000
|
||||||
# zmqpubrawblock=tcp://*:3000
|
|
||||||
# BITCOIN_ZMQ_HOST="tcp://192.168.1.100:3000"
|
|
||||||
|
|
||||||
API_PORT=13334
|
API_PORT=13334
|
||||||
STRATUM_PORT=13333
|
STRATUM_PORTS=13333,13332,13331,13330
|
||||||
|
PPLNS_STRATUM_PORTS=
|
||||||
|
STRATUM_V2_PORTS=
|
||||||
|
PPLNS_STRATUM_V2_PORTS=
|
||||||
|
DATUM_PORTS=
|
||||||
|
PPLNS_DATUM_PORTS=
|
||||||
|
SV2_JDP_PORTS=
|
||||||
|
PPLNS_SV2_JDP_PORTS=
|
||||||
|
SV2_TDP_PORTS=
|
||||||
|
PPLNS_SV2_TDP_PORTS=
|
||||||
|
STRATUM_SECURE=false
|
||||||
|
SECURE_STRATUM_PORTS=
|
||||||
|
PPLNS_SECURE_STRATUM_PORTS=
|
||||||
|
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
|
||||||
|
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
|
||||||
|
|
||||||
#optional telegram bot
|
#optional telegram bot
|
||||||
#TELEGRAM_BOT_TOKEN=
|
#TELEGRAM_BOT_TOKEN=
|
||||||
@@ -26,9 +38,10 @@ NETWORK=testnet
|
|||||||
|
|
||||||
API_SECURE=false
|
API_SECURE=false
|
||||||
|
|
||||||
ENABLE_SOLO=true
|
DB_HOST=timescaledb-testnet
|
||||||
ENABLE_PROXY=false
|
DB_PORT=5432
|
||||||
|
DB_USERNAME=public_pool
|
||||||
BRAIINS_ACCESS_TOKEN=
|
DB_PASSWORD=public_pool
|
||||||
|
DB_DATABASE=public_pool_testnet
|
||||||
PROXY_PORT=3333
|
REDIS_URL=redis://redis-testnet:6379
|
||||||
|
PRODUCTION=true
|
||||||
|
|||||||
Generated
+9600
-7869
File diff suppressed because it is too large
Load Diff
+68
-43
@@ -4,75 +4,90 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"author": "",
|
"author": "",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "UNLICENSED",
|
"license": "AGPL-3.0-only",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.12.0"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"postinstall": "patch-package",
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"start:prod": "node dist/main",
|
"start:prod": "node dist/main",
|
||||||
|
"start:docker": "node dist/scripts/start-docker.js",
|
||||||
|
"migration:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d src/data-source.ts migration:run",
|
||||||
|
"migration:run:prod": "node dist/scripts/run-migrations.js",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
|
"test:baseline": "jest --runInBand --json --outputFile=.baseline-jest-results.json",
|
||||||
|
"test:integration": "jest --config ./test/jest-integration.json --runInBand",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"test:cov": "jest --coverage",
|
"test:cov": "jest --coverage",
|
||||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nestjs/axios": "^3.0.0",
|
"@nestjs/axios": "^4.0.1",
|
||||||
"@nestjs/cache-manager": "^2.0.1",
|
"@nestjs/cache-manager": "^3.1.2",
|
||||||
"@nestjs/common": "^9.0.0",
|
"@nestjs/common": "^11.1.19",
|
||||||
"@nestjs/config": "^2.3.2",
|
"@nestjs/config": "^4.0.4",
|
||||||
"@nestjs/core": "^9.0.0",
|
"@nestjs/core": "^11.1.19",
|
||||||
"@nestjs/platform-fastify": "^9.4.2",
|
"@nestjs/platform-fastify": "^11.1.19",
|
||||||
"@nestjs/schedule": "^3.0.1",
|
"@nestjs/schedule": "^6.1.3",
|
||||||
"@nestjs/typeorm": "^10.0.0",
|
"@nestjs/typeorm": "^11.0.1",
|
||||||
"axios": "^1.4.0",
|
"@scure/btc-signer": "^2.2.0",
|
||||||
"big.js": "^6.2.1",
|
"axios": "^1.16.0",
|
||||||
"bitcoin-address-validation": "^2.2.1",
|
"bitcoin-address-validation": "^2.2.3",
|
||||||
"bitcoinjs-lib": "^6.1.3",
|
"bitcoinjs-lib": "^6.1.7",
|
||||||
"bitcoinjs-message": "^2.2.0",
|
|
||||||
"bs58": "^5.0.0",
|
"bs58": "^5.0.0",
|
||||||
"cache-manager": "^5.2.3",
|
"cache-manager": "^7.2.8",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.0",
|
"class-validator": "^0.14.4",
|
||||||
"discord.js": "^14.11.0",
|
"discord.js": "^14.26.4",
|
||||||
|
"dotenv": "^16.6.1",
|
||||||
|
"libsodium-wrappers-sumo": "^0.8.4",
|
||||||
"merkle-lib": "^2.0.10",
|
"merkle-lib": "^2.0.10",
|
||||||
"node-telegram-bot-api": "^0.61.0",
|
"pg": "^8.20.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"pm2": "^7.0.1",
|
||||||
"rpc-bitcoin": "^2.0.0",
|
"redis": "^5.12.1",
|
||||||
"rxjs": "^7.2.0",
|
"reflect-metadata": "^0.2.2",
|
||||||
"sqlite3": "^5.1.6",
|
"rxjs": "^7.8.2",
|
||||||
"tiny-secp256k1": "^2.2.3",
|
"tiny-secp256k1": "^2.2.4",
|
||||||
"typeorm": "^0.3.17",
|
"typeorm": "^0.3.28",
|
||||||
"zeromq": "6.0.0-beta.19"
|
"zeromq": "6.0.0-beta.19"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^9.0.0",
|
"@nestjs/cli": "^11.0.21",
|
||||||
"@nestjs/schematics": "^9.0.0",
|
"@nestjs/schematics": "^11.1.0",
|
||||||
"@nestjs/testing": "^9.0.0",
|
"@nestjs/testing": "^11.1.19",
|
||||||
"@types/big.js": "^6.1.6",
|
|
||||||
"@types/cron": "^2.0.1",
|
"@types/cron": "^2.0.1",
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.25",
|
||||||
"@types/jest": "29.5.1",
|
"@types/jest": "^29.5.14",
|
||||||
"@types/node": "^18.16.12",
|
"@types/libsodium-wrappers-sumo": "^0.7.8",
|
||||||
"@types/node-telegram-bot-api": "^0.61.6",
|
"@types/node": "^18.19.130",
|
||||||
"@types/supertest": "^2.0.11",
|
"@types/supertest": "^7.2.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||||
"@typescript-eslint/parser": "^5.0.0",
|
"@typescript-eslint/parser": "^5.0.0",
|
||||||
"eslint": "^8.0.1",
|
"eslint": "^8.0.1",
|
||||||
"eslint-config-prettier": "^8.3.0",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-prettier": "^4.0.0",
|
"eslint-plugin-prettier": "^5.5.5",
|
||||||
"jest": "29.5.0",
|
"jest": "^29.7.0",
|
||||||
"prettier": "^2.3.2",
|
"patch-package": "^8.0.1",
|
||||||
|
"prettier": "^3.8.3",
|
||||||
"source-map-support": "^0.5.20",
|
"source-map-support": "^0.5.20",
|
||||||
"supertest": "^6.1.3",
|
"supertest": "^7.2.2",
|
||||||
"ts-jest": "29.1.0",
|
"ts-jest": "^29.4.9",
|
||||||
"ts-loader": "^9.2.3",
|
"ts-loader": "^9.5.7",
|
||||||
"ts-node": "^10.0.0",
|
"ts-node": "^10.9.2",
|
||||||
"tsconfig-paths": "4.2.0",
|
"tsconfig-paths": "4.2.0",
|
||||||
"typescript": "^5.0.0"
|
"typescript": "^5.9.3"
|
||||||
|
},
|
||||||
|
"overrides": {
|
||||||
|
"@fastify/middie": "^9.3.2",
|
||||||
|
"fastify": "^5.8.5",
|
||||||
|
"path-to-regexp": "^8.4.2"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"moduleFileExtensions": [
|
"moduleFileExtensions": [
|
||||||
@@ -83,8 +98,18 @@
|
|||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"testRegex": ".*\\.spec\\.ts$",
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+\\.(t|j)s$": [
|
||||||
|
"ts-jest",
|
||||||
|
{
|
||||||
|
"tsconfig": {
|
||||||
|
"allowJs": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
|
"transformIgnorePatterns": [
|
||||||
|
"node_modules/(?!(@scure|@noble|micro-packed))"
|
||||||
|
],
|
||||||
"collectCoverageFrom": [
|
"collectCoverageFrom": [
|
||||||
"**/*.(t|j)s"
|
"**/*.(t|j)s"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class AcceptedShareHighScores1781309000000 implements MigrationInterface {
|
||||||
|
public name = 'AcceptedShareHighScores1781309000000';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "accepted_share_high_score" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"scope" varchar(16) NOT NULL,
|
||||||
|
"payoutMode" varchar(16) NOT NULL DEFAULT 'all',
|
||||||
|
"bucketDate" date NOT NULL DEFAULT DATE '1970-01-01',
|
||||||
|
"submissionDifficulty" numeric NOT NULL DEFAULT 0,
|
||||||
|
"acceptedAt" timestamptz,
|
||||||
|
"bucket" timestamptz,
|
||||||
|
"blockHeight" bigint,
|
||||||
|
"address" varchar(128),
|
||||||
|
"clientName" varchar(256),
|
||||||
|
"protocol" varchar(16),
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT NOW(),
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "UQ_accepted_share_high_score_scope"
|
||||||
|
ON "accepted_share_high_score" ("scope", "payoutMode", "bucketDate")
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_high_score_best"
|
||||||
|
ON "accepted_share_high_score" ("payoutMode", "submissionDifficulty" DESC, "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "accepted_share_high_score"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class AcceptedShareIndex1780862400000 implements MigrationInterface {
|
||||||
|
public name = 'AcceptedShareIndex1780862400000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`CREATE SEQUENCE IF NOT EXISTS "accepted_share_index_seq"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" ADD COLUMN IF NOT EXISTS "shareIndex" bigint`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT setval(
|
||||||
|
'accepted_share_index_seq',
|
||||||
|
GREATEST(
|
||||||
|
(SELECT COUNT(*) FROM "accepted_share_entity") + 1,
|
||||||
|
(SELECT COALESCE(MAX("shareIndex"), 0) + 1 FROM "accepted_share_entity"),
|
||||||
|
1
|
||||||
|
),
|
||||||
|
false
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity"
|
||||||
|
ALTER COLUMN "shareIndex" SET DEFAULT nextval('accepted_share_index_seq')
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_order"
|
||||||
|
ON "accepted_share_entity" ("shareIndex" DESC)
|
||||||
|
WHERE "shareIndex" IS NOT NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_order"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity"
|
||||||
|
ALTER COLUMN "shareIndex" DROP DEFAULT
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" DROP COLUMN IF EXISTS "shareIndex"`);
|
||||||
|
await queryRunner.query(`DROP SEQUENCE IF EXISTS "accepted_share_index_seq"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class AcceptedShareProtocolMetadata1781130600000 implements MigrationInterface {
|
||||||
|
public name = 'AcceptedShareProtocolMetadata1781130600000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await this.decompressAcceptedShareChunks(queryRunner);
|
||||||
|
await queryRunner.query(`
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_name = 'accepted_share_entity'
|
||||||
|
AND column_name = 'protocol'
|
||||||
|
AND COALESCE(character_maximum_length, 0) < 16
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "accepted_share_entity" ALTER COLUMN "protocol" TYPE varchar(16);
|
||||||
|
END IF;
|
||||||
|
END
|
||||||
|
$$
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" ADD COLUMN IF NOT EXISTS "workSource" varchar(16) NOT NULL DEFAULT 'pool_template'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" ADD COLUMN IF NOT EXISTS "workProtocol" varchar(16) NOT NULL DEFAULT 'pool'`);
|
||||||
|
await this.restoreAcceptedShareCompression(queryRunner);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_protocol_work"
|
||||||
|
ON "accepted_share_entity" ("protocol", "workSource", "workProtocol", "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await this.decompressAcceptedShareChunks(queryRunner);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_protocol_work"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" DROP COLUMN IF EXISTS "workProtocol"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" DROP COLUMN IF EXISTS "workSource"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" ALTER COLUMN "protocol" TYPE varchar(8)`);
|
||||||
|
await this.restoreAcceptedShareCompression(queryRunner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async decompressAcceptedShareChunks(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
chunk_name regclass;
|
||||||
|
BEGIN
|
||||||
|
FOR chunk_name IN SELECT show_chunks('accepted_share_entity')
|
||||||
|
LOOP
|
||||||
|
PERFORM decompress_chunk(chunk_name, if_compressed => TRUE);
|
||||||
|
END LOOP;
|
||||||
|
END
|
||||||
|
$$
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async restoreAcceptedShareCompression(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity" SET (
|
||||||
|
timescaledb.compress,
|
||||||
|
timescaledb.compress_orderby = '"acceptedAt" DESC',
|
||||||
|
timescaledb.compress_segmentby = '"address","clientName"'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_compression_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '24 hours',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class AcceptedShareRetentionCompression1780966200000 implements MigrationInterface {
|
||||||
|
public name = 'AcceptedShareRetentionCompression1780966200000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity" SET (
|
||||||
|
timescaledb.compress,
|
||||||
|
timescaledb.compress_orderby = '"acceptedAt" DESC',
|
||||||
|
timescaledb.compress_segmentby = '"address","clientName"'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_compression_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '24 hours',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`SELECT remove_retention_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_retention_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '7 days',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_compression_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '1 day',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`SELECT remove_retention_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_retention_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '30 days',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class AcceptedShareRollupIndexes1780865400000 implements MigrationInterface {
|
||||||
|
public name = 'AcceptedShareRollupIndexes1780865400000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_10m_bucket"
|
||||||
|
ON "accepted_share_10m" ("bucket" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_10m_address_bucket"
|
||||||
|
ON "accepted_share_10m" ("address", "bucket" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_10m_group_bucket"
|
||||||
|
ON "accepted_share_10m" ("address", "clientName", "bucket" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_10m_client_bucket"
|
||||||
|
ON "accepted_share_10m" ("clientId", "bucket" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_10m_client_bucket"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_10m_group_bucket"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_10m_address_bucket"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_10m_bucket"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class ActiveClientReportIndex1781311000000 implements MigrationInterface {
|
||||||
|
public name = 'ActiveClientReportIndex1781311000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_client_working_report_updated_user_agent"
|
||||||
|
ON "client_entity" ("updatedAt" DESC, "userAgent")
|
||||||
|
INCLUDE ("hashRate", "bestDifficulty")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
AND "hashRate" > 0
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_client_working_report_updated_user_agent"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class ActiveClientReportRecentIndex1781312000000 implements MigrationInterface {
|
||||||
|
public name = 'ActiveClientReportRecentIndex1781312000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_client_active_report_updated_user_agent"
|
||||||
|
ON "client_entity" ("updatedAt" DESC, "userAgent")
|
||||||
|
INCLUDE ("hashRate", "bestDifficulty")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_client_working_report_updated_user_agent"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_client_working_report_updated_user_agent"
|
||||||
|
ON "client_entity" ("updatedAt" DESC, "userAgent")
|
||||||
|
INCLUDE ("hashRate", "bestDifficulty")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
AND "hashRate" > 0
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_client_active_report_updated_user_agent"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class ActiveOnlyUserAgentReport1780860200000 implements MigrationInterface {
|
||||||
|
name = 'ActiveOnlyUserAgentReport1780860200000';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "user_agent_report_view"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW "user_agent_report_view" AS
|
||||||
|
SELECT
|
||||||
|
"userAgent",
|
||||||
|
COUNT("userAgent") AS "count",
|
||||||
|
MAX("bestDifficulty") AS "bestDifficulty",
|
||||||
|
SUM("hashRate") AS "totalHashRate"
|
||||||
|
FROM "client_entity"
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
GROUP BY "userAgent"
|
||||||
|
ORDER BY "totalHashRate" DESC
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "user_agent_report_view"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW "user_agent_report_view" AS
|
||||||
|
SELECT
|
||||||
|
"userAgent",
|
||||||
|
COUNT("userAgent") AS "count",
|
||||||
|
MAX("bestDifficulty") AS "bestDifficulty",
|
||||||
|
SUM("hashRate") AS "totalHashRate"
|
||||||
|
FROM "client_entity"
|
||||||
|
GROUP BY "userAgent"
|
||||||
|
ORDER BY "totalHashRate" DESC
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class BlocksSubmissionMetadata1781220000000 implements MigrationInterface {
|
||||||
|
public name = 'BlocksSubmissionMetadata1781220000000';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" ADD COLUMN IF NOT EXISTS "blockHash" varchar`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" ADD COLUMN IF NOT EXISTS "blockSubmissionResult" varchar`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_blocks_successful_found"
|
||||||
|
ON "blocks_entity" ("height" DESC, "createdAt" DESC)
|
||||||
|
WHERE "blockSubmissionResult" IS NULL OR "blockSubmissionResult" = 'SUCCESS!'
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "UQ_blocks_block_hash"
|
||||||
|
ON "blocks_entity" ("blockHash")
|
||||||
|
WHERE "blockHash" IS NOT NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "UQ_blocks_block_hash"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_blocks_successful_found"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" DROP COLUMN IF EXISTS "blockSubmissionResult"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" DROP COLUMN IF EXISTS "blockHash"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class CurrentRoundBestShareIndex1780897600000 implements MigrationInterface {
|
||||||
|
public name = 'CurrentRoundBestShareIndex1780897600000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_address_settings_best_difficulty"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_round_best"
|
||||||
|
ON "accepted_share_entity" ("submissionDifficulty" DESC, "acceptedAt" DESC, "blockHeight")
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_round_best"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_address_settings_best_difficulty"
|
||||||
|
ON "address_settings_entity" ("bestDifficulty" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class CurrentRoundWorkRollup1780899000000 implements MigrationInterface {
|
||||||
|
public name = 'CurrentRoundWorkRollup1780899000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_block_10m"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', "acceptedAt") AS "bucket",
|
||||||
|
"blockHeight",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount",
|
||||||
|
MAX("networkDifficulty") AS "networkDifficulty",
|
||||||
|
MAX("submissionDifficulty") AS "bestSubmissionDifficulty"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "blockHeight"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_block_10m',
|
||||||
|
start_offset => INTERVAL '180 days',
|
||||||
|
end_offset => INTERVAL '1 minute',
|
||||||
|
schedule_interval => INTERVAL '1 minute',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_block_10m_height_bucket"
|
||||||
|
ON "accepted_share_block_10m" ("blockHeight" DESC, "bucket" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_block_10m_height_bucket"`);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "accepted_share_block_10m"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class FixClientSessionActiveIndex1780863600000 implements MigrationInterface {
|
||||||
|
public name = 'FixClientSessionActiveIndex1780863600000';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_unique_nonce"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
DELETE FROM "client_entity"
|
||||||
|
WHERE ctid IN (
|
||||||
|
SELECT ctid
|
||||||
|
FROM (
|
||||||
|
SELECT
|
||||||
|
ctid,
|
||||||
|
row_number() OVER (
|
||||||
|
PARTITION BY "sessionId"
|
||||||
|
ORDER BY "createdAt" DESC, "id" DESC
|
||||||
|
) AS rn
|
||||||
|
FROM "client_entity"
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
) duplicates
|
||||||
|
WHERE rn > 1
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_unique_nonce"
|
||||||
|
ON "client_entity" ("sessionId")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_unique_nonce"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_unique_nonce"
|
||||||
|
ON "client_entity" ("sessionId")
|
||||||
|
WHERE "deletedAt" IS NOT NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class InitialTimescaleSchema1780859300000 implements MigrationInterface {
|
||||||
|
public name = 'InitialTimescaleSchema1780859300000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
|
||||||
|
await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS timescaledb`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "address_settings_entity" (
|
||||||
|
"address" varchar(62) PRIMARY KEY,
|
||||||
|
"shares" integer NOT NULL DEFAULT 0,
|
||||||
|
"bestDifficulty" numeric NOT NULL DEFAULT 0,
|
||||||
|
"bestDifficultyUserAgent" varchar,
|
||||||
|
"miscCoinbaseScriptData" varchar,
|
||||||
|
"deletedAt" timestamptz,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "client_entity" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"clientName" varchar(64) NOT NULL,
|
||||||
|
"sessionId" varchar(8) NOT NULL,
|
||||||
|
"userAgent" varchar(128),
|
||||||
|
"startTime" timestamptz NOT NULL,
|
||||||
|
"bestDifficulty" numeric NOT NULL DEFAULT 0,
|
||||||
|
"hashRate" numeric NOT NULL DEFAULT 0,
|
||||||
|
"deletedAt" timestamptz,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_client_entity_address" ON "client_entity" ("address")`);
|
||||||
|
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_client_cleanup" ON "client_entity" ("id") WHERE "deletedAt" IS NULL`);
|
||||||
|
await queryRunner.query(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_unique_nonce" ON "client_entity" ("sessionId") WHERE "deletedAt" IS NULL`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "accepted_share_entity" (
|
||||||
|
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
|
||||||
|
"acceptedAt" timestamptz NOT NULL,
|
||||||
|
"protocol" varchar(8) NOT NULL,
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"clientName" varchar NOT NULL,
|
||||||
|
"sessionId" varchar(8) NOT NULL,
|
||||||
|
"clientId" uuid NOT NULL,
|
||||||
|
"jobId" varchar NOT NULL,
|
||||||
|
"jobTemplateId" varchar NOT NULL,
|
||||||
|
"blockHeight" bigint NOT NULL,
|
||||||
|
"creditedDifficulty" numeric NOT NULL,
|
||||||
|
"submissionDifficulty" numeric NOT NULL,
|
||||||
|
"networkDifficulty" numeric NOT NULL,
|
||||||
|
"nonce" varchar NOT NULL,
|
||||||
|
"ntime" varchar NOT NULL,
|
||||||
|
"version" varchar NOT NULL,
|
||||||
|
"extraNonce2" varchar NOT NULL,
|
||||||
|
"isBlockCandidate" boolean NOT NULL DEFAULT false,
|
||||||
|
"blockSubmissionResult" text,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY ("id", "acceptedAt")
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT create_hypertable(
|
||||||
|
'"accepted_share_entity"',
|
||||||
|
'acceptedAt',
|
||||||
|
chunk_time_interval => INTERVAL '1 day',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_accepted_share_accounting_lookup" ON "accepted_share_entity" ("address", "clientName", "acceptedAt" DESC)`);
|
||||||
|
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_accepted_share_client_lookup" ON "accepted_share_entity" ("clientId", "acceptedAt" DESC)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_accepted_share_unique_submission"
|
||||||
|
ON "accepted_share_entity" ("acceptedAt", "protocol", "sessionId", "jobId", "nonce", "ntime", "version", "extraNonce2")
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "blocks_entity" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"height" integer NOT NULL,
|
||||||
|
"minerAddress" varchar(62) NOT NULL,
|
||||||
|
"worker" varchar NOT NULL,
|
||||||
|
"sessionId" varchar(8) NOT NULL,
|
||||||
|
"blockData" varchar NOT NULL,
|
||||||
|
"blockHash" varchar,
|
||||||
|
"blockSubmissionResult" varchar,
|
||||||
|
"deletedAt" timestamptz,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "rpc_block_entity" (
|
||||||
|
"blockHeight" integer PRIMARY KEY,
|
||||||
|
"data" varchar
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "telegram_subscriptions_entity" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"telegramChatId" integer NOT NULL,
|
||||||
|
"deletedAt" timestamptz,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_telegram_subscriptions_address" ON "telegram_subscriptions_entity" ("address")`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "user_agent_report_view" AS
|
||||||
|
SELECT
|
||||||
|
"userAgent",
|
||||||
|
COUNT("userAgent") AS "count",
|
||||||
|
MAX("bestDifficulty") AS "bestDifficulty",
|
||||||
|
SUM("hashRate") AS "totalHashRate"
|
||||||
|
FROM "client_entity"
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
GROUP BY "userAgent"
|
||||||
|
ORDER BY "totalHashRate" DESC
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_10m"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', "acceptedAt") AS "bucket",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"sessionId",
|
||||||
|
"clientId",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount",
|
||||||
|
ROUND(((SUM("creditedDifficulty") * 4294967296) / 600)) AS "hashRate"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "address", "clientName", "sessionId", "clientId"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_1h"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '1 hour', "acceptedAt") AS "bucket",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "address", "clientName"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_1d"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '1 day', "acceptedAt") AS "bucket",
|
||||||
|
"address",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "address"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_10m',
|
||||||
|
start_offset => INTERVAL '2 days',
|
||||||
|
end_offset => INTERVAL '1 minute',
|
||||||
|
schedule_interval => INTERVAL '1 minute',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_1h',
|
||||||
|
start_offset => INTERVAL '30 days',
|
||||||
|
end_offset => INTERVAL '10 minutes',
|
||||||
|
schedule_interval => INTERVAL '10 minutes',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_1d',
|
||||||
|
start_offset => INTERVAL '365 days',
|
||||||
|
end_offset => INTERVAL '1 hour',
|
||||||
|
schedule_interval => INTERVAL '1 hour',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`SELECT add_retention_policy('accepted_share_entity', INTERVAL '90 days', if_not_exists => TRUE)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "accepted_share_1d"`);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "accepted_share_1h"`);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "accepted_share_10m"`);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "user_agent_report_view"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "accepted_share_entity" CASCADE`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "telegram_subscriptions_entity"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "rpc_block_entity"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "blocks_entity"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "client_entity"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "address_settings_entity"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class PayoutModes1781300000000 implements MigrationInterface {
|
||||||
|
public name = 'PayoutModes1781300000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'solo'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "client_entity" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'solo'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'solo'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "share_rollup_batch" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'pplns'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "share_rollup_batch_summary" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'pplns'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_snapshot" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'pplns'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_snapshot_entry" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'pplns'`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_history" ADD COLUMN IF NOT EXISTS "payoutMode" varchar(16) NOT NULL DEFAULT 'pplns'`);
|
||||||
|
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_accounting_lookup"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_unique_submission"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_range"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_finalized_end"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_summary_address_batch"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_latest"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_template_window"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "UQ_payout_history_block_address"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_history_address_created"`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_accounting_lookup"
|
||||||
|
ON "accepted_share_entity" ("payoutMode", "address", "clientName", "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_mode_order"
|
||||||
|
ON "accepted_share_entity" ("payoutMode", "shareIndex")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_accepted_share_unique_submission"
|
||||||
|
ON "accepted_share_entity" ("acceptedAt", "payoutMode", "protocol", "sessionId", "jobId", "nonce", "ntime", "version", "extraNonce2")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_share_rollup_batch_range"
|
||||||
|
ON "share_rollup_batch" ("payoutMode", "startShareIndex", "endShareIndex")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_batch_finalized_end"
|
||||||
|
ON "share_rollup_batch" ("payoutMode", "endShareIndex" DESC)
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_summary_address_batch"
|
||||||
|
ON "share_rollup_batch_summary" ("payoutMode", "address", "clientName", "blockHeight", "batchId")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_snapshot_latest"
|
||||||
|
ON "payout_snapshot" ("payoutMode", "status", "createdAt" DESC, "id" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_snapshot_template_window"
|
||||||
|
ON "payout_snapshot" ("payoutMode", "method", "blockHeight", "coinbaseValueSats", "windowEndShareIndex")
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "UQ_payout_history_block_address"
|
||||||
|
ON "payout_history" ("payoutMode", "blockHeight", "address")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_history_address_created"
|
||||||
|
ON "payout_history" ("payoutMode", "address", "createdAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_blocks_payout_mode_height"
|
||||||
|
ON "blocks_entity" ("payoutMode", "height" DESC, "createdAt" DESC)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await this.recreateContinuousAggregates(queryRunner);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity"
|
||||||
|
SET (
|
||||||
|
timescaledb.compress_segmentby = '"payoutMode","address","clientName"',
|
||||||
|
timescaledb.compress_orderby = '"acceptedAt" DESC'
|
||||||
|
)
|
||||||
|
`).catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_blocks_payout_mode_height"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_mode_order"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_accounting_lookup"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_unique_submission"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_range"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_finalized_end"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_summary_address_batch"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_latest"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_template_window"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "UQ_payout_history_block_address"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_history_address_created"`);
|
||||||
|
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_history" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_snapshot_entry" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "payout_snapshot" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "share_rollup_batch_summary" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "share_rollup_batch" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "client_entity" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "accepted_share_entity" DROP COLUMN IF EXISTS "payoutMode"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async recreateContinuousAggregates(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await this.dropContinuousAggregate(queryRunner, 'accepted_share_block_10m');
|
||||||
|
await this.dropContinuousAggregate(queryRunner, 'accepted_share_1d');
|
||||||
|
await this.dropContinuousAggregate(queryRunner, 'accepted_share_1h');
|
||||||
|
await this.dropContinuousAggregate(queryRunner, 'accepted_share_10m');
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_10m"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', "acceptedAt") AS "bucket",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"sessionId",
|
||||||
|
"clientId",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount",
|
||||||
|
ROUND(((SUM("creditedDifficulty") * 4294967296) / 600)) AS "hashRate"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "payoutMode", "address", "clientName", "sessionId", "clientId"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_1h"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '1 hour', "acceptedAt") AS "bucket",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "payoutMode", "address", "clientName"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_1d"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '1 day', "acceptedAt") AS "bucket",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "payoutMode", "address"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW IF NOT EXISTS "accepted_share_block_10m"
|
||||||
|
WITH (timescaledb.continuous) AS
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', "acceptedAt") AS "bucket",
|
||||||
|
"payoutMode",
|
||||||
|
"blockHeight",
|
||||||
|
SUM("creditedDifficulty") AS "shares",
|
||||||
|
COUNT(*) AS "acceptedCount",
|
||||||
|
MAX("networkDifficulty") AS "networkDifficulty",
|
||||||
|
MAX("submissionDifficulty") AS "bestSubmissionDifficulty"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
GROUP BY "bucket", "payoutMode", "blockHeight"
|
||||||
|
WITH NO DATA
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_10m',
|
||||||
|
start_offset => INTERVAL '2 days',
|
||||||
|
end_offset => INTERVAL '1 minute',
|
||||||
|
schedule_interval => INTERVAL '1 minute',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_1h',
|
||||||
|
start_offset => INTERVAL '30 days',
|
||||||
|
end_offset => INTERVAL '10 minutes',
|
||||||
|
schedule_interval => INTERVAL '10 minutes',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_1d',
|
||||||
|
start_offset => INTERVAL '365 days',
|
||||||
|
end_offset => INTERVAL '1 hour',
|
||||||
|
schedule_interval => INTERVAL '1 hour',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_continuous_aggregate_policy(
|
||||||
|
'accepted_share_block_10m',
|
||||||
|
start_offset => INTERVAL '180 days',
|
||||||
|
end_offset => INTERVAL '1 minute',
|
||||||
|
schedule_interval => INTERVAL '1 minute',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_block_10m_height_bucket"
|
||||||
|
ON "accepted_share_block_10m" ("payoutMode", "blockHeight" DESC, "bucket" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async dropContinuousAggregate(queryRunner: QueryRunner, viewName: string): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT remove_continuous_aggregate_policy('${viewName}', if_exists => TRUE)`).catch(() => undefined);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "${viewName}" CASCADE`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class PayoutSnapshots1780969800000 implements MigrationInterface {
|
||||||
|
public name = 'PayoutSnapshots1780969800000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "payout_snapshot" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"method" varchar(32) NOT NULL,
|
||||||
|
"status" varchar(16) NOT NULL DEFAULT 'finalized',
|
||||||
|
"blockHeight" bigint NOT NULL,
|
||||||
|
"coinbaseValueSats" bigint NOT NULL,
|
||||||
|
"networkDifficulty" numeric NOT NULL,
|
||||||
|
"windowTargetDifficulty" numeric NOT NULL DEFAULT 0,
|
||||||
|
"windowFactor" numeric NOT NULL DEFAULT 4,
|
||||||
|
"feeAddress" varchar(62),
|
||||||
|
"feeSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"minPayoutSats" integer NOT NULL DEFAULT 546,
|
||||||
|
"coinbaseWeightBudget" integer NOT NULL DEFAULT 50000,
|
||||||
|
"startBatchId" bigint NOT NULL REFERENCES "share_rollup_batch" ("id"),
|
||||||
|
"endBatchId" bigint NOT NULL REFERENCES "share_rollup_batch" ("id"),
|
||||||
|
"windowStartShareIndex" bigint NOT NULL,
|
||||||
|
"windowEndShareIndex" bigint NOT NULL,
|
||||||
|
"totalCreditedDifficulty" numeric NOT NULL,
|
||||||
|
"totalAcceptedShareCount" bigint NOT NULL,
|
||||||
|
"eligibleAddressCount" integer NOT NULL,
|
||||||
|
"includedOutputCount" integer NOT NULL,
|
||||||
|
"distributedSats" bigint NOT NULL,
|
||||||
|
"unallocatedRemainderSats" bigint NOT NULL,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_snapshot_latest"
|
||||||
|
ON "payout_snapshot" ("status", "createdAt" DESC, "id" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_snapshot_window"
|
||||||
|
ON "payout_snapshot" ("windowEndShareIndex" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_snapshot_template_window"
|
||||||
|
ON "payout_snapshot" ("method", "blockHeight", "coinbaseValueSats", "windowEndShareIndex")
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "payout_snapshot_entry" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"snapshotId" bigint NOT NULL REFERENCES "payout_snapshot" ("id") ON DELETE CASCADE,
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"creditedDifficulty" numeric NOT NULL,
|
||||||
|
"acceptedShareCount" bigint NOT NULL,
|
||||||
|
"payoutWeight" numeric NOT NULL,
|
||||||
|
"grossPayoutSats" bigint NOT NULL,
|
||||||
|
"payoutSats" bigint NOT NULL,
|
||||||
|
"balanceBeforeSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"balanceAfterSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"includedInCoinbase" boolean NOT NULL DEFAULT true,
|
||||||
|
"rowType" varchar(16) NOT NULL DEFAULT 'coinbase',
|
||||||
|
"rank" integer NOT NULL,
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_snapshot_entry_snapshot_address"
|
||||||
|
ON "payout_snapshot_entry" ("snapshotId", "address")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_snapshot_entry_snapshot_rank"
|
||||||
|
ON "payout_snapshot_entry" ("snapshotId", "rank")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_snapshot_entry_address"
|
||||||
|
ON "payout_snapshot_entry" ("address")
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "payout_balance" (
|
||||||
|
"address" varchar(62) PRIMARY KEY,
|
||||||
|
"balanceSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"totalPaidSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"lastAcceptedShareAt" timestamptz,
|
||||||
|
"updatedAt" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_balance_nonzero"
|
||||||
|
ON "payout_balance" ("balanceSats")
|
||||||
|
WHERE "balanceSats" != 0
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "payout_history" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"blockHeight" bigint NOT NULL,
|
||||||
|
"payoutSnapshotId" bigint NOT NULL REFERENCES "payout_snapshot" ("id") ON DELETE CASCADE,
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"paidSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"percent" numeric NOT NULL DEFAULT 0,
|
||||||
|
"balanceBeforeSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"balanceAfterSats" bigint NOT NULL DEFAULT 0,
|
||||||
|
"rowType" varchar(16) NOT NULL DEFAULT 'coinbase',
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "UQ_payout_history_block_address"
|
||||||
|
ON "payout_history" ("blockHeight", "address")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_payout_history_address_created"
|
||||||
|
ON "payout_history" ("address", "createdAt" DESC)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" ADD COLUMN IF NOT EXISTS "payoutSnapshotId" bigint`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_blocks_payout_snapshot"
|
||||||
|
ON "blocks_entity" ("payoutSnapshotId")
|
||||||
|
WHERE "payoutSnapshotId" IS NOT NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_blocks_payout_snapshot"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "blocks_entity" DROP COLUMN IF EXISTS "payoutSnapshotId"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_history_address_created"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "UQ_payout_history_block_address"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "payout_history"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_balance_nonzero"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "payout_balance"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_entry_address"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_entry_snapshot_rank"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_entry_snapshot_address"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "payout_snapshot_entry"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_template_window"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_window"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_payout_snapshot_latest"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "payout_snapshot"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class PoolAccountingDashboardIndexes1780867200000 implements MigrationInterface {
|
||||||
|
public name = 'PoolAccountingDashboardIndexes1780867200000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_accepted_at"
|
||||||
|
ON "accepted_share_entity" ("acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_round_best"
|
||||||
|
ON "accepted_share_entity" ("submissionDifficulty" DESC, "acceptedAt" DESC, "blockHeight")
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_round_best"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_accepted_at"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class RemoveAcceptedShareRetention1780959000000 implements MigrationInterface {
|
||||||
|
public name = 'RemoveAcceptedShareRetention1780959000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT remove_retention_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT add_retention_policy('accepted_share_entity', INTERVAL '30 days', if_not_exists => TRUE)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class ShareRollupBatches1780962600000 implements MigrationInterface {
|
||||||
|
public name = 'ShareRollupBatches1780962600000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "share_rollup_batch" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"startShareIndex" bigint NOT NULL,
|
||||||
|
"endShareIndex" bigint NOT NULL,
|
||||||
|
"startAcceptedAt" timestamptz NOT NULL,
|
||||||
|
"endAcceptedAt" timestamptz NOT NULL,
|
||||||
|
"acceptedShareCount" bigint NOT NULL,
|
||||||
|
"creditedDifficulty" numeric NOT NULL,
|
||||||
|
"status" varchar(16) NOT NULL DEFAULT 'finalized',
|
||||||
|
"createdAt" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"finalizedAt" timestamptz,
|
||||||
|
CONSTRAINT "CHK_share_rollup_batch_index_order"
|
||||||
|
CHECK ("endShareIndex" >= "startShareIndex")
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_share_rollup_batch_range"
|
||||||
|
ON "share_rollup_batch" ("startShareIndex", "endShareIndex")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_batch_finalized_end"
|
||||||
|
ON "share_rollup_batch" ("endShareIndex" DESC)
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS "share_rollup_batch_summary" (
|
||||||
|
"batchId" bigint NOT NULL REFERENCES "share_rollup_batch" ("id") ON DELETE CASCADE,
|
||||||
|
"address" varchar(62) NOT NULL,
|
||||||
|
"clientName" varchar NOT NULL,
|
||||||
|
"protocol" varchar(8) NOT NULL,
|
||||||
|
"blockHeight" integer NOT NULL,
|
||||||
|
"creditedDifficulty" numeric NOT NULL,
|
||||||
|
"acceptedShareCount" bigint NOT NULL,
|
||||||
|
"bestSubmissionDifficulty" numeric NOT NULL,
|
||||||
|
"firstShareAt" timestamptz NOT NULL,
|
||||||
|
"lastShareAt" timestamptz NOT NULL,
|
||||||
|
PRIMARY KEY ("batchId", "address", "clientName", "protocol", "blockHeight")
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_summary_address_batch"
|
||||||
|
ON "share_rollup_batch_summary" ("address", "clientName", "blockHeight", "batchId")
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_summary_address_batch"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "share_rollup_batch_summary"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_finalized_end"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_batch_range"`);
|
||||||
|
await queryRunner.query(`DROP TABLE IF EXISTS "share_rollup_batch"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class ShareRollupStoragePolicy1781305000000 implements MigrationInterface {
|
||||||
|
public name = 'ShareRollupStoragePolicy1781305000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`TRUNCATE TABLE "payout_balance", "share_rollup_batch" RESTART IDENTITY CASCADE`);
|
||||||
|
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_summary_address_batch"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "share_rollup_batch_summary" DROP CONSTRAINT IF EXISTS "share_rollup_batch_summary_pkey"`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT create_hypertable(
|
||||||
|
'"share_rollup_batch_summary"',
|
||||||
|
'lastShareAt',
|
||||||
|
chunk_time_interval => INTERVAL '1 day',
|
||||||
|
if_not_exists => TRUE,
|
||||||
|
migrate_data => FALSE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_summary_batch"
|
||||||
|
ON "share_rollup_batch_summary" ("batchId", "payoutMode")
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "share_rollup_batch_summary" SET (
|
||||||
|
timescaledb.compress,
|
||||||
|
timescaledb.compress_orderby = '"lastShareAt" DESC',
|
||||||
|
timescaledb.compress_segmentby = '"payoutMode","batchId"'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('share_rollup_batch_summary', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_compression_policy(
|
||||||
|
'share_rollup_batch_summary',
|
||||||
|
INTERVAL '24 hours',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_accounting_lookup"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_client_lookup"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_order"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_accepted_at"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_round_best"`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_accepted_share_protocol_work"`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE OR REPLACE PROCEDURE prune_share_rollup_batches(job_id int, config jsonb)
|
||||||
|
LANGUAGE PLPGSQL
|
||||||
|
AS $$
|
||||||
|
DECLARE
|
||||||
|
retention interval := COALESCE((config ->> 'retention')::interval, INTERVAL '30 days');
|
||||||
|
deleted_count bigint;
|
||||||
|
BEGIN
|
||||||
|
DELETE FROM "share_rollup_batch"
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
AND "finalizedAt" IS NOT NULL
|
||||||
|
AND "finalizedAt" < NOW() - retention;
|
||||||
|
|
||||||
|
GET DIAGNOSTICS deleted_count = ROW_COUNT;
|
||||||
|
RAISE LOG 'prune_share_rollup_batches deleted % finalized batches older than %', deleted_count, retention;
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM timescaledb_information.jobs
|
||||||
|
WHERE proc_name = 'prune_share_rollup_batches'
|
||||||
|
) THEN
|
||||||
|
PERFORM add_job(
|
||||||
|
'prune_share_rollup_batches'::regproc,
|
||||||
|
INTERVAL '1 day',
|
||||||
|
jsonb_build_object('retention', '30 days')
|
||||||
|
);
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT delete_job(job_id) FROM timescaledb_information.jobs WHERE proc_name = 'prune_share_rollup_batches'`);
|
||||||
|
await queryRunner.query(`DROP PROCEDURE IF EXISTS prune_share_rollup_batches(int, jsonb)`);
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('share_rollup_batch_summary', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_share_rollup_summary_batch"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_share_rollup_summary_address_batch"
|
||||||
|
ON "share_rollup_batch_summary" ("payoutMode", "address", "clientName", "blockHeight", "batchId")
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_accounting_lookup"
|
||||||
|
ON "accepted_share_entity" ("payoutMode", "address", "clientName", "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_client_lookup"
|
||||||
|
ON "accepted_share_entity" ("clientId", "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_order"
|
||||||
|
ON "accepted_share_entity" ("shareIndex" DESC)
|
||||||
|
WHERE "shareIndex" IS NOT NULL
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_accepted_at"
|
||||||
|
ON "accepted_share_entity" ("acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_round_best"
|
||||||
|
ON "accepted_share_entity" ("submissionDifficulty" DESC, "acceptedAt" DESC, "blockHeight")
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS "IDX_accepted_share_protocol_work"
|
||||||
|
ON "accepted_share_entity" ("protocol", "workSource", "workProtocol", "acceptedAt" DESC)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class TimescaleOperationalHardening1780861200000 implements MigrationInterface {
|
||||||
|
public name = 'TimescaleOperationalHardening1780861200000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
ALTER TABLE "accepted_share_entity" SET (
|
||||||
|
timescaledb.compress,
|
||||||
|
timescaledb.compress_orderby = '"acceptedAt" DESC',
|
||||||
|
timescaledb.compress_segmentby = '"address","clientName"'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`
|
||||||
|
SELECT add_compression_policy(
|
||||||
|
'accepted_share_entity',
|
||||||
|
INTERVAL '1 day',
|
||||||
|
if_not_exists => TRUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await queryRunner.query(`SELECT remove_retention_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`SELECT add_retention_policy('accepted_share_entity', INTERVAL '30 days', if_not_exists => TRUE)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`SELECT remove_compression_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`SELECT remove_retention_policy('accepted_share_entity', if_exists => TRUE)`);
|
||||||
|
await queryRunner.query(`SELECT add_retention_policy('accepted_share_entity', INTERVAL '90 days', if_not_exists => TRUE)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class UniqueNonceIndex implements MigrationInterface {
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_unique_nonce" ON "client_entity" ("sessionId") WHERE "deletedAt" IS NULL`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_unique_nonce"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class UserAgentReportNonzeroHashrate1781313000000 implements MigrationInterface {
|
||||||
|
public name = 'UserAgentReportNonzeroHashrate1781313000000';
|
||||||
|
public transaction = false;
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "user_agent_report_view"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW "user_agent_report_view" AS
|
||||||
|
SELECT
|
||||||
|
"userAgent",
|
||||||
|
COUNT("userAgent") AS "count",
|
||||||
|
MAX("bestDifficulty") AS "bestDifficulty",
|
||||||
|
SUM("hashRate") AS "totalHashRate"
|
||||||
|
FROM "client_entity"
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
AND "hashRate" > 0
|
||||||
|
GROUP BY "userAgent"
|
||||||
|
ORDER BY "totalHashRate" DESC
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_client_working_report_updated_user_agent"
|
||||||
|
ON "client_entity" ("updatedAt" DESC, "userAgent")
|
||||||
|
INCLUDE ("hashRate", "bestDifficulty")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
AND "hashRate" > 0
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_client_active_report_updated_user_agent"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_client_working_report_updated_user_agent"`);
|
||||||
|
await queryRunner.query(`DROP MATERIALIZED VIEW IF EXISTS "user_agent_report_view"`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE MATERIALIZED VIEW "user_agent_report_view" AS
|
||||||
|
SELECT
|
||||||
|
"userAgent",
|
||||||
|
COUNT("userAgent") AS "count",
|
||||||
|
MAX("bestDifficulty") AS "bestDifficulty",
|
||||||
|
SUM("hashRate") AS "totalHashRate"
|
||||||
|
FROM "client_entity"
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
GROUP BY "userAgent"
|
||||||
|
ORDER BY "totalHashRate" DESC
|
||||||
|
`);
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_client_active_report_updated_user_agent"
|
||||||
|
ON "client_entity" ("updatedAt" DESC, "userAgent")
|
||||||
|
INCLUDE ("hashRate", "bestDifficulty")
|
||||||
|
WHERE "deletedAt" IS NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
|
||||||
|
import { UserAgentReportService } from './user-agent-report.service';
|
||||||
|
import { UserAgentReportView } from './user-agent-report.view';
|
||||||
|
import { ClientEntity } from '../../client/client.entity';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([UserAgentReportView, ClientEntity])],
|
||||||
|
providers: [UserAgentReportService],
|
||||||
|
exports: [TypeOrmModule, UserAgentReportService],
|
||||||
|
})
|
||||||
|
export class UserAgentReportModule { }
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import { UserAgentReportService } from './user-agent-report.service';
|
||||||
|
|
||||||
|
describe('UserAgentReportService', () => {
|
||||||
|
const originalApiOnly = process.env.API_ONLY;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (originalApiOnly == null) {
|
||||||
|
delete process.env.API_ONLY;
|
||||||
|
} else {
|
||||||
|
process.env.API_ONLY = originalApiOnly;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses active database clients for live API-only reports', async () => {
|
||||||
|
process.env.API_ONLY = 'true';
|
||||||
|
const userAgentReport = {
|
||||||
|
find: jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
userAgent: 'db-view',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 0,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
const clientRepository = createClientRepository([
|
||||||
|
{
|
||||||
|
userAgent: 'unknown/sv2',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 456,
|
||||||
|
totalHashRate: '123',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const redisMessagingService = {
|
||||||
|
getJsonCache: jest.fn().mockResolvedValue(null),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const service = new UserAgentReportService(
|
||||||
|
userAgentReport as any,
|
||||||
|
clientRepository as any,
|
||||||
|
redisMessagingService as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(service.getReport()).resolves.toEqual([
|
||||||
|
{
|
||||||
|
userAgent: 'unknown/sv2',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 456,
|
||||||
|
totalHashRate: '123',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(userAgentReport.find).not.toHaveBeenCalled();
|
||||||
|
expect(clientRepository.createQueryBuilder).toHaveBeenCalled();
|
||||||
|
expect(clientRepository.queryBuilder.andWhere).toHaveBeenCalledWith(
|
||||||
|
'client.updatedAt > :activeSince',
|
||||||
|
expect.objectContaining({ activeSince: expect.any(Date) }),
|
||||||
|
);
|
||||||
|
expect(clientRepository.queryBuilder.andWhere).toHaveBeenCalledWith('client.hashRate > 0');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the materialized view when no active database clients exist', async () => {
|
||||||
|
process.env.API_ONLY = 'true';
|
||||||
|
const viewRows = [
|
||||||
|
{
|
||||||
|
userAgent: 'db-view',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 0,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const userAgentReport = {
|
||||||
|
find: jest.fn().mockResolvedValue(viewRows),
|
||||||
|
};
|
||||||
|
const clientRepository = createClientRepository([]);
|
||||||
|
const redisMessagingService = {
|
||||||
|
getJsonCache: jest.fn().mockResolvedValue([]),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const service = new UserAgentReportService(
|
||||||
|
userAgentReport as any,
|
||||||
|
clientRepository as any,
|
||||||
|
redisMessagingService as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(service.getReport()).resolves.toEqual(viewRows);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns a non-empty cached live report before querying the database', async () => {
|
||||||
|
process.env.API_ONLY = 'true';
|
||||||
|
const cachedRows = [
|
||||||
|
{
|
||||||
|
userAgent: 'cached',
|
||||||
|
count: '2',
|
||||||
|
bestDifficulty: 8,
|
||||||
|
totalHashRate: '16',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const userAgentReport = {
|
||||||
|
find: jest.fn(),
|
||||||
|
};
|
||||||
|
const clientRepository = createClientRepository([]);
|
||||||
|
const redisMessagingService = {
|
||||||
|
getJsonCache: jest.fn().mockResolvedValue(cachedRows),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const service = new UserAgentReportService(
|
||||||
|
userAgentReport as any,
|
||||||
|
clientRepository as any,
|
||||||
|
redisMessagingService as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(service.getReport()).resolves.toEqual(cachedRows);
|
||||||
|
expect(clientRepository.createQueryBuilder).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function createClientRepository(rows: unknown[]) {
|
||||||
|
const queryBuilder = {
|
||||||
|
select: jest.fn().mockReturnThis(),
|
||||||
|
addSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
groupBy: jest.fn().mockReturnThis(),
|
||||||
|
orderBy: jest.fn().mockReturnThis(),
|
||||||
|
getRawMany: jest.fn().mockResolvedValue(rows),
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
createQueryBuilder: jest.fn().mockReturnValue(queryBuilder),
|
||||||
|
queryBuilder,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
|
||||||
|
import { ClientEntity } from '../../client/client.entity';
|
||||||
|
import { UserAgentReportView } from './user-agent-report.view';
|
||||||
|
import { RedisMessagingService } from '../../../services/redis-messaging.service';
|
||||||
|
|
||||||
|
const DEFAULT_CLIENT_REPORT_ACTIVE_WINDOW_MS = 30 * 60 * 1000;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UserAgentReportService {
|
||||||
|
private readonly liveReportCacheKey = 'presence:user-agent-report';
|
||||||
|
private readonly activeWindowMs = this.readPositiveInt('CLIENT_REPORT_ACTIVE_WINDOW_MS', DEFAULT_CLIENT_REPORT_ACTIVE_WINDOW_MS);
|
||||||
|
private liveRefreshPromise: Promise<UserAgentReportView[]> | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(UserAgentReportView)
|
||||||
|
private userAgentReport: Repository<UserAgentReportView>,
|
||||||
|
@InjectRepository(ClientEntity)
|
||||||
|
private clientRepository: Repository<ClientEntity>,
|
||||||
|
private redisMessagingService: RedisMessagingService,
|
||||||
|
) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getReport() {
|
||||||
|
const cachedReport = await this.redisMessagingService
|
||||||
|
.getJsonCache<UserAgentReportView[]>(this.liveReportCacheKey)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Live user-agent report cache read failed: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (cachedReport != null) {
|
||||||
|
if (cachedReport.length > 0) {
|
||||||
|
return cachedReport;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.API_ONLY == 'true') {
|
||||||
|
const liveReport = await this.refreshLiveReport();
|
||||||
|
if (liveReport.length > 0) {
|
||||||
|
return liveReport;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.userAgentReport.find();
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.refreshLiveReport();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refreshLiveReport() {
|
||||||
|
if (this.liveRefreshPromise != null) {
|
||||||
|
return this.liveRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.liveRefreshPromise = this.buildLiveReport()
|
||||||
|
.finally(() => {
|
||||||
|
this.liveRefreshPromise = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.liveRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async buildLiveReport() {
|
||||||
|
const activeSince = new Date(Date.now() - this.activeWindowMs);
|
||||||
|
const rows = await this.clientRepository
|
||||||
|
.createQueryBuilder('client')
|
||||||
|
.select('COALESCE(NULLIF(client.userAgent, \'\'), \'Other\')', 'userAgent')
|
||||||
|
.addSelect('COUNT(*)', 'count')
|
||||||
|
.addSelect('MAX(client.bestDifficulty)', 'bestDifficulty')
|
||||||
|
.addSelect('COALESCE(SUM(client.hashRate), 0)', 'totalHashRate')
|
||||||
|
.where('client.deletedAt IS NULL')
|
||||||
|
.andWhere('client.updatedAt > :activeSince', { activeSince })
|
||||||
|
.andWhere('client.hashRate > 0')
|
||||||
|
.groupBy('COALESCE(NULLIF(client.userAgent, \'\'), \'Other\')')
|
||||||
|
.orderBy('"totalHashRate"', 'DESC')
|
||||||
|
.getRawMany<UserAgentReportView>();
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return await this.userAgentReport.find();
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.redisMessagingService
|
||||||
|
.setJsonCache(this.liveReportCacheKey, rows, 60 * 1000)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Live user-agent report cache write failed: ${error.message}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refreshReport() {
|
||||||
|
try {
|
||||||
|
await this.userAgentReport.query(`REFRESH MATERIALIZED VIEW user_agent_report_view`);
|
||||||
|
return await this.refreshLiveReport();
|
||||||
|
} catch (e) {
|
||||||
|
|
||||||
|
console.log(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
if (Number.isInteger(value) && value > 0) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { DataSource, ViewColumn, ViewEntity } from 'typeorm';
|
||||||
|
|
||||||
|
import { ClientEntity } from '../../client/client.entity';
|
||||||
|
|
||||||
|
@ViewEntity({
|
||||||
|
materialized: true,
|
||||||
|
expression: (dataSource: DataSource) =>
|
||||||
|
dataSource
|
||||||
|
.createQueryBuilder()
|
||||||
|
.select('client.userAgent as "userAgent"')
|
||||||
|
.addSelect('COUNT(client.userAgent)', 'count')
|
||||||
|
.addSelect('MAX(client.bestDifficulty)', 'bestDifficulty')
|
||||||
|
.addSelect('SUM(client.hashRate)', 'totalHashRate')
|
||||||
|
.from(ClientEntity, 'client')
|
||||||
|
.where('client.deletedAt IS NULL')
|
||||||
|
.andWhere('client.hashRate > 0')
|
||||||
|
.groupBy('client.userAgent')
|
||||||
|
.orderBy('"totalHashRate"', 'DESC')
|
||||||
|
})
|
||||||
|
export class UserAgentReportView {
|
||||||
|
@ViewColumn()
|
||||||
|
userAgent: string;
|
||||||
|
@ViewColumn()
|
||||||
|
count: string;
|
||||||
|
@ViewColumn()
|
||||||
|
bestDifficulty: number;
|
||||||
|
@ViewColumn()
|
||||||
|
totalHashRate: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
@Entity()
|
||||||
|
@Index('IDX_accepted_share_mode_order', ['payoutMode', 'shareIndex'])
|
||||||
|
@Index('IDX_accepted_share_unique_submission', ['acceptedAt', 'payoutMode', 'protocol', 'sessionId', 'jobId', 'nonce', 'ntime', 'version', 'extraNonce2'], { unique: true })
|
||||||
|
export class AcceptedShareEntity {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@PrimaryColumn({ type: 'timestamptz' })
|
||||||
|
acceptedAt: Date;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: () => `nextval('accepted_share_index_seq')` })
|
||||||
|
shareIndex: number;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar' })
|
||||||
|
protocol: 'sv1' | 'sv1_tls' | 'sv2' | 'sv2_jdp' | 'datum';
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'solo' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'pool_template' })
|
||||||
|
workSource: 'pool_template' | 'miner_template';
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'pool' })
|
||||||
|
workProtocol: 'pool' | 'sv2_jdp' | 'datum';
|
||||||
|
|
||||||
|
@Column({ length: 62, type: 'varchar' })
|
||||||
|
address: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
clientName: string;
|
||||||
|
|
||||||
|
@Column({ length: 8, type: 'varchar' })
|
||||||
|
sessionId: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
clientId: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
jobId: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
jobTemplateId: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
blockHeight: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
creditedDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
submissionDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
networkDifficulty: number;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
nonce: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
ntime: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
version: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
extraNonce2: string;
|
||||||
|
|
||||||
|
@Column({ default: false })
|
||||||
|
isBlockCandidate: boolean;
|
||||||
|
|
||||||
|
@Column({ type: 'text', nullable: true })
|
||||||
|
blockSubmissionResult?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
@@ -11,9 +11,12 @@ export class AddressSettingsEntity extends TrackedEntity {
|
|||||||
@Column({ default: 0 })
|
@Column({ default: 0 })
|
||||||
shares: number;
|
shares: number;
|
||||||
|
|
||||||
@Column({ type: 'real', default: 0 })
|
@Column({ type: 'decimal', default: 0 })
|
||||||
bestDifficulty: number;
|
bestDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
bestDifficultyUserAgent: string;
|
||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
miscCoinbaseScriptData: string;
|
miscCoinbaseScriptData: string;
|
||||||
|
|
||||||
|
|||||||
@@ -17,33 +17,68 @@ export class AddressSettingsService {
|
|||||||
public async getSettings(address: string, createIfNotFound: boolean) {
|
public async getSettings(address: string, createIfNotFound: boolean) {
|
||||||
const settings = await this.addressSettingsRepository.findOne({ where: { address } });
|
const settings = await this.addressSettingsRepository.findOne({ where: { address } });
|
||||||
if (createIfNotFound == true && settings == null) {
|
if (createIfNotFound == true && settings == null) {
|
||||||
|
// It's possible to have a race condition here so if we get a PK violation, fetch it
|
||||||
|
try {
|
||||||
return await this.createNew(address);
|
return await this.createNew(address);
|
||||||
|
} catch (e) {
|
||||||
|
return await this.addressSettingsRepository.findOne({ where: { address } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return settings;
|
return settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateBestDifficulty(address: string, bestDifficulty: number) {
|
public async updateBestDifficulty(address: string, bestDifficulty: number, bestDifficultyUserAgent: string) {
|
||||||
return await this.addressSettingsRepository.update({ address }, { bestDifficulty });
|
return await this.addressSettingsRepository.update({ address }, { bestDifficulty, bestDifficultyUserAgent });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateBestDifficultyIfHigher(address: string, bestDifficulty: number, bestDifficultyUserAgent: string) {
|
||||||
|
await this.addressSettingsRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.insert()
|
||||||
|
.into(AddressSettingsEntity)
|
||||||
|
.values({ address })
|
||||||
|
.orIgnore()
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
return await this.addressSettingsRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(AddressSettingsEntity)
|
||||||
|
.set({ bestDifficulty, bestDifficultyUserAgent })
|
||||||
|
.where('address = :address', { address })
|
||||||
|
.andWhere('"bestDifficulty" < :bestDifficulty', { bestDifficulty })
|
||||||
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createNew(address: string) {
|
public async createNew(address: string) {
|
||||||
return await this.addressSettingsRepository.save({ address });
|
return await this.addressSettingsRepository.save({ address });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async addShares(address: string, shares: number) {
|
// public async addShares(address: string, shares: number) {
|
||||||
return await this.addressSettingsRepository.createQueryBuilder()
|
// return await this.addressSettingsRepository.createQueryBuilder()
|
||||||
|
// .update(AddressSettingsEntity)
|
||||||
|
// .set({
|
||||||
|
// shares: () => `"shares" + ${shares}` // Use the actual value of shares here
|
||||||
|
// })
|
||||||
|
// .where('address = :address', { address })
|
||||||
|
// .execute();
|
||||||
|
// }
|
||||||
|
|
||||||
|
public async resetBestDifficultyAndShares() {
|
||||||
|
return await this.addressSettingsRepository
|
||||||
|
.createQueryBuilder()
|
||||||
.update(AddressSettingsEntity)
|
.update(AddressSettingsEntity)
|
||||||
.set({
|
.set({
|
||||||
shares: () => `"shares" + ${shares}` // Use the actual value of shares here
|
shares: 0,
|
||||||
|
bestDifficulty: 0
|
||||||
})
|
})
|
||||||
.where('address = :address', { address })
|
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async resetBestDifficultyAndShares() {
|
public async getHighScores() {
|
||||||
return await this.addressSettingsRepository.update({}, {
|
return await this.addressSettingsRepository.createQueryBuilder()
|
||||||
shares: 0,
|
.select('"updatedAt", "bestDifficulty", "bestDifficultyUserAgent"')
|
||||||
bestDifficulty: 0
|
.orderBy('"bestDifficulty"', 'DESC')
|
||||||
});
|
.limit(10)
|
||||||
|
.execute();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
import { Column, Entity } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
import { PrimaryGeneratedBigIntColumn } from '../utils/PrimaryGeneratedBigIntColumn';
|
||||||
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
||||||
|
|
||||||
@Entity()
|
@Entity()
|
||||||
export class BlocksEntity extends TrackedEntity {
|
export class BlocksEntity extends TrackedEntity {
|
||||||
|
|
||||||
@PrimaryGeneratedColumn()
|
@PrimaryGeneratedBigIntColumn()
|
||||||
id: number;
|
id: number;
|
||||||
|
|
||||||
@Column()
|
@Column()
|
||||||
@@ -17,10 +19,22 @@ export class BlocksEntity extends TrackedEntity {
|
|||||||
@Column()
|
@Column()
|
||||||
worker: string;
|
worker: string;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'solo' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
@Column({ length: 8, type: 'varchar' })
|
@Column({ length: 8, type: 'varchar' })
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
|
|
||||||
@Column()
|
@Column()
|
||||||
blockData: string;
|
blockData: string;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
blockHash?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', nullable: true })
|
||||||
|
blockSubmissionResult?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', nullable: true })
|
||||||
|
payoutSnapshotId?: string | null;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import * as bitcoinjs from 'bitcoinjs-lib';
|
||||||
|
import { BlocksService } from './blocks.service';
|
||||||
|
|
||||||
|
describe('BlocksService', () => {
|
||||||
|
it('computes block hash metadata when saving found blocks', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.findOne.mockResolvedValue(null);
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
const blockHex = createBlockHex();
|
||||||
|
const blockHash = bitcoinjs.Block.fromHex(blockHex).getId();
|
||||||
|
|
||||||
|
await service.save({
|
||||||
|
height: 123,
|
||||||
|
minerAddress: 'tb1qexample',
|
||||||
|
worker: 'worker',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
blockData: blockHex,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.save).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
blockHash,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not downgrade an existing successful block on duplicate rejected submissions', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.findOne.mockResolvedValue({
|
||||||
|
id: 9,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '7',
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'worker',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
});
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await service.save({
|
||||||
|
blockData: createBlockHex(),
|
||||||
|
blockSubmissionResult: 'duplicate',
|
||||||
|
payoutSnapshotId: '8',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.update).not.toHaveBeenCalled();
|
||||||
|
expect(repository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps real miner attribution when a duplicate TDP submit arrives', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.findOne.mockResolvedValue({
|
||||||
|
id: 9,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '7',
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'sv2gateway',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
});
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await service.save({
|
||||||
|
blockData: createBlockHex(),
|
||||||
|
minerAddress: 'tb1qpool',
|
||||||
|
worker: 'tdp',
|
||||||
|
sessionId: '00000010',
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '8',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.update).toHaveBeenCalledWith(9, {
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '8',
|
||||||
|
});
|
||||||
|
expect(repository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears payout snapshot metadata when a duplicate successful solo submit arrives', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.findOne.mockResolvedValue({
|
||||||
|
id: 9,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '7',
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'worker',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
});
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await service.save({
|
||||||
|
blockData: createBlockHex(),
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.update).toHaveBeenCalledWith(9, {
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: null,
|
||||||
|
});
|
||||||
|
expect(repository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('repairs internal TDP attribution when a duplicate real miner submit arrives', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.findOne.mockResolvedValue({
|
||||||
|
id: 9,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
payoutSnapshotId: '7',
|
||||||
|
minerAddress: 'tb1qpool',
|
||||||
|
worker: 'tdp',
|
||||||
|
sessionId: '00000010',
|
||||||
|
});
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await service.save({
|
||||||
|
blockData: createBlockHex(),
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'sv2gateway',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
blockSubmissionResult: 'duplicate',
|
||||||
|
payoutSnapshotId: '8',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.update).toHaveBeenCalledWith(9, {
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'sv2gateway',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
});
|
||||||
|
expect(repository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns one public found-block row per block hash or legacy height', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.find.mockResolvedValue([
|
||||||
|
{ height: 124, minerAddress: 'addr2', worker: 'b', sessionId: '2222', blockHash: 'hash-b' },
|
||||||
|
{ height: 124, minerAddress: 'addr2', worker: 'b-dup', sessionId: '3333', blockHash: 'hash-b' },
|
||||||
|
{ height: 123, minerAddress: 'addr1', worker: 'a', sessionId: '1111', blockHash: null },
|
||||||
|
{ height: 123, minerAddress: 'addr1', worker: 'a-dup', sessionId: '4444', blockHash: null },
|
||||||
|
]);
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await expect(service.getFoundBlocks()).resolves.toEqual([
|
||||||
|
{ height: 124, minerAddress: 'addr2', worker: 'b', sessionId: '2222', blockHash: 'hash-b' },
|
||||||
|
{ height: 123, minerAddress: 'addr1', worker: 'a', sessionId: '1111', blockHash: null },
|
||||||
|
]);
|
||||||
|
expect(repository.find).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
where: expect.arrayContaining([
|
||||||
|
expect.objectContaining({ blockSubmissionResult: expect.objectContaining({ _value: expect.arrayContaining(['SUCCESS!', 'datum-gateway-submit-expected']) }) }),
|
||||||
|
expect.objectContaining({ blockSubmissionResult: expect.objectContaining({ _type: 'isNull' }) }),
|
||||||
|
]),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes DATUM gateway-submitted candidates for address found-block lookups', async () => {
|
||||||
|
const repository = createRepository();
|
||||||
|
repository.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
height: 4991348,
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'datum',
|
||||||
|
sessionId: '28ff7236',
|
||||||
|
blockHash: 'hash-datum',
|
||||||
|
blockSubmissionResult: 'datum-gateway-submit-expected',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const service = new BlocksService({} as any, repository as any);
|
||||||
|
|
||||||
|
await expect(service.getFoundBlocksByAddress('tb1qminer')).resolves.toEqual([
|
||||||
|
{
|
||||||
|
height: 4991348,
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
worker: 'datum',
|
||||||
|
sessionId: '28ff7236',
|
||||||
|
blockHash: 'hash-datum',
|
||||||
|
blockSubmissionResult: 'datum-gateway-submit-expected',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(repository.find).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
where: expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
blockSubmissionResult: expect.objectContaining({ _value: expect.arrayContaining(['SUCCESS!', 'datum-gateway-submit-expected']) }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
minerAddress: 'tb1qminer',
|
||||||
|
blockSubmissionResult: expect.objectContaining({ _type: 'isNull' }),
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
function createRepository() {
|
||||||
|
return {
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
find: jest.fn().mockResolvedValue([]),
|
||||||
|
findOne: jest.fn().mockResolvedValue(null),
|
||||||
|
update: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBlockHex(): string {
|
||||||
|
const tx = new bitcoinjs.Transaction();
|
||||||
|
tx.version = 1;
|
||||||
|
tx.addInput(Buffer.alloc(32), 0xffffffff, 0xffffffff, Buffer.from([0x01]));
|
||||||
|
tx.addOutput(Buffer.from('6a', 'hex'), 0);
|
||||||
|
|
||||||
|
const block = new bitcoinjs.Block();
|
||||||
|
block.version = 1;
|
||||||
|
block.prevHash = Buffer.alloc(32);
|
||||||
|
block.timestamp = 1;
|
||||||
|
block.bits = 0x207fffff;
|
||||||
|
block.nonce = 1;
|
||||||
|
block.transactions = [tx];
|
||||||
|
block.merkleRoot = bitcoinjs.Block.calculateMerkleRoot(block.transactions, false);
|
||||||
|
return block.toHex(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { DataSource, Repository } from 'typeorm';
|
import * as bitcoinjs from 'bitcoinjs-lib';
|
||||||
|
import { DataSource, In, IsNull, Repository } from 'typeorm';
|
||||||
|
|
||||||
import { BlocksEntity } from './blocks.entity';
|
import { BlocksEntity } from './blocks.entity';
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BlocksService {
|
export class BlocksService {
|
||||||
|
|
||||||
|
private static readonly PUBLIC_FOUND_BLOCK_RESULTS = ['SUCCESS!', 'datum-gateway-submit-expected'];
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
|
|
||||||
private dataSource: DataSource,
|
private dataSource: DataSource,
|
||||||
@@ -19,31 +23,143 @@ export class BlocksService {
|
|||||||
|
|
||||||
|
|
||||||
public async save(block: Partial<BlocksEntity>) {
|
public async save(block: Partial<BlocksEntity>) {
|
||||||
await this.blocksRepository.save(block);
|
const blockHash = block.blockHash ?? this.getBlockHash(block.blockData);
|
||||||
}
|
const existing = blockHash == null
|
||||||
|
? null
|
||||||
public async getFoundBlocks() {
|
: await this.blocksRepository.findOne({
|
||||||
return await this.blocksRepository.find({
|
|
||||||
select: {
|
select: {
|
||||||
height: true,
|
id: true,
|
||||||
|
blockSubmissionResult: true,
|
||||||
|
payoutSnapshotId: true,
|
||||||
minerAddress: true,
|
minerAddress: true,
|
||||||
worker: true,
|
worker: true,
|
||||||
sessionId: true
|
sessionId: true,
|
||||||
}
|
payoutMode: true,
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getFoundBlocksByAddress(address: string) {
|
|
||||||
return await this.blocksRepository.find({
|
|
||||||
select: {
|
|
||||||
height: true,
|
|
||||||
minerAddress: true,
|
|
||||||
worker: true,
|
|
||||||
sessionId: true
|
|
||||||
},
|
},
|
||||||
where: {
|
where: { blockHash },
|
||||||
minerAddress: address
|
});
|
||||||
|
if (existing != null) {
|
||||||
|
const update: Partial<BlocksEntity> = {};
|
||||||
|
if (this.isSuccessfulBlockSubmission(block.blockSubmissionResult)) {
|
||||||
|
update.blockSubmissionResult = 'SUCCESS!';
|
||||||
|
update.payoutSnapshotId = Object.prototype.hasOwnProperty.call(block, 'payoutSnapshotId')
|
||||||
|
? block.payoutSnapshotId ?? null
|
||||||
|
: existing.payoutSnapshotId;
|
||||||
}
|
}
|
||||||
|
if (this.shouldReplaceAttribution(existing, block)) {
|
||||||
|
update.minerAddress = block.minerAddress;
|
||||||
|
update.worker = block.worker;
|
||||||
|
update.sessionId = block.sessionId;
|
||||||
|
}
|
||||||
|
if (block.payoutMode != null && existing.payoutMode !== block.payoutMode) {
|
||||||
|
update.payoutMode = block.payoutMode;
|
||||||
|
}
|
||||||
|
if (Object.keys(update).length > 0) {
|
||||||
|
await this.blocksRepository.update(existing.id, update);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.blocksRepository.save({
|
||||||
|
...block,
|
||||||
|
blockHash,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getFoundBlocks(payoutMode?: PayoutMode) {
|
||||||
|
const rows = await this.blocksRepository.find({
|
||||||
|
select: {
|
||||||
|
height: true,
|
||||||
|
minerAddress: true,
|
||||||
|
worker: true,
|
||||||
|
sessionId: true,
|
||||||
|
payoutMode: true,
|
||||||
|
blockHash: true,
|
||||||
|
blockSubmissionResult: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
where: [
|
||||||
|
{ ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: In(BlocksService.PUBLIC_FOUND_BLOCK_RESULTS) },
|
||||||
|
{ ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: IsNull() },
|
||||||
|
],
|
||||||
|
order: {
|
||||||
|
height: 'DESC',
|
||||||
|
createdAt: 'DESC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.uniqueFoundBlocks(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getFoundBlocksByAddress(address: string, payoutMode?: PayoutMode) {
|
||||||
|
const rows = await this.blocksRepository.find({
|
||||||
|
select: {
|
||||||
|
height: true,
|
||||||
|
minerAddress: true,
|
||||||
|
worker: true,
|
||||||
|
sessionId: true,
|
||||||
|
payoutMode: true,
|
||||||
|
blockHash: true,
|
||||||
|
blockSubmissionResult: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
where: [
|
||||||
|
{ minerAddress: address, ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: In(BlocksService.PUBLIC_FOUND_BLOCK_RESULTS) },
|
||||||
|
{ minerAddress: address, ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: IsNull() },
|
||||||
|
],
|
||||||
|
order: {
|
||||||
|
height: 'DESC',
|
||||||
|
createdAt: 'DESC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.uniqueFoundBlocks(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
private uniqueFoundBlocks(rows: Partial<BlocksEntity>[]): Partial<BlocksEntity>[] {
|
||||||
|
const seenBlocks = new Set<string>();
|
||||||
|
const seenHeights = new Set<number>();
|
||||||
|
return rows.filter(row => {
|
||||||
|
if (row.height != null && seenHeights.has(row.height)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const key = row.blockHash || `height:${row.height}`;
|
||||||
|
if (seenBlocks.has(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
seenBlocks.add(key);
|
||||||
|
if (row.height != null) {
|
||||||
|
seenHeights.add(row.height);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getBlockHash(blockData?: string): string | undefined {
|
||||||
|
if (blockData == null || blockData.length < 160) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return bitcoinjs.Block.fromHex(blockData).getId();
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private isSuccessfulBlockSubmission(result?: string | null): boolean {
|
||||||
|
return result == null || result === 'SUCCESS!';
|
||||||
|
}
|
||||||
|
|
||||||
|
private shouldReplaceAttribution(existing: Partial<BlocksEntity>, incoming: Partial<BlocksEntity>): boolean {
|
||||||
|
if (!incoming.minerAddress || !incoming.worker) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (this.isInternalAttribution(incoming)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return this.isInternalAttribution(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isInternalAttribution(block: Partial<BlocksEntity>): boolean {
|
||||||
|
const worker = block.worker?.toLowerCase();
|
||||||
|
return worker === 'tdp' || block.minerAddress === 'sv2-tdp';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
|
||||||
|
|
||||||
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
|
||||||
|
|
||||||
@Entity()
|
|
||||||
//Index for getHashRateForSession
|
|
||||||
@Index(["address", "clientName", "sessionId"])
|
|
||||||
//Index for statistics save
|
|
||||||
@Index(["address", "clientName", "sessionId", "time"])
|
|
||||||
export class ClientStatisticsEntity extends TrackedEntity {
|
|
||||||
|
|
||||||
@PrimaryGeneratedColumn()
|
|
||||||
id: number;
|
|
||||||
|
|
||||||
@Column({ length: 62, type: 'varchar' })
|
|
||||||
address: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
clientName: string;
|
|
||||||
|
|
||||||
@Column({ length: 8, type: 'varchar' })
|
|
||||||
sessionId: string;
|
|
||||||
|
|
||||||
@Index()
|
|
||||||
@Column({ type: 'integer' })
|
|
||||||
time: number;
|
|
||||||
|
|
||||||
@Column({ type: 'real' })
|
|
||||||
shares: number;
|
|
||||||
|
|
||||||
@Column({ default: 0, type: 'integer' })
|
|
||||||
acceptedCount: number;
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,11 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
|
|
||||||
import { ClientStatisticsEntity } from './client-statistics.entity';
|
|
||||||
import { ClientStatisticsService } from './client-statistics.service';
|
import { ClientStatisticsService } from './client-statistics.service';
|
||||||
|
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([ClientStatisticsEntity])],
|
|
||||||
providers: [ClientStatisticsService],
|
providers: [ClientStatisticsService],
|
||||||
exports: [TypeOrmModule, ClientStatisticsService],
|
exports: [ClientStatisticsService],
|
||||||
})
|
})
|
||||||
export class ClientStatisticsModule { }
|
export class ClientStatisticsModule { }
|
||||||
@@ -1,260 +1,220 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectDataSource } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
|
|
||||||
import { ClientStatisticsEntity } from './client-statistics.entity';
|
import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
const HASHES_PER_DIFFICULTY = 4294967296;
|
||||||
|
const CHART_BUCKET_SECONDS = 600;
|
||||||
|
const CHART_WINDOW = '24 hours';
|
||||||
|
const SITE_CHART_WINDOW = '7 days';
|
||||||
|
|
||||||
|
interface AcceptedShareChartFilter {
|
||||||
|
address?: string;
|
||||||
|
clientName?: string;
|
||||||
|
clientId?: string;
|
||||||
|
payoutMode?: PayoutMode;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ClientStatisticsService {
|
export class ClientStatisticsService {
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
|
@InjectDataSource()
|
||||||
|
private dataSource: DataSource,
|
||||||
@InjectRepository(ClientStatisticsEntity)
|
|
||||||
private clientStatisticsRepository: Repository<ClientStatisticsEntity>,
|
|
||||||
) {
|
) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async save(clientStatistic: Partial<ClientStatisticsEntity>) {
|
public async getChartDataForSite(limit: number = 144 * 7) {
|
||||||
// Attempt to update the existing record
|
return this.getAcceptedShareChartData('', [], limit, SITE_CHART_WINDOW);
|
||||||
const updateResult = await this.clientStatisticsRepository
|
|
||||||
.createQueryBuilder()
|
|
||||||
.update(ClientStatisticsEntity)
|
|
||||||
.set({
|
|
||||||
shares: () => `"shares" + :sharesIncrement`,
|
|
||||||
acceptedCount: () => `"acceptedCount" + 1`
|
|
||||||
})
|
|
||||||
.where('address = :address AND clientName = :clientName AND sessionId = :sessionId AND time = :time', {
|
|
||||||
address: clientStatistic.address,
|
|
||||||
clientName: clientStatistic.clientName,
|
|
||||||
sessionId: clientStatistic.sessionId,
|
|
||||||
time: clientStatistic.time,
|
|
||||||
sharesIncrement: clientStatistic.shares
|
|
||||||
})
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
// Check if the update affected any rows
|
|
||||||
if (updateResult.affected === 0) {
|
|
||||||
// If no rows were updated, insert a new record
|
|
||||||
await this.clientStatisticsRepository.insert(clientStatistic);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteOldStatistics() {
|
public async getChartDataForSiteByPayoutMode(payoutMode?: PayoutMode, limit: number = 144 * 7) {
|
||||||
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
return this.getAcceptedShareChartDataByPayoutMode({ payoutMode }, limit, SITE_CHART_WINDOW);
|
||||||
|
|
||||||
return await this.clientStatisticsRepository
|
|
||||||
.createQueryBuilder()
|
|
||||||
.delete()
|
|
||||||
.from(ClientStatisticsEntity)
|
|
||||||
.where('time < :time', { time: oneDayAgo.getTime() })
|
|
||||||
.execute();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getChartDataForSite() {
|
|
||||||
|
|
||||||
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
SELECT
|
|
||||||
time AS label,
|
|
||||||
ROUND(((SUM(shares) * 4294967296) / 600)) AS data
|
|
||||||
FROM
|
|
||||||
client_statistics_entity AS entry
|
|
||||||
WHERE
|
|
||||||
entry.time > ${yesterday.getTime()}
|
|
||||||
GROUP BY
|
|
||||||
time
|
|
||||||
ORDER BY
|
|
||||||
time
|
|
||||||
LIMIT 144;
|
|
||||||
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result: any[] = await this.clientStatisticsRepository.query(query);
|
|
||||||
|
|
||||||
|
|
||||||
return result.map(res => {
|
|
||||||
res.label = new Date(res.label).toISOString();
|
|
||||||
return res;
|
|
||||||
}).slice(0, result.length - 1)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// public async getHashRateForAddress(address: string) {
|
|
||||||
|
|
||||||
// const oneHour = new Date(new Date().getTime() - (60 * 60 * 1000));
|
|
||||||
|
|
||||||
// const query = `
|
|
||||||
// SELECT
|
|
||||||
// SUM(entry.shares) AS difficultySum
|
|
||||||
// FROM
|
|
||||||
// client_statistics_entity AS entry
|
|
||||||
// WHERE
|
|
||||||
// entry.address = ? AND entry.time > ${oneHour}
|
|
||||||
// `;
|
|
||||||
|
|
||||||
// const result = await this.clientStatisticsRepository.query(query, [address]);
|
|
||||||
|
|
||||||
// const difficultySum = result[0].difficultySum;
|
|
||||||
|
|
||||||
// return (difficultySum * 4294967296) / (600);
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
public async getChartDataForAddress(address: string) {
|
public async getChartDataForAddress(address: string) {
|
||||||
|
return this.getAcceptedShareChartData(
|
||||||
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
|
'AND "address" = $1',
|
||||||
|
[address],
|
||||||
const query = `
|
144,
|
||||||
SELECT
|
CHART_WINDOW,
|
||||||
time label,
|
);
|
||||||
(SUM(shares) * 4294967296) / 600 AS data
|
|
||||||
FROM
|
|
||||||
client_statistics_entity AS entry
|
|
||||||
WHERE
|
|
||||||
entry.address = ? AND entry.time > ${yesterday.getTime()}
|
|
||||||
GROUP BY
|
|
||||||
time
|
|
||||||
ORDER BY
|
|
||||||
time
|
|
||||||
LIMIT 144;
|
|
||||||
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await this.clientStatisticsRepository.query(query, [address]);
|
|
||||||
|
|
||||||
return result.map(res => {
|
|
||||||
res.label = new Date(res.label).toISOString();
|
|
||||||
return res;
|
|
||||||
}).slice(0, result.length - 1);
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getChartDataForAddressByPayoutMode(address: string, payoutMode?: PayoutMode) {
|
||||||
|
return this.getAcceptedShareChartDataByPayoutMode({ address, payoutMode }, 144, CHART_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
public async getHashRateForGroup(address: string, clientName: string) {
|
public async getHashRateForGroup(address: string, clientName: string) {
|
||||||
|
const result = await this.dataSource.query(`
|
||||||
var oneHour = new Date(new Date().getTime() - (60 * 60 * 1000));
|
WITH bounds AS (
|
||||||
|
SELECT time_bucket(INTERVAL '10 minutes', NOW()) AS current_bucket
|
||||||
const query = `
|
),
|
||||||
|
completed AS (
|
||||||
|
SELECT COALESCE(SUM("shares"), 0) AS "creditedDifficulty"
|
||||||
|
FROM "accepted_share_10m", bounds
|
||||||
|
WHERE "address" = $1
|
||||||
|
AND "clientName" = $2
|
||||||
|
AND "bucket" > bounds.current_bucket - INTERVAL '1 hour'
|
||||||
|
AND "bucket" < bounds.current_bucket
|
||||||
|
),
|
||||||
|
live AS (
|
||||||
|
SELECT COALESCE(SUM("creditedDifficulty"), 0) AS "creditedDifficulty"
|
||||||
|
FROM "accepted_share_entity", bounds
|
||||||
|
WHERE "address" = $1
|
||||||
|
AND "clientName" = $2
|
||||||
|
AND "acceptedAt" >= bounds.current_bucket
|
||||||
|
)
|
||||||
SELECT
|
SELECT
|
||||||
SUM(entry.shares) AS difficultySum
|
COALESCE(((completed."creditedDifficulty" + live."creditedDifficulty") * ${HASHES_PER_DIFFICULTY}) / ${CHART_BUCKET_SECONDS}, 0) AS "hashRate"
|
||||||
FROM
|
FROM completed, live
|
||||||
client_statistics_entity AS entry
|
`, [address, clientName]);
|
||||||
WHERE
|
|
||||||
entry.address = ? AND entry.clientName = ? AND entry.time > ${oneHour.getTime()}
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await this.clientStatisticsRepository.query(query, [address, clientName]);
|
|
||||||
|
|
||||||
|
|
||||||
const difficultySum = result[0].difficultySum;
|
|
||||||
|
|
||||||
return (difficultySum * 4294967296) / (600);
|
|
||||||
|
|
||||||
|
return parseFloat(result[0]?.hashRate ?? '0');
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getChartDataForGroup(address: string, clientName: string) {
|
public async getChartDataForGroup(address: string, clientName: string) {
|
||||||
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
|
return this.getAcceptedShareChartData(
|
||||||
|
'AND "address" = $1 AND "clientName" = $2',
|
||||||
|
[address, clientName],
|
||||||
|
144,
|
||||||
|
CHART_WINDOW,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getChartDataForGroupByPayoutMode(address: string, clientName: string, payoutMode?: PayoutMode) {
|
||||||
|
return this.getAcceptedShareChartDataByPayoutMode({ address, clientName, payoutMode }, 144, CHART_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getChartDataForSession(clientId: string) {
|
||||||
|
return this.getAcceptedShareChartData(
|
||||||
|
'AND "clientId" = $1',
|
||||||
|
[clientId],
|
||||||
|
144,
|
||||||
|
CHART_WINDOW,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getChartDataForSessionByPayoutMode(clientId: string, payoutMode?: PayoutMode) {
|
||||||
|
return this.getAcceptedShareChartDataByPayoutMode({ clientId, payoutMode }, 144, CHART_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAcceptedShareChartData(filterSql: string, params: unknown[], limit: number, windowSql: string) {
|
||||||
const query = `
|
const query = `
|
||||||
|
WITH bounds AS (
|
||||||
SELECT
|
SELECT
|
||||||
time label,
|
NOW() - INTERVAL '${windowSql}' AS since,
|
||||||
(SUM(shares) * 4294967296) / 600 AS data
|
time_bucket(INTERVAL '10 minutes', NOW()) AS current_bucket
|
||||||
FROM
|
)
|
||||||
client_statistics_entity AS entry
|
SELECT
|
||||||
WHERE
|
"label",
|
||||||
entry.address = ? AND entry.clientName = ? AND entry.time > ${yesterday.getTime()}
|
"data",
|
||||||
GROUP BY
|
"shares",
|
||||||
time
|
"acceptedCount"
|
||||||
ORDER BY
|
FROM (
|
||||||
time
|
SELECT
|
||||||
LIMIT 144;
|
"bucket" AS "label",
|
||||||
|
ROUND((SUM("shares") * ${HASHES_PER_DIFFICULTY}) / ${CHART_BUCKET_SECONDS}) AS "data",
|
||||||
|
SUM("shares") AS "shares",
|
||||||
|
SUM("acceptedCount") AS "acceptedCount"
|
||||||
|
FROM "accepted_share_10m", bounds
|
||||||
|
WHERE "bucket" > bounds.since
|
||||||
|
AND "bucket" < bounds.current_bucket
|
||||||
|
${filterSql}
|
||||||
|
GROUP BY "bucket"
|
||||||
|
ORDER BY "bucket" DESC
|
||||||
|
LIMIT ${limit}
|
||||||
|
) AS limited_rows
|
||||||
|
ORDER BY "label"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await this.clientStatisticsRepository.query(query, [address, clientName]);
|
const result = await this.dataSource.query(query, params);
|
||||||
|
|
||||||
return result.map(res => {
|
return result.map(res => {
|
||||||
res.label = new Date(res.label).toISOString();
|
return {
|
||||||
return res;
|
label: new Date(res.label).toISOString(),
|
||||||
}).slice(0, result.length - 1);
|
data: res.data,
|
||||||
|
shares: Number(res.shares ?? 0),
|
||||||
|
acceptedCount: Number(res.acceptedCount ?? 0),
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async getAcceptedShareChartDataByPayoutMode(
|
||||||
public async getHashRateForSession(address: string, clientName: string, sessionId: string) {
|
filter: AcceptedShareChartFilter,
|
||||||
|
limit: number,
|
||||||
|
windowSql: string,
|
||||||
|
) {
|
||||||
|
const { whereSql, params } = this.buildModeChartWhere(filter);
|
||||||
const query = `
|
const query = `
|
||||||
|
WITH bounds AS (
|
||||||
SELECT
|
SELECT
|
||||||
createdAt,
|
NOW() - INTERVAL '${windowSql}' AS since,
|
||||||
updatedAt,
|
time_bucket(INTERVAL '10 minutes', NOW()) AS current_bucket
|
||||||
shares
|
)
|
||||||
FROM
|
SELECT
|
||||||
client_statistics_entity AS entry
|
"label",
|
||||||
WHERE
|
"payoutMode",
|
||||||
entry.address = ? AND entry.clientName = ? AND entry.sessionId = ?
|
"data",
|
||||||
ORDER BY time DESC
|
"shares",
|
||||||
LIMIT 2;
|
"acceptedCount"
|
||||||
|
FROM (
|
||||||
|
SELECT
|
||||||
|
"bucket" AS "label",
|
||||||
|
"payoutMode",
|
||||||
|
ROUND((SUM("shares") * ${HASHES_PER_DIFFICULTY}) / ${CHART_BUCKET_SECONDS}) AS "data",
|
||||||
|
SUM("shares") AS "shares",
|
||||||
|
SUM("acceptedCount") AS "acceptedCount"
|
||||||
|
FROM "accepted_share_10m", bounds
|
||||||
|
WHERE "bucket" > bounds.since
|
||||||
|
AND "bucket" < bounds.current_bucket
|
||||||
|
${whereSql}
|
||||||
|
GROUP BY "bucket", "payoutMode"
|
||||||
|
ORDER BY "bucket" DESC
|
||||||
|
LIMIT ${limit * 2}
|
||||||
|
) AS limited_rows
|
||||||
|
ORDER BY "label", "payoutMode"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await this.clientStatisticsRepository.query(query, [address, clientName, sessionId]);
|
const result = await this.dataSource.query(query, params);
|
||||||
|
|
||||||
if (result.length < 1) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const latestStat = result[0];
|
|
||||||
|
|
||||||
if (result.length < 2) {
|
|
||||||
const time = new Date(latestStat.updatedAt).getTime() - new Date(latestStat.createdAt).getTime();
|
|
||||||
if (time < 1) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return (latestStat.shares * 4294967296) / (time / 1000);
|
|
||||||
} else {
|
|
||||||
const secondLatestStat = result[1];
|
|
||||||
const time = new Date(latestStat.updatedAt).getTime() - new Date(secondLatestStat.createdAt).getTime();
|
|
||||||
if (time < 1) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return ((latestStat.shares + secondLatestStat.shares) * 4294967296) / (time / 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getChartDataForSession(address: string, clientName: string, sessionId: string) {
|
|
||||||
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
SELECT
|
|
||||||
time label,
|
|
||||||
(SUM(shares) * 4294967296) / 600 AS data
|
|
||||||
FROM
|
|
||||||
client_statistics_entity AS entry
|
|
||||||
WHERE
|
|
||||||
entry.address = ? AND entry.clientName = ? AND entry.sessionId = ? AND entry.time > ${yesterday.getTime()}
|
|
||||||
GROUP BY
|
|
||||||
time
|
|
||||||
ORDER BY
|
|
||||||
time
|
|
||||||
LIMIT 144;
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await this.clientStatisticsRepository.query(query, [address, clientName, sessionId]);
|
|
||||||
|
|
||||||
return result.map(res => {
|
return result.map(res => {
|
||||||
res.label = new Date(res.label).toISOString();
|
return {
|
||||||
return res;
|
label: new Date(res.label).toISOString(),
|
||||||
}).slice(0, result.length - 1);
|
payoutMode: res.payoutMode,
|
||||||
|
data: res.data,
|
||||||
|
shares: Number(res.shares ?? 0),
|
||||||
|
acceptedCount: Number(res.acceptedCount ?? 0),
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteAll() {
|
private buildModeChartWhere(filter: AcceptedShareChartFilter): { whereSql: string; params: string[] } {
|
||||||
return await this.clientStatisticsRepository.delete({})
|
const where: string[] = [];
|
||||||
|
const params: string[] = [];
|
||||||
|
|
||||||
|
if (filter.address != null) {
|
||||||
|
params.push(filter.address);
|
||||||
|
where.push(`"address" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.clientName != null) {
|
||||||
|
params.push(filter.clientName);
|
||||||
|
where.push(`"clientName" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.clientId != null) {
|
||||||
|
params.push(filter.clientId);
|
||||||
|
where.push(`"clientId" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.payoutMode != null) {
|
||||||
|
params.push(normalizePayoutMode(filter.payoutMode));
|
||||||
|
where.push(`"payoutMode" = $${params.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
whereSql: where.length > 0 ? `AND ${where.join(' AND ')}` : '',
|
||||||
|
params,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,41 +1,45 @@
|
|||||||
import { Column, Entity, Index, PrimaryColumn } from 'typeorm';
|
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
import { DateTimeTransformer } from '../utils/DateTimeTransformer';
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
||||||
|
|
||||||
//https://www.sqlite.org/withoutrowid.html
|
|
||||||
|
|
||||||
//The WITHOUT ROWID optimization is likely to be helpful for tables that have non-integer
|
@Entity()
|
||||||
// or composite (multi-column) PRIMARY KEYs and that do not store large strings or BLOBs.
|
@Index("IDX_unique_nonce", { synchronize: false })
|
||||||
//WITHOUT ROWID tables work best when individual rows are not too large.
|
@Index('idx_client_cleanup', ['id'], {
|
||||||
@Entity({ withoutRowid: true })
|
where: '"deletedAt" IS NULL',
|
||||||
@Index(['address', 'clientName', 'sessionId'], { unique: true })
|
// This is a partial (filtered) index — only indexes active clients
|
||||||
|
})
|
||||||
export class ClientEntity extends TrackedEntity {
|
export class ClientEntity extends TrackedEntity {
|
||||||
|
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
@PrimaryColumn({ length: 62, type: 'varchar' })
|
@Index()
|
||||||
|
@Column({ length: 62, type: 'varchar' })
|
||||||
address: string;
|
address: string;
|
||||||
|
|
||||||
@PrimaryColumn({ length: 64, type: 'varchar' })
|
@Column({ length: 64, type: 'varchar' })
|
||||||
clientName: string;
|
clientName: string;
|
||||||
|
|
||||||
@PrimaryColumn({ length: 8, type: 'varchar' })
|
@Column({ length: 8, type: 'varchar', })
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'solo' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
|
|
||||||
@Column({ length: 128, type: 'varchar', nullable: true })
|
@Column({ length: 128, type: 'varchar', nullable: true })
|
||||||
userAgent: string;
|
userAgent: string;
|
||||||
|
|
||||||
|
|
||||||
|
@Column()
|
||||||
@Column({ type: 'datetime', transformer: new DateTimeTransformer() })
|
|
||||||
startTime: Date;
|
startTime: Date;
|
||||||
|
|
||||||
@Column({ type: 'real', default: 0 })
|
@Column({ type: 'decimal', default: 0 })
|
||||||
bestDifficulty: number
|
bestDifficulty: number
|
||||||
|
|
||||||
@Column({ default: 0 })
|
@Column({ default: 0, type: 'decimal' })
|
||||||
hashRate: number;
|
hashRate: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,14 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { Interval } from '@nestjs/schedule';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { BehaviorSubject, firstValueFrom } from 'rxjs';
|
import { In, Repository } from 'typeorm';
|
||||||
import { ObjectLiteral, Repository } from 'typeorm';
|
|
||||||
|
|
||||||
import { ClientEntity } from './client.entity';
|
import { ClientEntity } from './client.entity';
|
||||||
|
|
||||||
|
const DEFAULT_CLIENT_ACTIVE_WINDOW_MS = 30 * 60 * 1000;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ClientService {
|
export class ClientService {
|
||||||
|
private readonly activeWindowMs = this.readPositiveInt('CLIENT_REPORT_ACTIVE_WINDOW_MS', DEFAULT_CLIENT_ACTIVE_WINDOW_MS);
|
||||||
|
|
||||||
public insertQueue: { result: BehaviorSubject<ObjectLiteral | null>, partialClient: Partial<ClientEntity> }[] = [];
|
|
||||||
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(ClientEntity)
|
@InjectRepository(ClientEntity)
|
||||||
@@ -22,59 +17,19 @@ export class ClientService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Interval(1000 * 5)
|
|
||||||
public async insertClients() {
|
|
||||||
const queueCopy = [...this.insertQueue];
|
|
||||||
this.insertQueue = [];
|
|
||||||
|
|
||||||
const results = await this.clientRepository.insert(queueCopy.map(c => c.partialClient));
|
|
||||||
|
|
||||||
queueCopy.forEach((c, index) => {
|
|
||||||
c.result.next(results.generatedMaps[index]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public async killDeadClients() {
|
|
||||||
var fiveMinutes = new Date(new Date().getTime() - (5 * 60 * 1000)).toISOString();
|
|
||||||
|
|
||||||
return await this.clientRepository
|
|
||||||
.createQueryBuilder()
|
|
||||||
.update(ClientEntity)
|
|
||||||
.set({ deletedAt: () => "DATETIME('now')" })
|
|
||||||
.where("deletedAt IS NULL AND updatedAt < DATETIME(:fiveMinutes)", { fiveMinutes })
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async heartbeat(address: string, clientName: string, sessionId: string, hashRate: number, updatedAt: Date) {
|
|
||||||
return await this.clientRepository.update({ address, clientName, sessionId }, { hashRate, deletedAt: null, updatedAt });
|
|
||||||
}
|
|
||||||
|
|
||||||
// public async save(client: Partial<ClientEntity>) {
|
|
||||||
// return await this.clientRepository.save(client);
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
public async insert(partialClient: Partial<ClientEntity>): Promise<ClientEntity> {
|
public async insert(partialClient: Partial<ClientEntity>): Promise<ClientEntity> {
|
||||||
|
const insertResult = await this.clientRepository.insert(partialClient);
|
||||||
const result = new BehaviorSubject(null);
|
|
||||||
|
|
||||||
this.insertQueue.push({ result, partialClient });
|
|
||||||
|
|
||||||
|
|
||||||
// const insertResult = await this.clientRepository.insert(partialClient);
|
|
||||||
|
|
||||||
const generatedMap = await firstValueFrom(result);
|
|
||||||
|
|
||||||
const client = {
|
const client = {
|
||||||
...partialClient,
|
...partialClient,
|
||||||
...generatedMap
|
...insertResult.generatedMaps[0]
|
||||||
};
|
};
|
||||||
|
|
||||||
return client as ClientEntity;
|
return client as ClientEntity;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async delete(sessionId: string) {
|
public async delete(id: string) {
|
||||||
return await this.clientRepository.softDelete({ sessionId });
|
return await this.clientRepository.softDelete({ id });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteOldClients() {
|
public async deleteOldClients() {
|
||||||
@@ -90,19 +45,55 @@ export class ClientService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateBestDifficulty(sessionId: string, bestDifficulty: number) {
|
public async updateBestDifficulty(id: string, bestDifficulty: number) {
|
||||||
return await this.clientRepository.update({ sessionId }, { bestDifficulty });
|
return await this.clientRepository.update({ id }, { bestDifficulty });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async updateBestDifficultyIfHigher(id: string, bestDifficulty: number) {
|
||||||
|
return await this.clientRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(ClientEntity)
|
||||||
|
.set({ bestDifficulty })
|
||||||
|
.where('id = :id', { id })
|
||||||
|
.andWhere('"bestDifficulty" < :bestDifficulty', { bestDifficulty })
|
||||||
|
.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async updateHashRate(id: string, hashRate: number, updatedAt = new Date()) {
|
||||||
|
return await this.clientRepository.update({ id }, { hashRate, updatedAt, deletedAt: null });
|
||||||
|
}
|
||||||
|
|
||||||
public async connectedClientCount(): Promise<number> {
|
public async connectedClientCount(): Promise<number> {
|
||||||
return await this.clientRepository.count();
|
return await this.clientRepository.count();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getByAddress(address: string): Promise<ClientEntity[]> {
|
public async getActiveIds(ids: string[]): Promise<Set<string>> {
|
||||||
return await this.clientRepository.find({
|
if (ids.length === 0) {
|
||||||
where: {
|
return new Set();
|
||||||
address
|
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
const clients = await this.clientRepository.find({
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
},
|
||||||
|
where: {
|
||||||
|
id: In(ids),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Set(clients.map(client => client.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getByAddress(address: string): Promise<ClientEntity[]> {
|
||||||
|
const activeSince = new Date(Date.now() - this.activeWindowMs);
|
||||||
|
return await this.clientRepository
|
||||||
|
.createQueryBuilder('client')
|
||||||
|
.where('client.address = :address', { address })
|
||||||
|
.andWhere('client.deletedAt IS NULL')
|
||||||
|
.andWhere('client.updatedAt > :activeSince', { activeSince })
|
||||||
|
.andWhere('client.hashRate > 0')
|
||||||
|
.orderBy('client.updatedAt', 'DESC')
|
||||||
|
.getMany();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -126,19 +117,32 @@ export class ClientService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async deleteAll() {
|
public async deleteAll() {
|
||||||
return await this.clientRepository.softDelete({})
|
return await this.clientRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.delete()
|
||||||
|
.from(ClientEntity)
|
||||||
|
.where('"deletedAt" IS NULL')
|
||||||
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getUserAgents() {
|
// public async getUserAgents() {
|
||||||
const result = await this.clientRepository.createQueryBuilder('client')
|
// const result = await this.clientRepository.createQueryBuilder('client')
|
||||||
.select('client.userAgent as userAgent')
|
// .select('client.userAgent as "userAgent"')
|
||||||
.addSelect('COUNT(client.userAgent)', 'count')
|
// .addSelect('COUNT(client.userAgent)', 'count')
|
||||||
.addSelect('MAX(client.bestDifficulty)', 'bestDifficulty')
|
// .addSelect('MAX(client.bestDifficulty)', 'bestDifficulty')
|
||||||
.addSelect('SUM(client.hashRate)', 'totalHashRate')
|
// .addSelect('SUM(client.hashRate)', 'totalHashRate')
|
||||||
.groupBy('client.userAgent')
|
// .groupBy('client.userAgent')
|
||||||
.orderBy('count', 'DESC')
|
// .orderBy('"totalHashRate"', 'DESC')
|
||||||
.getRawMany();
|
// .getRawMany();
|
||||||
return result;
|
// return result;
|
||||||
|
// }
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
if (Number.isInteger(value) && value > 0) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { Column, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
|
||||||
|
|
||||||
|
const bigintTransformer = {
|
||||||
|
from: (value: string | number | null): number => Number(value ?? 0),
|
||||||
|
to: (value: number): number => Math.trunc(value ?? 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
@Entity({ name: 'payout_balance' })
|
||||||
|
export class PayoutBalanceEntity {
|
||||||
|
@PrimaryColumn({ length: 62, type: 'varchar' })
|
||||||
|
address: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0, transformer: bigintTransformer })
|
||||||
|
balanceSats: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0, transformer: bigintTransformer })
|
||||||
|
totalPaidSats: number;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', nullable: true })
|
||||||
|
lastAcceptedShareAt: Date | null;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { buildPayoutDistribution } from './payout-distribution';
|
||||||
|
|
||||||
|
const ADDRESS_A = 'bc1qs29kyaqqc0fkvj897ke9e5xa9utljjey0y5jjn';
|
||||||
|
const ADDRESS_B = 'bc1q99n3pu025yyu0jlywpmwzalyhm36tg5u37w20d';
|
||||||
|
const ADDRESS_C = 'bc1q7yx4d3xspf4xvssmsm4prf4mg2slkv8jtkc5l6';
|
||||||
|
|
||||||
|
describe('buildPayoutDistribution', () => {
|
||||||
|
it('should conserve the full coinbase reward across outputs', () => {
|
||||||
|
const result = buildPayoutDistribution({
|
||||||
|
addressWork: [
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 2, acceptedShareCount: 2 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 1, acceptedShareCount: 1 },
|
||||||
|
],
|
||||||
|
balances: [],
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
feePercent: 0,
|
||||||
|
minOutputSats: 546,
|
||||||
|
coinbaseWeightBudget: 50_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.payoutOutputs.map(entry => ({
|
||||||
|
address: entry.address,
|
||||||
|
payoutSats: entry.payoutSats,
|
||||||
|
balanceAfterSats: entry.balanceAfterSats,
|
||||||
|
}))).toEqual([
|
||||||
|
{ address: ADDRESS_A, payoutSats: 667, balanceAfterSats: 0 },
|
||||||
|
{ address: ADDRESS_B, payoutSats: 333, balanceAfterSats: 0 },
|
||||||
|
]);
|
||||||
|
expect(result.distributedSats).toBe(1000);
|
||||||
|
expect(result.unallocatedRemainderSats).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should include small active miner payouts instead of reallocating their work', () => {
|
||||||
|
const result = buildPayoutDistribution({
|
||||||
|
addressWork: [
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 999, acceptedShareCount: 999 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 1, acceptedShareCount: 1 },
|
||||||
|
],
|
||||||
|
balances: [],
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
feePercent: 0,
|
||||||
|
minOutputSats: 546,
|
||||||
|
coinbaseWeightBudget: 50_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const pending = result.entries.find(entry => entry.address === ADDRESS_B);
|
||||||
|
const paid = result.entries.find(entry => entry.address === ADDRESS_A);
|
||||||
|
|
||||||
|
expect(pending).toEqual(expect.objectContaining({
|
||||||
|
includedInCoinbase: true,
|
||||||
|
grossPayoutSats: 1,
|
||||||
|
payoutSats: 1,
|
||||||
|
balanceAfterSats: 0,
|
||||||
|
}));
|
||||||
|
expect(paid).toEqual(expect.objectContaining({
|
||||||
|
includedInCoinbase: true,
|
||||||
|
payoutSats: 999,
|
||||||
|
balanceAfterSats: 0,
|
||||||
|
}));
|
||||||
|
expect(result.distributedSats).toBe(1000);
|
||||||
|
expect(result.unallocatedRemainderSats).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should trim outputs that do not fit the coinbase weight budget', () => {
|
||||||
|
const result = buildPayoutDistribution({
|
||||||
|
addressWork: [
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 10, acceptedShareCount: 1 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 9, acceptedShareCount: 1 },
|
||||||
|
{ address: ADDRESS_C, creditedDifficulty: 8, acceptedShareCount: 1 },
|
||||||
|
],
|
||||||
|
balances: [],
|
||||||
|
coinbaseValueSats: 3000,
|
||||||
|
feePercent: 0,
|
||||||
|
minOutputSats: 546,
|
||||||
|
coinbaseWeightBudget: 850,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.payoutOutputs).toHaveLength(1);
|
||||||
|
expect(result.payoutOutputs[0].address).toBe(ADDRESS_A);
|
||||||
|
expect(result.payoutOutputs[0]).toEqual(expect.objectContaining({
|
||||||
|
payoutSats: 3000,
|
||||||
|
balanceAfterSats: -1889,
|
||||||
|
}));
|
||||||
|
expect(result.entries.find(entry => entry.address === ADDRESS_B))
|
||||||
|
.toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 1000 }));
|
||||||
|
expect(result.entries.find(entry => entry.address === ADDRESS_C))
|
||||||
|
.toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 889 }));
|
||||||
|
expect(result.distributedSats).toBe(3000);
|
||||||
|
expect(result.unallocatedRemainderSats).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should apply positive and negative carried balances to the next distribution', () => {
|
||||||
|
const result = buildPayoutDistribution({
|
||||||
|
addressWork: [
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 10, acceptedShareCount: 1 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 10, acceptedShareCount: 1 },
|
||||||
|
],
|
||||||
|
balances: [
|
||||||
|
{ address: ADDRESS_A, balanceSats: 100 },
|
||||||
|
{ address: ADDRESS_B, balanceSats: -100 },
|
||||||
|
],
|
||||||
|
coinbaseValueSats: 2000,
|
||||||
|
feePercent: 0,
|
||||||
|
minOutputSats: 546,
|
||||||
|
coinbaseWeightBudget: 50_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.payoutOutputs.map(entry => ({
|
||||||
|
address: entry.address,
|
||||||
|
payoutSats: entry.payoutSats,
|
||||||
|
balanceAfterSats: entry.balanceAfterSats,
|
||||||
|
}))).toEqual([
|
||||||
|
{ address: ADDRESS_A, payoutSats: 1100, balanceAfterSats: 0 },
|
||||||
|
{ address: ADDRESS_B, payoutSats: 900, balanceAfterSats: 0 },
|
||||||
|
]);
|
||||||
|
expect(result.unallocatedRemainderSats).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reserve a configured fee output before miner distribution', () => {
|
||||||
|
const result = buildPayoutDistribution({
|
||||||
|
addressWork: [
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 1, acceptedShareCount: 1 },
|
||||||
|
],
|
||||||
|
balances: [],
|
||||||
|
coinbaseValueSats: 100000,
|
||||||
|
feeAddress: ADDRESS_C,
|
||||||
|
feePercent: 2,
|
||||||
|
minOutputSats: 546,
|
||||||
|
coinbaseWeightBudget: 50_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.payoutOutputs[0]).toEqual(expect.objectContaining({
|
||||||
|
address: ADDRESS_C,
|
||||||
|
payoutSats: 2000,
|
||||||
|
}));
|
||||||
|
expect(result.payoutOutputs[1]).toEqual(expect.objectContaining({
|
||||||
|
address: ADDRESS_A,
|
||||||
|
payoutSats: 98000,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
import { AddressType, getAddressInfo } from 'bitcoin-address-validation';
|
||||||
|
|
||||||
|
export interface PayoutAddressWork {
|
||||||
|
address: string;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
acceptedShareCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayoutBalanceInput {
|
||||||
|
address: string;
|
||||||
|
balanceSats: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayoutDistributionEntry {
|
||||||
|
address: string;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
acceptedShareCount: number;
|
||||||
|
payoutWeight: number;
|
||||||
|
grossPayoutSats: number;
|
||||||
|
payoutSats: number;
|
||||||
|
balanceBeforeSats: number;
|
||||||
|
balanceAfterSats: number;
|
||||||
|
includedInCoinbase: boolean;
|
||||||
|
rank: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayoutDistributionResult {
|
||||||
|
entries: PayoutDistributionEntry[];
|
||||||
|
payoutOutputs: PayoutDistributionEntry[];
|
||||||
|
consideredAddressCount: number;
|
||||||
|
distributedSats: number;
|
||||||
|
unallocatedRemainderSats: number;
|
||||||
|
feeSats: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayoutDistributionInput {
|
||||||
|
addressWork: PayoutAddressWork[];
|
||||||
|
balances: PayoutBalanceInput[];
|
||||||
|
coinbaseValueSats: number;
|
||||||
|
feeAddress?: string;
|
||||||
|
feePercent: number;
|
||||||
|
minOutputSats: number;
|
||||||
|
coinbaseWeightBudget: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_COINBASE_WEIGHT_BUDGET = 50_000;
|
||||||
|
const DUST_LIMIT_SATS = 546;
|
||||||
|
const COINBASE_BASE_WEIGHT = 328;
|
||||||
|
const COINBASE_WITNESS_COMMITMENT_WEIGHT = 188;
|
||||||
|
const COINBASE_OUTPUT_WEIGHT = 172;
|
||||||
|
const BUDGET_SAFETY_MARGIN_WEIGHT = 200;
|
||||||
|
|
||||||
|
const OUTPUT_WEIGHT_BY_TYPE: Record<string, number> = {
|
||||||
|
[AddressType.p2wpkh]: 124,
|
||||||
|
[AddressType.p2sh]: 128,
|
||||||
|
[AddressType.p2pkh]: 136,
|
||||||
|
[AddressType.p2wsh]: 172,
|
||||||
|
[AddressType.p2tr]: 172,
|
||||||
|
};
|
||||||
|
|
||||||
|
const outputWeightCache = new Map<string, number>();
|
||||||
|
|
||||||
|
interface ComputedAddress {
|
||||||
|
address: string;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
acceptedShareCount: number;
|
||||||
|
payoutWeight: number;
|
||||||
|
rawFairSats: number;
|
||||||
|
balanceBeforeSats: number;
|
||||||
|
targetSats: number;
|
||||||
|
payoutSats: number;
|
||||||
|
balanceAfterSats: number;
|
||||||
|
includedInCoinbase: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AllocationTarget<T> {
|
||||||
|
item: T;
|
||||||
|
weight: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutDistributionResult {
|
||||||
|
const coinbaseValueSats = Math.max(0, Math.floor(input.coinbaseValueSats));
|
||||||
|
const minOutputSats = Math.max(DUST_LIMIT_SATS, Math.floor(input.minOutputSats));
|
||||||
|
const coinbaseWeightBudget = input.coinbaseWeightBudget > 0
|
||||||
|
? input.coinbaseWeightBudget
|
||||||
|
: DEFAULT_COINBASE_WEIGHT_BUDGET;
|
||||||
|
const feePercent = Number.isFinite(input.feePercent) && input.feePercent > 0
|
||||||
|
? input.feePercent
|
||||||
|
: 0;
|
||||||
|
const feeAddress = input.feeAddress?.trim() ?? '';
|
||||||
|
const wantedFeeSats = Math.floor((feePercent / 100) * coinbaseValueSats);
|
||||||
|
const feeSats = feeAddress.length > 0 && wantedFeeSats >= minOutputSats ? wantedFeeSats : 0;
|
||||||
|
const minerRewardSats = coinbaseValueSats - feeSats;
|
||||||
|
|
||||||
|
const workByAddress = new Map<string, { creditedDifficulty: number; acceptedShareCount: number }>();
|
||||||
|
for (const work of input.addressWork) {
|
||||||
|
if (!work.address || !Number.isFinite(work.creditedDifficulty) || work.creditedDifficulty <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const existing = workByAddress.get(work.address) ?? { creditedDifficulty: 0, acceptedShareCount: 0 };
|
||||||
|
existing.creditedDifficulty += work.creditedDifficulty;
|
||||||
|
existing.acceptedShareCount += work.acceptedShareCount;
|
||||||
|
workByAddress.set(work.address, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
const balanceByAddress = new Map<string, number>();
|
||||||
|
for (const balance of input.balances) {
|
||||||
|
if (balance.address && Number.isFinite(balance.balanceSats) && balance.balanceSats !== 0) {
|
||||||
|
balanceByAddress.set(balance.address, Math.trunc(balance.balanceSats));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let totalCreditedDifficulty = 0;
|
||||||
|
for (const work of workByAddress.values()) {
|
||||||
|
totalCreditedDifficulty += work.creditedDifficulty;
|
||||||
|
}
|
||||||
|
if (coinbaseValueSats <= 0 || totalCreditedDifficulty <= 0) {
|
||||||
|
return {
|
||||||
|
entries: [],
|
||||||
|
payoutOutputs: [],
|
||||||
|
consideredAddressCount: 0,
|
||||||
|
distributedSats: 0,
|
||||||
|
unallocatedRemainderSats: coinbaseValueSats,
|
||||||
|
feeSats,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const fairShareSats = allocateIntegerSats(
|
||||||
|
[...workByAddress.entries()].map(([address, work]) => ({
|
||||||
|
item: address,
|
||||||
|
weight: work.creditedDifficulty,
|
||||||
|
})),
|
||||||
|
minerRewardSats,
|
||||||
|
totalCreditedDifficulty,
|
||||||
|
);
|
||||||
|
|
||||||
|
const computations = new Map<string, ComputedAddress>();
|
||||||
|
const considered = new Set<string>([...workByAddress.keys(), ...balanceByAddress.keys()]);
|
||||||
|
|
||||||
|
for (const address of considered) {
|
||||||
|
const work = workByAddress.get(address);
|
||||||
|
const creditedDifficulty = work?.creditedDifficulty ?? 0;
|
||||||
|
const acceptedShareCount = work?.acceptedShareCount ?? 0;
|
||||||
|
const payoutWeight = creditedDifficulty > 0 ? creditedDifficulty / totalCreditedDifficulty : 0;
|
||||||
|
const rawFairSats = fairShareSats.get(address) ?? 0;
|
||||||
|
const balanceBeforeSats = balanceByAddress.get(address) ?? 0;
|
||||||
|
const targetSats = rawFairSats + balanceBeforeSats;
|
||||||
|
computations.set(address, {
|
||||||
|
address,
|
||||||
|
creditedDifficulty,
|
||||||
|
acceptedShareCount,
|
||||||
|
payoutWeight,
|
||||||
|
rawFairSats,
|
||||||
|
balanceBeforeSats,
|
||||||
|
targetSats,
|
||||||
|
payoutSats: 0,
|
||||||
|
balanceAfterSats: targetSats,
|
||||||
|
includedInCoinbase: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const feeWeight = feeSats > 0 ? outputWeightForAddress(feeAddress) : 0;
|
||||||
|
let usedWeight = COINBASE_BASE_WEIGHT + COINBASE_WITNESS_COMMITMENT_WEIGHT + feeWeight;
|
||||||
|
const effectiveBudget = coinbaseWeightBudget - BUDGET_SAFETY_MARGIN_WEIGHT;
|
||||||
|
allocatePayoutTargets(computations, minerRewardSats, totalCreditedDifficulty);
|
||||||
|
|
||||||
|
const eligible = [...computations.values()]
|
||||||
|
.filter(row => row.payoutSats > 0 && (row.creditedDifficulty > 0 || row.payoutSats >= minOutputSats))
|
||||||
|
.sort((a, b) => b.payoutSats - a.payoutSats || b.targetSats - a.targetSats || a.address.localeCompare(b.address));
|
||||||
|
|
||||||
|
for (const row of eligible) {
|
||||||
|
const outputWeight = outputWeightForAddress(row.address);
|
||||||
|
if (usedWeight + outputWeight > effectiveBudget) {
|
||||||
|
row.balanceAfterSats = row.targetSats;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
row.includedInCoinbase = true;
|
||||||
|
row.balanceAfterSats = row.targetSats - row.payoutSats;
|
||||||
|
usedWeight += outputWeight;
|
||||||
|
}
|
||||||
|
for (const row of computations.values()) {
|
||||||
|
if (!row.includedInCoinbase && row.payoutSats > 0) {
|
||||||
|
row.payoutSats = 0;
|
||||||
|
row.balanceAfterSats = row.targetSats;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
redistributeUnfitMinerPayouts(computations, minerRewardSats);
|
||||||
|
|
||||||
|
const feeEntry = feeSats > 0
|
||||||
|
? {
|
||||||
|
address: feeAddress,
|
||||||
|
creditedDifficulty: 0,
|
||||||
|
acceptedShareCount: 0,
|
||||||
|
payoutWeight: 0,
|
||||||
|
grossPayoutSats: feeSats,
|
||||||
|
payoutSats: feeSats,
|
||||||
|
balanceBeforeSats: 0,
|
||||||
|
balanceAfterSats: 0,
|
||||||
|
includedInCoinbase: true,
|
||||||
|
rank: 1,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const minerEntries = [...computations.values()]
|
||||||
|
.filter(row => row.includedInCoinbase || row.balanceBeforeSats !== row.balanceAfterSats || row.balanceAfterSats !== 0)
|
||||||
|
.sort((a, b) => {
|
||||||
|
if (a.includedInCoinbase !== b.includedInCoinbase) {
|
||||||
|
return a.includedInCoinbase ? -1 : 1;
|
||||||
|
}
|
||||||
|
return b.payoutSats - a.payoutSats || b.targetSats - a.targetSats || a.address.localeCompare(b.address);
|
||||||
|
})
|
||||||
|
.map(row => ({
|
||||||
|
address: row.address,
|
||||||
|
creditedDifficulty: row.creditedDifficulty,
|
||||||
|
acceptedShareCount: row.acceptedShareCount,
|
||||||
|
payoutWeight: row.payoutWeight,
|
||||||
|
grossPayoutSats: row.rawFairSats,
|
||||||
|
payoutSats: row.payoutSats,
|
||||||
|
balanceBeforeSats: row.balanceBeforeSats,
|
||||||
|
balanceAfterSats: row.balanceAfterSats,
|
||||||
|
includedInCoinbase: row.includedInCoinbase,
|
||||||
|
rank: 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mergedEntries = feeEntry == null
|
||||||
|
? minerEntries
|
||||||
|
: mergeFeeEntry(feeEntry, minerEntries);
|
||||||
|
const entries = mergedEntries
|
||||||
|
.map((entry, index) => ({ ...entry, rank: index + 1 }));
|
||||||
|
const payoutOutputs = entries.filter(entry => entry.includedInCoinbase);
|
||||||
|
const distributedSats = payoutOutputs.reduce((sum, entry) => sum + entry.payoutSats, 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
entries,
|
||||||
|
payoutOutputs,
|
||||||
|
consideredAddressCount: considered.size,
|
||||||
|
distributedSats,
|
||||||
|
unallocatedRemainderSats: coinbaseValueSats - distributedSats,
|
||||||
|
feeSats,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function allocatePayoutTargets(
|
||||||
|
computations: Map<string, ComputedAddress>,
|
||||||
|
minerRewardSats: number,
|
||||||
|
totalCreditedDifficulty: number,
|
||||||
|
): void {
|
||||||
|
const positiveTargets = [...computations.values()]
|
||||||
|
.filter(row => row.targetSats > 0);
|
||||||
|
const totalPositiveTarget = positiveTargets.reduce((sum, row) => sum + row.targetSats, 0);
|
||||||
|
|
||||||
|
if (totalPositiveTarget <= 0) {
|
||||||
|
const activeRows = [...computations.values()]
|
||||||
|
.filter(row => row.creditedDifficulty > 0);
|
||||||
|
const activeAllocations = allocateIntegerSats(
|
||||||
|
activeRows.map(row => ({ item: row.address, weight: row.creditedDifficulty })),
|
||||||
|
minerRewardSats,
|
||||||
|
totalCreditedDifficulty,
|
||||||
|
);
|
||||||
|
for (const row of activeRows) {
|
||||||
|
row.payoutSats = activeAllocations.get(row.address) ?? 0;
|
||||||
|
row.balanceAfterSats = row.targetSats - row.payoutSats;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalPositiveTarget <= minerRewardSats) {
|
||||||
|
for (const row of positiveTargets) {
|
||||||
|
row.payoutSats = row.targetSats;
|
||||||
|
row.balanceAfterSats = 0;
|
||||||
|
}
|
||||||
|
const surplus = minerRewardSats - totalPositiveTarget;
|
||||||
|
if (surplus <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const activeRows = positiveTargets.filter(row => row.creditedDifficulty > 0);
|
||||||
|
const activeWeight = activeRows.reduce((sum, row) => sum + row.creditedDifficulty, 0);
|
||||||
|
const surplusAllocations = allocateIntegerSats(
|
||||||
|
activeRows.map(row => ({ item: row.address, weight: row.creditedDifficulty })),
|
||||||
|
surplus,
|
||||||
|
activeWeight,
|
||||||
|
);
|
||||||
|
for (const row of activeRows) {
|
||||||
|
const extra = surplusAllocations.get(row.address) ?? 0;
|
||||||
|
row.payoutSats += extra;
|
||||||
|
row.balanceAfterSats -= extra;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cappedAllocations = allocateIntegerSats(
|
||||||
|
positiveTargets.map(row => ({ item: row.address, weight: row.targetSats })),
|
||||||
|
minerRewardSats,
|
||||||
|
totalPositiveTarget,
|
||||||
|
);
|
||||||
|
for (const row of positiveTargets) {
|
||||||
|
row.payoutSats = cappedAllocations.get(row.address) ?? 0;
|
||||||
|
row.balanceAfterSats = row.targetSats - row.payoutSats;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function redistributeUnfitMinerPayouts(
|
||||||
|
computations: Map<string, ComputedAddress>,
|
||||||
|
minerRewardSats: number,
|
||||||
|
): void {
|
||||||
|
const distributedToMiners = [...computations.values()]
|
||||||
|
.filter(row => row.includedInCoinbase)
|
||||||
|
.reduce((sum, row) => sum + row.payoutSats, 0);
|
||||||
|
const remainder = minerRewardSats - distributedToMiners;
|
||||||
|
if (remainder <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keptActive = [...computations.values()]
|
||||||
|
.filter(row => row.includedInCoinbase && row.creditedDifficulty > 0);
|
||||||
|
const keptDifficulty = keptActive.reduce((sum, row) => sum + row.creditedDifficulty, 0);
|
||||||
|
if (keptDifficulty <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bonusAllocations = allocateIntegerSats(
|
||||||
|
keptActive.map(row => ({ item: row.address, weight: row.creditedDifficulty })),
|
||||||
|
remainder,
|
||||||
|
keptDifficulty,
|
||||||
|
);
|
||||||
|
for (const row of keptActive) {
|
||||||
|
const bonus = bonusAllocations.get(row.address) ?? 0;
|
||||||
|
row.payoutSats += bonus;
|
||||||
|
row.balanceAfterSats -= bonus;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function allocateIntegerSats<T extends string>(
|
||||||
|
targets: AllocationTarget<T>[],
|
||||||
|
amountSats: number,
|
||||||
|
totalWeight: number,
|
||||||
|
): Map<T, number> {
|
||||||
|
const result = new Map<T, number>();
|
||||||
|
if (amountSats <= 0 || totalWeight <= 0) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
let assigned = 0;
|
||||||
|
const fractions = targets
|
||||||
|
.filter(target => target.weight > 0)
|
||||||
|
.map(target => {
|
||||||
|
const exact = (target.weight * amountSats) / totalWeight;
|
||||||
|
const whole = Math.floor(exact);
|
||||||
|
assigned += whole;
|
||||||
|
result.set(target.item, whole);
|
||||||
|
return {
|
||||||
|
item: target.item,
|
||||||
|
weight: target.weight,
|
||||||
|
fraction: exact - whole,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.fraction - a.fraction || b.weight - a.weight || a.item.localeCompare(b.item));
|
||||||
|
|
||||||
|
let residual = amountSats - assigned;
|
||||||
|
for (const target of fractions) {
|
||||||
|
if (residual <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
result.set(target.item, (result.get(target.item) ?? 0) + 1);
|
||||||
|
residual--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeFeeEntry(
|
||||||
|
feeEntry: PayoutDistributionEntry,
|
||||||
|
minerEntries: Omit<PayoutDistributionEntry, 'rank'>[],
|
||||||
|
): Omit<PayoutDistributionEntry, 'rank'>[] {
|
||||||
|
const existing = minerEntries.find(entry => entry.address === feeEntry.address && entry.includedInCoinbase);
|
||||||
|
if (existing == null) {
|
||||||
|
return [feeEntry, ...minerEntries];
|
||||||
|
}
|
||||||
|
existing.payoutSats += feeEntry.payoutSats;
|
||||||
|
existing.grossPayoutSats += feeEntry.grossPayoutSats;
|
||||||
|
return minerEntries;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function outputWeightForAddress(address: string): number {
|
||||||
|
if (!address) {
|
||||||
|
return COINBASE_OUTPUT_WEIGHT;
|
||||||
|
}
|
||||||
|
const cached = outputWeightCache.get(address);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
let weight = COINBASE_OUTPUT_WEIGHT;
|
||||||
|
try {
|
||||||
|
const info = getAddressInfo(address);
|
||||||
|
weight = OUTPUT_WEIGHT_BY_TYPE[info.type] ?? COINBASE_OUTPUT_WEIGHT;
|
||||||
|
} catch {
|
||||||
|
weight = COINBASE_OUTPUT_WEIGHT;
|
||||||
|
}
|
||||||
|
outputWeightCache.set(address, weight);
|
||||||
|
return weight;
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
const bigintTransformer = {
|
||||||
|
from: (value: string | number | null): number => Number(value ?? 0),
|
||||||
|
to: (value: number): number => Math.trunc(value ?? 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
@Entity({ name: 'payout_history' })
|
||||||
|
@Index('UQ_payout_history_block_address', ['payoutMode', 'blockHeight', 'address'], { unique: true })
|
||||||
|
@Index('IDX_payout_history_address_created', ['address', 'createdAt'])
|
||||||
|
export class PayoutHistoryEntity {
|
||||||
|
@PrimaryGeneratedColumn({ type: 'bigint' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
blockHeight: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
payoutSnapshotId: string;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'pplns' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
|
@Column({ length: 62, type: 'varchar' })
|
||||||
|
address: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0, transformer: bigintTransformer })
|
||||||
|
paidSats: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal', default: 0 })
|
||||||
|
percent: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0, transformer: bigintTransformer })
|
||||||
|
balanceBeforeSats: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0, transformer: bigintTransformer })
|
||||||
|
balanceAfterSats: number;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'coinbase' })
|
||||||
|
rowType: 'coinbase' | 'pending';
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
import { PayoutSnapshotEntity } from './payout-snapshot.entity';
|
||||||
|
|
||||||
|
@Entity({ name: 'payout_snapshot_entry' })
|
||||||
|
@Index('IDX_payout_snapshot_entry_snapshot_rank', ['snapshotId', 'rank'])
|
||||||
|
@Index('IDX_payout_snapshot_entry_address', ['address'])
|
||||||
|
export class PayoutSnapshotEntryEntity {
|
||||||
|
@PrimaryGeneratedColumn({ type: 'bigint' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
snapshotId: string;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'pplns' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
|
@ManyToOne(() => PayoutSnapshotEntity, snapshot => snapshot.entries, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'snapshotId' })
|
||||||
|
snapshot: PayoutSnapshotEntity;
|
||||||
|
|
||||||
|
@Column({ length: 62, type: 'varchar' })
|
||||||
|
address: string;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
creditedDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
acceptedShareCount: string;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
payoutWeight: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
grossPayoutSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
payoutSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0 })
|
||||||
|
balanceBeforeSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0 })
|
||||||
|
balanceAfterSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'boolean', default: true })
|
||||||
|
includedInCoinbase: boolean;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'coinbase' })
|
||||||
|
rowType: 'coinbase' | 'pending';
|
||||||
|
|
||||||
|
@Column({ type: 'integer' })
|
||||||
|
rank: number;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Column, Entity, Index, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
import { PayoutSnapshotEntryEntity } from './payout-snapshot-entry.entity';
|
||||||
|
|
||||||
|
@Entity({ name: 'payout_snapshot' })
|
||||||
|
@Index('IDX_payout_snapshot_latest', ['payoutMode', 'status', 'createdAt'])
|
||||||
|
@Index('IDX_payout_snapshot_window', ['windowEndShareIndex'])
|
||||||
|
export class PayoutSnapshotEntity {
|
||||||
|
@PrimaryGeneratedColumn({ type: 'bigint' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ length: 32, type: 'varchar' })
|
||||||
|
method: string;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'pplns' })
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
|
||||||
|
@Column({ length: 16, type: 'varchar', default: 'finalized' })
|
||||||
|
status: 'finalized' | 'bridge_seed';
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
blockHeight: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
coinbaseValueSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
networkDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal', default: 0 })
|
||||||
|
windowTargetDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal', default: 4 })
|
||||||
|
windowFactor: number;
|
||||||
|
|
||||||
|
@Column({ length: 62, type: 'varchar', nullable: true })
|
||||||
|
feeAddress?: string | null;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint', default: 0 })
|
||||||
|
feeSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'integer', default: 546 })
|
||||||
|
minPayoutSats: number;
|
||||||
|
|
||||||
|
@Column({ type: 'integer', default: 50000 })
|
||||||
|
coinbaseWeightBudget: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
startBatchId: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
endBatchId: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
windowStartShareIndex: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
windowEndShareIndex: string;
|
||||||
|
|
||||||
|
@Column({ type: 'decimal' })
|
||||||
|
totalCreditedDifficulty: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
totalAcceptedShareCount: string;
|
||||||
|
|
||||||
|
@Column({ type: 'integer' })
|
||||||
|
eligibleAddressCount: number;
|
||||||
|
|
||||||
|
@Column({ type: 'integer' })
|
||||||
|
includedOutputCount: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
distributedSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
unallocatedRemainderSats: string;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@OneToMany(() => PayoutSnapshotEntryEntity, entry => entry.snapshot)
|
||||||
|
entries: PayoutSnapshotEntryEntity[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
|
||||||
|
import { PayoutBalanceEntity } from './payout-balance.entity';
|
||||||
|
import { PayoutHistoryEntity } from './payout-history.entity';
|
||||||
|
import { PayoutSnapshotEntryEntity } from './payout-snapshot-entry.entity';
|
||||||
|
import { PayoutSnapshotEntity } from './payout-snapshot.entity';
|
||||||
|
import { PayoutSnapshotService } from './payout-snapshot.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([
|
||||||
|
PayoutBalanceEntity,
|
||||||
|
PayoutHistoryEntity,
|
||||||
|
PayoutSnapshotEntity,
|
||||||
|
PayoutSnapshotEntryEntity,
|
||||||
|
])],
|
||||||
|
providers: [PayoutSnapshotService],
|
||||||
|
exports: [TypeOrmModule, PayoutSnapshotService],
|
||||||
|
})
|
||||||
|
export class PayoutSnapshotModule { }
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
import { DataSource, EntityManager } from 'typeorm';
|
||||||
|
|
||||||
|
import type { PayoutDistributionEntry } from './payout-distribution';
|
||||||
|
import { PayoutSnapshotService } from './payout-snapshot.service';
|
||||||
|
|
||||||
|
const ADDRESS_A = 'bc1qs29kyaqqc0fkvj897ke9e5xa9utljjey0y5jjn';
|
||||||
|
const ADDRESS_B = 'bc1q99n3pu025yyu0jlywpmwzalyhm36tg5u37w20d';
|
||||||
|
|
||||||
|
describe('PayoutSnapshotService', () => {
|
||||||
|
let originalEnv: NodeJS.ProcessEnv;
|
||||||
|
let manager: { query: jest.Mock };
|
||||||
|
let dataSource: { transaction: jest.Mock; query: jest.Mock };
|
||||||
|
let service: PayoutSnapshotService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalEnv = { ...process.env };
|
||||||
|
process.env.PAYOUT_SNAPSHOT_ENABLED = 'true';
|
||||||
|
process.env.PAYOUT_METHOD = 'pplns';
|
||||||
|
process.env.PAYOUT_WINDOW_FACTOR = '4';
|
||||||
|
process.env.PAYOUT_BOOTSTRAP_WINDOW = 'false';
|
||||||
|
process.env.PAYOUT_MAX_COINBASE_OUTPUTS = '10';
|
||||||
|
process.env.PAYOUT_MIN_OUTPUT_SATS = '546';
|
||||||
|
process.env.PAYOUT_FEE_PERCENT = '0';
|
||||||
|
process.env.PAYOUT_FEE_ADDRESS = '';
|
||||||
|
process.env.PAYOUT_COINBASE_WEIGHT_BUDGET = '50000';
|
||||||
|
manager = { query: jest.fn() };
|
||||||
|
dataSource = {
|
||||||
|
transaction: jest.fn(async callback => callback(manager as unknown as EntityManager)),
|
||||||
|
query: jest.fn(),
|
||||||
|
};
|
||||||
|
service = new PayoutSnapshotService(dataSource as unknown as DataSource);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env = originalEnv;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create a PPLNS payout snapshot from finalized rollup batches', async () => {
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
startBatchId: '10',
|
||||||
|
endBatchId: '12',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: '100',
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 60, acceptedShareCount: 3 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 40, acceptedShareCount: 2 },
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{ id: '55' }])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
id: '55',
|
||||||
|
method: 'pplns',
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: '1000',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
eligibleAddressCount: 2,
|
||||||
|
includedOutputCount: 2,
|
||||||
|
distributedSats: '1000',
|
||||||
|
unallocatedRemainderSats: '0',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, payoutSats: '600' },
|
||||||
|
{ address: ADDRESS_B, payoutSats: '400' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const snapshot = await service.createSnapshotForTemplate({
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
networkDifficulty: 25,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(snapshot).toEqual(expect.objectContaining({
|
||||||
|
id: '55',
|
||||||
|
method: 'pplns',
|
||||||
|
blockHeight: 900000,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
totalAcceptedShareCount: 5,
|
||||||
|
distributedSats: '1000',
|
||||||
|
unallocatedRemainderSats: '0',
|
||||||
|
}));
|
||||||
|
expect(snapshot.payoutOutputs).toEqual([
|
||||||
|
{ address: ADDRESS_A, amountSats: 600, percent: 60 },
|
||||||
|
{ address: ADDRESS_B, amountSats: 400, percent: 40 },
|
||||||
|
]);
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(8);
|
||||||
|
expect(manager.query.mock.calls[0][1]).toEqual([100, 'pplns']);
|
||||||
|
|
||||||
|
const entryInsertCalls = manager.query.mock.calls.filter(([sql]) => (
|
||||||
|
sql.includes('INSERT INTO "payout_snapshot_entry"')
|
||||||
|
));
|
||||||
|
expect(entryInsertCalls).toHaveLength(1);
|
||||||
|
expect(entryInsertCalls[0][0]).toContain('FROM UNNEST(');
|
||||||
|
expect(entryInsertCalls[0][0]).toContain('WITH ORDINALITY');
|
||||||
|
expect(entryInsertCalls[0][0]).toContain('ORDER BY entry."ordinality"');
|
||||||
|
expect(entryInsertCalls[0][1]).toEqual([
|
||||||
|
'55',
|
||||||
|
'pplns',
|
||||||
|
[ADDRESS_A, ADDRESS_B],
|
||||||
|
[60, 40],
|
||||||
|
[3, 2],
|
||||||
|
[0.6, 0.4],
|
||||||
|
[600, 400],
|
||||||
|
[600, 400],
|
||||||
|
[0, 0],
|
||||||
|
[0, 0],
|
||||||
|
[true, true],
|
||||||
|
['coinbase', 'coinbase'],
|
||||||
|
[1, 2],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should bound and chunk set-based snapshot entry inserts without changing values', async () => {
|
||||||
|
const entries: PayoutDistributionEntry[] = Array.from({ length: 1_001 }, (_, index) => {
|
||||||
|
const includedInCoinbase = index % 3 !== 0;
|
||||||
|
const balanceBeforeSats = 200 + index;
|
||||||
|
const grossPayoutSats = 10_000 + index;
|
||||||
|
return {
|
||||||
|
address: `test-address-${index}`,
|
||||||
|
creditedDifficulty: index + 0.5,
|
||||||
|
acceptedShareCount: index + 1,
|
||||||
|
payoutWeight: (index + 1) / 1_001,
|
||||||
|
grossPayoutSats,
|
||||||
|
payoutSats: includedInCoinbase ? 1_000 + index : 0,
|
||||||
|
balanceBeforeSats,
|
||||||
|
balanceAfterSats: includedInCoinbase
|
||||||
|
? balanceBeforeSats
|
||||||
|
: balanceBeforeSats + grossPayoutSats,
|
||||||
|
includedInCoinbase,
|
||||||
|
rank: 1_001 - index,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const insertSnapshotEntries = Reflect.get(service, 'insertSnapshotEntries') as (
|
||||||
|
manager: EntityManager,
|
||||||
|
snapshotId: string,
|
||||||
|
entries: PayoutDistributionEntry[],
|
||||||
|
) => Promise<void>;
|
||||||
|
let resolveFirstInsert: () => void = () => {
|
||||||
|
throw new Error('First insert did not start');
|
||||||
|
};
|
||||||
|
manager.query
|
||||||
|
.mockImplementationOnce(() => new Promise<void>(resolve => {
|
||||||
|
resolveFirstInsert = () => resolve();
|
||||||
|
}))
|
||||||
|
.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
|
const insertion = insertSnapshotEntries.call(
|
||||||
|
service,
|
||||||
|
manager as unknown as EntityManager,
|
||||||
|
'77',
|
||||||
|
entries,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(1);
|
||||||
|
resolveFirstInsert();
|
||||||
|
await insertion;
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(2);
|
||||||
|
const calls = manager.query.mock.calls;
|
||||||
|
expect(calls.map(([, parameters]) => parameters.length)).toEqual([13, 13]);
|
||||||
|
expect(calls.map(([, parameters]) => parameters[2].length)).toEqual([1_000, 1]);
|
||||||
|
for (const [sql, parameters] of calls) {
|
||||||
|
expect(sql).toContain('FROM UNNEST(');
|
||||||
|
expect(sql).toContain('ORDER BY entry."ordinality"');
|
||||||
|
for (const values of parameters.slice(2)) {
|
||||||
|
expect(values.length).toBeLessThanOrEqual(1_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedParameters = (batch: PayoutDistributionEntry[]) => [
|
||||||
|
'77',
|
||||||
|
'pplns',
|
||||||
|
batch.map(entry => entry.address),
|
||||||
|
batch.map(entry => entry.creditedDifficulty),
|
||||||
|
batch.map(entry => entry.acceptedShareCount),
|
||||||
|
batch.map(entry => entry.payoutWeight),
|
||||||
|
batch.map(entry => entry.grossPayoutSats),
|
||||||
|
batch.map(entry => entry.payoutSats),
|
||||||
|
batch.map(entry => entry.balanceBeforeSats),
|
||||||
|
batch.map(entry => entry.balanceAfterSats),
|
||||||
|
batch.map(entry => entry.includedInCoinbase),
|
||||||
|
batch.map(entry => entry.includedInCoinbase ? 'coinbase' : 'pending'),
|
||||||
|
batch.map(entry => entry.rank),
|
||||||
|
];
|
||||||
|
expect(calls[0][1]).toEqual(expectedParameters(entries.slice(0, 1_000)));
|
||||||
|
expect(calls[1][1]).toEqual(expectedParameters(entries.slice(1_000)));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should bootstrap the PPLNS window from paid block count up to the configured factor', async () => {
|
||||||
|
process.env.PAYOUT_BOOTSTRAP_WINDOW = 'true';
|
||||||
|
service = new PayoutSnapshotService(dataSource as unknown as DataSource);
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{ paidBlockCount: 1 }])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
startBatchId: '10',
|
||||||
|
endBatchId: '12',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: '50',
|
||||||
|
totalAcceptedShareCount: '3',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 30, acceptedShareCount: 2 },
|
||||||
|
{ address: ADDRESS_B, creditedDifficulty: 20, acceptedShareCount: 1 },
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{ id: '56' }])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
id: '56',
|
||||||
|
method: 'pplns',
|
||||||
|
blockHeight: 900001,
|
||||||
|
coinbaseValueSats: '1000',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: 50,
|
||||||
|
totalAcceptedShareCount: '3',
|
||||||
|
eligibleAddressCount: 2,
|
||||||
|
includedOutputCount: 2,
|
||||||
|
distributedSats: '1000',
|
||||||
|
unallocatedRemainderSats: '0',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, payoutSats: '600' },
|
||||||
|
{ address: ADDRESS_B, payoutSats: '400' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
await expect(service.createSnapshotForTemplate({
|
||||||
|
blockHeight: 900001,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
networkDifficulty: 25,
|
||||||
|
})).resolves.toEqual(expect.objectContaining({
|
||||||
|
id: '56',
|
||||||
|
totalCreditedDifficulty: 50,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(manager.query.mock.calls[0][0]).toContain('COUNT(DISTINCT "blockHeight")');
|
||||||
|
expect(manager.query.mock.calls[1][1]).toEqual([50, 'pplns']);
|
||||||
|
expect(manager.query.mock.calls[5][1][5]).toBe(50);
|
||||||
|
expect(manager.query.mock.calls[5][1][6]).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not create a snapshot when there is no finalized rollup work', async () => {
|
||||||
|
manager.query.mockResolvedValueOnce([{
|
||||||
|
startBatchId: null,
|
||||||
|
endBatchId: null,
|
||||||
|
windowStartShareIndex: null,
|
||||||
|
windowEndShareIndex: null,
|
||||||
|
totalCreditedDifficulty: '0',
|
||||||
|
totalAcceptedShareCount: '0',
|
||||||
|
}]);
|
||||||
|
|
||||||
|
await expect(service.createSnapshotForTemplate({
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
networkDifficulty: 25,
|
||||||
|
})).resolves.toBeNull();
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reuse an existing snapshot for the same template and rollup window', async () => {
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
startBatchId: '10',
|
||||||
|
endBatchId: '12',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: '100',
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{ id: '55' }])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
id: '55',
|
||||||
|
method: 'pplns',
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: '1000',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
eligibleAddressCount: 2,
|
||||||
|
includedOutputCount: 2,
|
||||||
|
distributedSats: '1000',
|
||||||
|
unallocatedRemainderSats: '0',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, payoutSats: '600' },
|
||||||
|
{ address: ADDRESS_B, payoutSats: '400' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const snapshot = await service.createSnapshotForTemplate({
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
networkDifficulty: 25,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(snapshot.id).toBe('55');
|
||||||
|
expect(snapshot.payoutOutputs).toEqual([
|
||||||
|
{ address: ADDRESS_A, amountSats: 600, percent: 60 },
|
||||||
|
{ address: ADDRESS_B, amountSats: 400, percent: 40 },
|
||||||
|
]);
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores bridge seeds with a non-active status excluded from latest payout queries', async () => {
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
startBatchId: '10',
|
||||||
|
endBatchId: '12',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: '100',
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{ address: ADDRESS_A, creditedDifficulty: 100, acceptedShareCount: 5 },
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{ id: 'seed-57' }])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
id: 'seed-57',
|
||||||
|
method: 'pplns',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
blockHeight: 900002,
|
||||||
|
coinbaseValueSats: '1000',
|
||||||
|
windowStartShareIndex: '1000',
|
||||||
|
windowEndShareIndex: '2000',
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
totalAcceptedShareCount: '5',
|
||||||
|
eligibleAddressCount: 1,
|
||||||
|
includedOutputCount: 1,
|
||||||
|
distributedSats: '1000',
|
||||||
|
unallocatedRemainderSats: '0',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{ address: ADDRESS_A, payoutSats: '1000' }]);
|
||||||
|
|
||||||
|
await expect(service.createSnapshotForTemplate({
|
||||||
|
blockHeight: 900002,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
networkDifficulty: 25,
|
||||||
|
visibility: 'bridge_seed',
|
||||||
|
})).resolves.toEqual(expect.objectContaining({ id: 'seed-57' }));
|
||||||
|
|
||||||
|
const existingLookupSql = manager.query.mock.calls[1][0] as string;
|
||||||
|
const insertSql = manager.query.mock.calls[4][0] as string;
|
||||||
|
expect(existingLookupSql).toContain(`"status" = 'bridge_seed'`);
|
||||||
|
expect(insertSql).toContain(`'bridge_seed'`);
|
||||||
|
dataSource.query.mockResolvedValueOnce([]);
|
||||||
|
await expect(service.getLatestSnapshot()).resolves.toBeNull();
|
||||||
|
expect(dataSource.query.mock.calls[0][0]).toContain(`"status" = 'finalized'`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should finalize snapshot balances and payout history for a found block', async () => {
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{ id: '55', coinbaseValueSats: '1000' }])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
address: ADDRESS_A,
|
||||||
|
payoutSats: '600',
|
||||||
|
balanceBeforeSats: '0',
|
||||||
|
balanceAfterSats: '0',
|
||||||
|
creditedDifficulty: 60,
|
||||||
|
includedInCoinbase: true,
|
||||||
|
rowType: 'coinbase',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
address: ADDRESS_B,
|
||||||
|
payoutSats: '400',
|
||||||
|
balanceBeforeSats: '0',
|
||||||
|
balanceAfterSats: '0',
|
||||||
|
creditedDifficulty: 40,
|
||||||
|
includedInCoinbase: true,
|
||||||
|
rowType: 'coinbase',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
|
await expect(service.finalizeSnapshotForBlock({
|
||||||
|
payoutSnapshotId: '55',
|
||||||
|
blockHeight: 900000,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
})).resolves.toEqual({
|
||||||
|
finalized: true,
|
||||||
|
payoutSnapshotId: '55',
|
||||||
|
historyRows: 2,
|
||||||
|
balanceRows: 2,
|
||||||
|
});
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should skip finalization when a block was already processed', async () => {
|
||||||
|
manager.query
|
||||||
|
.mockResolvedValueOnce([{ id: '55', coinbaseValueSats: '1000' }])
|
||||||
|
.mockResolvedValueOnce([{ id: '99' }]);
|
||||||
|
|
||||||
|
await expect(service.finalizeSnapshotForBlock({
|
||||||
|
payoutSnapshotId: '55',
|
||||||
|
blockHeight: 900000,
|
||||||
|
blockSubmissionResult: 'SUCCESS!',
|
||||||
|
})).resolves.toEqual({
|
||||||
|
finalized: false,
|
||||||
|
reason: 'already-finalized',
|
||||||
|
payoutSnapshotId: '55',
|
||||||
|
});
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return the latest current expected PPLNS payout for an address', async () => {
|
||||||
|
dataSource.query.mockResolvedValueOnce([{
|
||||||
|
snapshotId: '55',
|
||||||
|
blockHeight: 900000,
|
||||||
|
coinbaseValueSats: '1000',
|
||||||
|
distributedSats: '1000',
|
||||||
|
totalCreditedDifficulty: '100',
|
||||||
|
includedOutputCount: 2,
|
||||||
|
createdAt: new Date('2026-06-16T12:00:00.000Z'),
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
payoutSats: '600',
|
||||||
|
grossPayoutSats: '600',
|
||||||
|
creditedDifficulty: '60',
|
||||||
|
payoutWeight: '0.6',
|
||||||
|
}]);
|
||||||
|
|
||||||
|
await expect(service.getLatestExpectedPayoutForAddress(ADDRESS_A)).resolves.toEqual({
|
||||||
|
snapshotId: '55',
|
||||||
|
blockHeight: 900000,
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
payoutSats: 600,
|
||||||
|
grossPayoutSats: 600,
|
||||||
|
creditedDifficulty: 60,
|
||||||
|
payoutWeight: 0.6,
|
||||||
|
coinbaseValueSats: 1000,
|
||||||
|
distributedSats: 1000,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
includedOutputCount: 2,
|
||||||
|
createdAt: new Date('2026-06-16T12:00:00.000Z'),
|
||||||
|
percent: 60,
|
||||||
|
});
|
||||||
|
expect(dataSource.query.mock.calls[0][1]).toEqual([ADDRESS_A, 'pplns']);
|
||||||
|
expect(dataSource.query.mock.calls[0][0]).toContain('WITH latest_snapshot AS');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return null when the latest PPLNS snapshot does not pay the address', async () => {
|
||||||
|
dataSource.query.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
|
await expect(service.getLatestExpectedPayoutForAddress(ADDRESS_A)).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,832 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { DataSource, EntityManager } from 'typeorm';
|
||||||
|
|
||||||
|
import type { AddressObject } from '../../models/MiningJob';
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
import {
|
||||||
|
buildPayoutDistribution,
|
||||||
|
PayoutAddressWork,
|
||||||
|
PayoutBalanceInput,
|
||||||
|
PayoutDistributionEntry,
|
||||||
|
} from './payout-distribution';
|
||||||
|
|
||||||
|
export interface PayoutSnapshotForTemplate {
|
||||||
|
id: string;
|
||||||
|
method: string;
|
||||||
|
blockHeight: number;
|
||||||
|
coinbaseValueSats: string;
|
||||||
|
windowStartShareIndex: string;
|
||||||
|
windowEndShareIndex: string;
|
||||||
|
totalCreditedDifficulty: number;
|
||||||
|
totalAcceptedShareCount: number;
|
||||||
|
eligibleAddressCount: number;
|
||||||
|
includedOutputCount: number;
|
||||||
|
distributedSats: string;
|
||||||
|
unallocatedRemainderSats: string;
|
||||||
|
payoutOutputs: AddressObject[];
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayoutFinalizationResult {
|
||||||
|
finalized: boolean;
|
||||||
|
reason?: 'disabled' | 'missing-snapshot' | 'already-finalized' | 'duplicate';
|
||||||
|
payoutSnapshotId?: string;
|
||||||
|
historyRows?: number;
|
||||||
|
balanceRows?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExpectedPayout {
|
||||||
|
snapshotId: string;
|
||||||
|
blockHeight: number;
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
payoutSats: number;
|
||||||
|
grossPayoutSats: number;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
payoutWeight: number;
|
||||||
|
coinbaseValueSats: number;
|
||||||
|
distributedSats: number;
|
||||||
|
totalCreditedDifficulty: number;
|
||||||
|
includedOutputCount: number;
|
||||||
|
createdAt: Date;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_MAX_COINBASE_OUTPUTS = 200;
|
||||||
|
const DEFAULT_MIN_OUTPUT_SATS = 546;
|
||||||
|
const DEFAULT_PAYOUT_METHOD = 'pplns';
|
||||||
|
const DEFAULT_PAYOUT_WINDOW_FACTOR = 4;
|
||||||
|
const DEFAULT_COINBASE_WEIGHT_BUDGET = 26_000;
|
||||||
|
const DEFAULT_PAYOUT_BOOTSTRAP_WINDOW = true;
|
||||||
|
const PPLNS_PAYOUT_MODE: PayoutMode = 'pplns';
|
||||||
|
// UNNEST keeps each statement at 13 bind parameters; this cap bounds array payload size.
|
||||||
|
const PAYOUT_SNAPSHOT_ENTRY_INSERT_BATCH_SIZE = 1_000;
|
||||||
|
type PayoutSnapshotStatus = 'finalized' | 'bridge_seed';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PayoutSnapshotService {
|
||||||
|
private readonly snapshotsEnabled = this.readBoolean('PAYOUT_SNAPSHOT_ENABLED', true);
|
||||||
|
private readonly method = process.env.PAYOUT_METHOD ?? DEFAULT_PAYOUT_METHOD;
|
||||||
|
private readonly windowFactor = this.readPositiveNumber('PAYOUT_WINDOW_FACTOR', DEFAULT_PAYOUT_WINDOW_FACTOR);
|
||||||
|
private readonly bootstrapWindow = this.readBoolean('PAYOUT_BOOTSTRAP_WINDOW', DEFAULT_PAYOUT_BOOTSTRAP_WINDOW);
|
||||||
|
private readonly maxCoinbaseOutputs = this.readPositiveInt('PAYOUT_MAX_COINBASE_OUTPUTS', DEFAULT_MAX_COINBASE_OUTPUTS);
|
||||||
|
private readonly minOutputSats = this.readNonNegativeInt('PAYOUT_MIN_OUTPUT_SATS', DEFAULT_MIN_OUTPUT_SATS);
|
||||||
|
private readonly feeAddress = process.env.PAYOUT_FEE_ADDRESS?.trim() ?? '';
|
||||||
|
private readonly feePercent = this.readNonNegativeNumber('PAYOUT_FEE_PERCENT', 0);
|
||||||
|
private readonly coinbaseWeightBudget = this.readPositiveInt('PAYOUT_COINBASE_WEIGHT_BUDGET', DEFAULT_COINBASE_WEIGHT_BUDGET);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
public async createSnapshotForTemplate(input: {
|
||||||
|
blockHeight: number;
|
||||||
|
coinbaseValueSats: number;
|
||||||
|
networkDifficulty: number;
|
||||||
|
/** Bridge seeds are frozen/reconstructable but excluded from active payout APIs. */
|
||||||
|
visibility?: 'active' | 'bridge_seed';
|
||||||
|
}): Promise<PayoutSnapshotForTemplate | null> {
|
||||||
|
if (!this.snapshotsEnabled || input.coinbaseValueSats <= 0 || input.networkDifficulty <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.dataSource.transaction(async manager => {
|
||||||
|
const snapshotStatus: PayoutSnapshotStatus = input.visibility === 'bridge_seed'
|
||||||
|
? 'bridge_seed'
|
||||||
|
: 'finalized';
|
||||||
|
const effectiveWindowFactor = await this.getEffectiveWindowFactor(manager);
|
||||||
|
const windowTargetDifficulty = input.networkDifficulty * effectiveWindowFactor;
|
||||||
|
const window = await this.getPplnsWindow(manager, windowTargetDifficulty);
|
||||||
|
if (window == null || this.toNumber(window.totalCreditedDifficulty) <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await this.getExistingSnapshot(manager, {
|
||||||
|
blockHeight: input.blockHeight,
|
||||||
|
coinbaseValueSats: input.coinbaseValueSats,
|
||||||
|
windowEndShareIndex: window.windowEndShareIndex,
|
||||||
|
status: snapshotStatus,
|
||||||
|
});
|
||||||
|
if (existing != null) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
const addressWork = await this.getAddressWork(manager, window);
|
||||||
|
const balances = await this.getOpenBalances(manager);
|
||||||
|
if (addressWork.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const distribution = buildPayoutDistribution({
|
||||||
|
addressWork,
|
||||||
|
balances,
|
||||||
|
coinbaseValueSats: input.coinbaseValueSats,
|
||||||
|
feeAddress: this.feeAddress,
|
||||||
|
feePercent: this.feePercent,
|
||||||
|
minOutputSats: this.minOutputSats,
|
||||||
|
coinbaseWeightBudget: this.coinbaseWeightBudget,
|
||||||
|
});
|
||||||
|
const entries = this.limitCoinbaseOutputs(distribution.entries);
|
||||||
|
if (entries.every(entry => !entry.includedInCoinbase)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const includedOutputCount = entries.filter(entry => entry.includedInCoinbase).length;
|
||||||
|
const distributedSats = entries
|
||||||
|
.filter(entry => entry.includedInCoinbase)
|
||||||
|
.reduce((sum, entry) => sum + entry.payoutSats, 0);
|
||||||
|
const unallocatedRemainderSats = input.coinbaseValueSats - distributedSats;
|
||||||
|
const [snapshotRow] = await manager.query(`
|
||||||
|
INSERT INTO "payout_snapshot" (
|
||||||
|
"method",
|
||||||
|
"payoutMode",
|
||||||
|
"status",
|
||||||
|
"blockHeight",
|
||||||
|
"coinbaseValueSats",
|
||||||
|
"networkDifficulty",
|
||||||
|
"windowTargetDifficulty",
|
||||||
|
"windowFactor",
|
||||||
|
"feeAddress",
|
||||||
|
"feeSats",
|
||||||
|
"minPayoutSats",
|
||||||
|
"coinbaseWeightBudget",
|
||||||
|
"startBatchId",
|
||||||
|
"endBatchId",
|
||||||
|
"windowStartShareIndex",
|
||||||
|
"windowEndShareIndex",
|
||||||
|
"totalCreditedDifficulty",
|
||||||
|
"totalAcceptedShareCount",
|
||||||
|
"eligibleAddressCount",
|
||||||
|
"includedOutputCount",
|
||||||
|
"distributedSats",
|
||||||
|
"unallocatedRemainderSats"
|
||||||
|
) VALUES (
|
||||||
|
$1,
|
||||||
|
$2,
|
||||||
|
'${snapshotStatus}',
|
||||||
|
$3::bigint,
|
||||||
|
$4::bigint,
|
||||||
|
$5::numeric,
|
||||||
|
$6::numeric,
|
||||||
|
$7::numeric,
|
||||||
|
NULLIF($8, ''),
|
||||||
|
$9::bigint,
|
||||||
|
$10::int,
|
||||||
|
$11::int,
|
||||||
|
$12::bigint,
|
||||||
|
$13::bigint,
|
||||||
|
$14::bigint,
|
||||||
|
$15::bigint,
|
||||||
|
$16::numeric,
|
||||||
|
$17::bigint,
|
||||||
|
$18::int,
|
||||||
|
$19::int,
|
||||||
|
$20::bigint,
|
||||||
|
$21::bigint
|
||||||
|
)
|
||||||
|
RETURNING "id"::text AS "id"
|
||||||
|
`, [
|
||||||
|
this.method,
|
||||||
|
PPLNS_PAYOUT_MODE,
|
||||||
|
input.blockHeight,
|
||||||
|
input.coinbaseValueSats.toString(),
|
||||||
|
input.networkDifficulty,
|
||||||
|
windowTargetDifficulty,
|
||||||
|
effectiveWindowFactor,
|
||||||
|
this.feeAddress,
|
||||||
|
distribution.feeSats.toString(),
|
||||||
|
this.minOutputSats,
|
||||||
|
this.coinbaseWeightBudget,
|
||||||
|
window.startBatchId,
|
||||||
|
window.endBatchId,
|
||||||
|
window.windowStartShareIndex,
|
||||||
|
window.windowEndShareIndex,
|
||||||
|
window.totalCreditedDifficulty,
|
||||||
|
window.totalAcceptedShareCount,
|
||||||
|
distribution.consideredAddressCount,
|
||||||
|
includedOutputCount,
|
||||||
|
distributedSats.toString(),
|
||||||
|
unallocatedRemainderSats.toString(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await this.insertSnapshotEntries(manager, snapshotRow.id, entries);
|
||||||
|
|
||||||
|
return this.getSnapshotById(manager, snapshotRow.id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getEffectiveWindowFactor(manager: EntityManager): Promise<number> {
|
||||||
|
if (!this.bootstrapWindow) {
|
||||||
|
return this.windowFactor;
|
||||||
|
}
|
||||||
|
|
||||||
|
const paidBlockCount = await this.getFinalizedPayoutBlockCount(manager);
|
||||||
|
return Math.min(this.windowFactor, Math.max(1, paidBlockCount + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getFinalizedPayoutBlockCount(manager: EntityManager): Promise<number> {
|
||||||
|
const [row] = await manager.query(`
|
||||||
|
SELECT COUNT(DISTINCT "blockHeight")::int AS "paidBlockCount"
|
||||||
|
FROM "payout_history"
|
||||||
|
WHERE "payoutMode" = $1
|
||||||
|
`, [PPLNS_PAYOUT_MODE]);
|
||||||
|
return this.toNumber(row?.paidBlockCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async finalizeSnapshotForBlock(input: {
|
||||||
|
payoutSnapshotId?: string | null;
|
||||||
|
blockHeight: number;
|
||||||
|
blockSubmissionResult?: string | null;
|
||||||
|
payoutMode?: PayoutMode;
|
||||||
|
}): Promise<PayoutFinalizationResult> {
|
||||||
|
if (!this.snapshotsEnabled) {
|
||||||
|
return { finalized: false, reason: 'disabled' };
|
||||||
|
}
|
||||||
|
if ((input.payoutMode ?? PPLNS_PAYOUT_MODE) !== PPLNS_PAYOUT_MODE) {
|
||||||
|
return { finalized: false, reason: 'missing-snapshot' };
|
||||||
|
}
|
||||||
|
if (!this.isSuccessfulBlockSubmission(input.blockSubmissionResult)) {
|
||||||
|
return { finalized: false, reason: 'missing-snapshot' };
|
||||||
|
}
|
||||||
|
if (input.payoutSnapshotId == null) {
|
||||||
|
return { finalized: false, reason: 'missing-snapshot' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.dataSource.transaction<PayoutFinalizationResult>(async manager => {
|
||||||
|
const [snapshot] = await manager.query(`
|
||||||
|
SELECT "id"::text AS "id", "coinbaseValueSats"::text AS "coinbaseValueSats"
|
||||||
|
FROM "payout_snapshot"
|
||||||
|
WHERE "id" = $1::bigint
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
LIMIT 1
|
||||||
|
`, [input.payoutSnapshotId, PPLNS_PAYOUT_MODE]);
|
||||||
|
if (snapshot == null) {
|
||||||
|
return { finalized: false, reason: 'missing-snapshot' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const [existing] = await manager.query(`
|
||||||
|
SELECT "id"::text AS "id"
|
||||||
|
FROM "payout_history"
|
||||||
|
WHERE "blockHeight" = $1::bigint
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
LIMIT 1
|
||||||
|
`, [input.blockHeight, PPLNS_PAYOUT_MODE]);
|
||||||
|
if (existing != null) {
|
||||||
|
return {
|
||||||
|
finalized: false,
|
||||||
|
reason: 'already-finalized',
|
||||||
|
payoutSnapshotId: input.payoutSnapshotId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
"address",
|
||||||
|
"payoutSats"::text AS "payoutSats",
|
||||||
|
"balanceBeforeSats"::text AS "balanceBeforeSats",
|
||||||
|
"balanceAfterSats"::text AS "balanceAfterSats",
|
||||||
|
"creditedDifficulty"::float AS "creditedDifficulty",
|
||||||
|
"includedInCoinbase",
|
||||||
|
"rowType"
|
||||||
|
FROM "payout_snapshot_entry"
|
||||||
|
WHERE "snapshotId" = $1::bigint
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
ORDER BY "rank"
|
||||||
|
`, [input.payoutSnapshotId, PPLNS_PAYOUT_MODE]);
|
||||||
|
if (entries.length === 0) {
|
||||||
|
return { finalized: false, reason: 'missing-snapshot' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let balanceRows = 0;
|
||||||
|
let historyRows = 0;
|
||||||
|
const coinbaseValue = this.toNumber(snapshot.coinbaseValueSats);
|
||||||
|
for (const entry of entries) {
|
||||||
|
const payoutSats = this.toNumber(entry.payoutSats);
|
||||||
|
const balanceBeforeSats = this.toNumber(entry.balanceBeforeSats);
|
||||||
|
const balanceAfterSats = this.toNumber(entry.balanceAfterSats);
|
||||||
|
const isCoinbase = entry.includedInCoinbase === true;
|
||||||
|
const wasActive = this.toNumber(entry.creditedDifficulty) > 0;
|
||||||
|
|
||||||
|
await manager.query(`
|
||||||
|
INSERT INTO "payout_balance" (
|
||||||
|
"address",
|
||||||
|
"balanceSats",
|
||||||
|
"totalPaidSats",
|
||||||
|
"lastAcceptedShareAt",
|
||||||
|
"updatedAt"
|
||||||
|
) VALUES (
|
||||||
|
$1,
|
||||||
|
$2::bigint,
|
||||||
|
$3::bigint,
|
||||||
|
CASE WHEN $4::boolean THEN NOW() ELSE NULL END,
|
||||||
|
NOW()
|
||||||
|
)
|
||||||
|
ON CONFLICT ("address") DO UPDATE SET
|
||||||
|
"balanceSats" = EXCLUDED."balanceSats",
|
||||||
|
"totalPaidSats" = "payout_balance"."totalPaidSats" + EXCLUDED."totalPaidSats",
|
||||||
|
"lastAcceptedShareAt" = CASE
|
||||||
|
WHEN $4::boolean THEN NOW()
|
||||||
|
ELSE "payout_balance"."lastAcceptedShareAt"
|
||||||
|
END,
|
||||||
|
"updatedAt" = NOW()
|
||||||
|
`, [
|
||||||
|
entry.address,
|
||||||
|
balanceAfterSats.toString(),
|
||||||
|
isCoinbase ? payoutSats.toString() : '0',
|
||||||
|
wasActive,
|
||||||
|
]);
|
||||||
|
balanceRows++;
|
||||||
|
|
||||||
|
await manager.query(`
|
||||||
|
INSERT INTO "payout_history" (
|
||||||
|
"blockHeight",
|
||||||
|
"payoutSnapshotId",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"paidSats",
|
||||||
|
"percent",
|
||||||
|
"balanceBeforeSats",
|
||||||
|
"balanceAfterSats",
|
||||||
|
"rowType"
|
||||||
|
) VALUES (
|
||||||
|
$1::bigint,
|
||||||
|
$2::bigint,
|
||||||
|
$3,
|
||||||
|
$4,
|
||||||
|
$5::bigint,
|
||||||
|
$6::numeric,
|
||||||
|
$7::bigint,
|
||||||
|
$8::bigint,
|
||||||
|
$9
|
||||||
|
)
|
||||||
|
ON CONFLICT ("payoutMode", "blockHeight", "address") DO NOTHING
|
||||||
|
`, [
|
||||||
|
input.blockHeight,
|
||||||
|
input.payoutSnapshotId,
|
||||||
|
PPLNS_PAYOUT_MODE,
|
||||||
|
entry.address,
|
||||||
|
payoutSats.toString(),
|
||||||
|
coinbaseValue > 0 && isCoinbase ? (payoutSats / coinbaseValue) * 100 : 0,
|
||||||
|
balanceBeforeSats.toString(),
|
||||||
|
balanceAfterSats.toString(),
|
||||||
|
isCoinbase ? 'coinbase' : 'pending',
|
||||||
|
]);
|
||||||
|
historyRows++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
finalized: true,
|
||||||
|
payoutSnapshotId: input.payoutSnapshotId,
|
||||||
|
historyRows,
|
||||||
|
balanceRows,
|
||||||
|
};
|
||||||
|
}).catch(error => {
|
||||||
|
if (error?.code === '23505') {
|
||||||
|
return {
|
||||||
|
finalized: false,
|
||||||
|
reason: 'duplicate',
|
||||||
|
payoutSnapshotId: input.payoutSnapshotId ?? undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getLatestSnapshot(): Promise<PayoutSnapshotForTemplate | null> {
|
||||||
|
const [snapshot] = await this.dataSource.query(`
|
||||||
|
SELECT "id"::text AS "id"
|
||||||
|
FROM "payout_snapshot"
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
AND "payoutMode" = $1
|
||||||
|
ORDER BY "createdAt" DESC, "id" DESC
|
||||||
|
LIMIT 1
|
||||||
|
`, [PPLNS_PAYOUT_MODE]);
|
||||||
|
if (snapshot?.id == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.dataSource.transaction(manager => this.getSnapshotById(manager, snapshot.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getLatestExpectedPayoutForAddress(address: string): Promise<ExpectedPayout | null> {
|
||||||
|
const [row] = await this.dataSource.query(`
|
||||||
|
WITH latest_snapshot AS (
|
||||||
|
SELECT
|
||||||
|
"id",
|
||||||
|
"blockHeight",
|
||||||
|
"coinbaseValueSats",
|
||||||
|
"distributedSats",
|
||||||
|
"totalCreditedDifficulty",
|
||||||
|
"includedOutputCount",
|
||||||
|
"createdAt",
|
||||||
|
"payoutMode"
|
||||||
|
FROM "payout_snapshot"
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
ORDER BY "createdAt" DESC, "id" DESC
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
s."id"::text AS "snapshotId",
|
||||||
|
s."blockHeight"::int AS "blockHeight",
|
||||||
|
s."coinbaseValueSats"::text AS "coinbaseValueSats",
|
||||||
|
s."distributedSats"::text AS "distributedSats",
|
||||||
|
s."totalCreditedDifficulty"::text AS "totalCreditedDifficulty",
|
||||||
|
s."includedOutputCount"::int AS "includedOutputCount",
|
||||||
|
s."createdAt" AS "createdAt",
|
||||||
|
e."payoutMode" AS "payoutMode",
|
||||||
|
e."payoutSats"::text AS "payoutSats",
|
||||||
|
e."grossPayoutSats"::text AS "grossPayoutSats",
|
||||||
|
e."creditedDifficulty"::text AS "creditedDifficulty",
|
||||||
|
e."payoutWeight"::text AS "payoutWeight"
|
||||||
|
FROM latest_snapshot s
|
||||||
|
JOIN "payout_snapshot_entry" e ON e."snapshotId" = s."id"
|
||||||
|
WHERE e."address" = $1
|
||||||
|
AND e."payoutMode" = $2
|
||||||
|
AND e."includedInCoinbase" = true
|
||||||
|
AND e."payoutSats" > 0
|
||||||
|
LIMIT 1
|
||||||
|
`, [address, PPLNS_PAYOUT_MODE]);
|
||||||
|
|
||||||
|
if (row == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payoutSats = this.toNumber(row.payoutSats);
|
||||||
|
const coinbaseValueSats = this.toNumber(row.coinbaseValueSats);
|
||||||
|
return {
|
||||||
|
snapshotId: row.snapshotId,
|
||||||
|
blockHeight: this.toNumber(row.blockHeight),
|
||||||
|
payoutMode: row.payoutMode,
|
||||||
|
payoutSats,
|
||||||
|
grossPayoutSats: this.toNumber(row.grossPayoutSats),
|
||||||
|
creditedDifficulty: this.toNumber(row.creditedDifficulty),
|
||||||
|
payoutWeight: this.toNumber(row.payoutWeight),
|
||||||
|
coinbaseValueSats,
|
||||||
|
distributedSats: this.toNumber(row.distributedSats),
|
||||||
|
totalCreditedDifficulty: this.toNumber(row.totalCreditedDifficulty),
|
||||||
|
includedOutputCount: this.toNumber(row.includedOutputCount),
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
percent: coinbaseValueSats > 0 ? (payoutSats / coinbaseValueSats) * 100 : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getPplnsWindow(manager: EntityManager, windowTargetDifficulty: number): Promise<{
|
||||||
|
startBatchId: string;
|
||||||
|
endBatchId: string;
|
||||||
|
windowStartShareIndex: string;
|
||||||
|
windowEndShareIndex: string;
|
||||||
|
totalCreditedDifficulty: string;
|
||||||
|
totalAcceptedShareCount: string;
|
||||||
|
} | null> {
|
||||||
|
const [window] = await manager.query(`
|
||||||
|
WITH ordered AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
"id",
|
||||||
|
"startShareIndex",
|
||||||
|
"endShareIndex",
|
||||||
|
"acceptedShareCount",
|
||||||
|
"creditedDifficulty",
|
||||||
|
COALESCE(
|
||||||
|
SUM("creditedDifficulty") OVER (
|
||||||
|
ORDER BY "endShareIndex" DESC
|
||||||
|
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
|
||||||
|
),
|
||||||
|
0
|
||||||
|
) AS "difficultyAfter"
|
||||||
|
FROM "share_rollup_batch"
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
),
|
||||||
|
selected AS MATERIALIZED (
|
||||||
|
SELECT *
|
||||||
|
FROM ordered
|
||||||
|
WHERE "difficultyAfter" < $1::numeric
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MIN("id")::text AS "startBatchId",
|
||||||
|
MAX("id")::text AS "endBatchId",
|
||||||
|
MIN("startShareIndex")::text AS "windowStartShareIndex",
|
||||||
|
MAX("endShareIndex")::text AS "windowEndShareIndex",
|
||||||
|
COALESCE(SUM("creditedDifficulty"), 0)::numeric AS "totalCreditedDifficulty",
|
||||||
|
COALESCE(SUM("acceptedShareCount"), 0)::bigint AS "totalAcceptedShareCount"
|
||||||
|
FROM selected
|
||||||
|
`, [windowTargetDifficulty, PPLNS_PAYOUT_MODE]);
|
||||||
|
|
||||||
|
if (window?.startBatchId == null || window?.windowEndShareIndex == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAddressWork(
|
||||||
|
manager: EntityManager,
|
||||||
|
window: { windowStartShareIndex: string; windowEndShareIndex: string },
|
||||||
|
): Promise<PayoutAddressWork[]> {
|
||||||
|
const rows = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
s."address",
|
||||||
|
COALESCE(SUM(s."creditedDifficulty"), 0)::float AS "creditedDifficulty",
|
||||||
|
COALESCE(SUM(s."acceptedShareCount"), 0)::int AS "acceptedShareCount"
|
||||||
|
FROM "share_rollup_batch_summary" s
|
||||||
|
JOIN "share_rollup_batch" b ON b."id" = s."batchId"
|
||||||
|
WHERE b."status" = 'finalized'
|
||||||
|
AND b."payoutMode" = $3
|
||||||
|
AND s."payoutMode" = $3
|
||||||
|
AND b."endShareIndex" >= $1::bigint
|
||||||
|
AND b."endShareIndex" <= $2::bigint
|
||||||
|
GROUP BY s."address"
|
||||||
|
HAVING COALESCE(SUM(s."creditedDifficulty"), 0) > 0
|
||||||
|
`, [
|
||||||
|
window.windowStartShareIndex,
|
||||||
|
window.windowEndShareIndex,
|
||||||
|
PPLNS_PAYOUT_MODE,
|
||||||
|
]);
|
||||||
|
return rows.map(row => ({
|
||||||
|
address: row.address,
|
||||||
|
creditedDifficulty: this.toNumber(row.creditedDifficulty),
|
||||||
|
acceptedShareCount: this.toNumber(row.acceptedShareCount),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getOpenBalances(manager: EntityManager): Promise<PayoutBalanceInput[]> {
|
||||||
|
const rows = await manager.query(`
|
||||||
|
SELECT "address", "balanceSats"::text AS "balanceSats"
|
||||||
|
FROM "payout_balance"
|
||||||
|
WHERE "balanceSats" != 0
|
||||||
|
`);
|
||||||
|
return rows.map(row => ({
|
||||||
|
address: row.address,
|
||||||
|
balanceSats: this.toNumber(row.balanceSats),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getExistingSnapshot(
|
||||||
|
manager: EntityManager,
|
||||||
|
input: {
|
||||||
|
blockHeight: number;
|
||||||
|
coinbaseValueSats: number;
|
||||||
|
windowEndShareIndex: string;
|
||||||
|
status: PayoutSnapshotStatus;
|
||||||
|
},
|
||||||
|
): Promise<PayoutSnapshotForTemplate | null> {
|
||||||
|
const [snapshot] = await manager.query(`
|
||||||
|
SELECT "id"::text AS "id"
|
||||||
|
FROM "payout_snapshot"
|
||||||
|
WHERE "method" = $1
|
||||||
|
AND "payoutMode" = $5
|
||||||
|
AND "status" = '${input.status}'
|
||||||
|
AND "blockHeight" = $2::bigint
|
||||||
|
AND "coinbaseValueSats" = $3::bigint
|
||||||
|
AND "windowEndShareIndex" = $4::bigint
|
||||||
|
ORDER BY "id" DESC
|
||||||
|
LIMIT 1
|
||||||
|
`, [
|
||||||
|
this.method,
|
||||||
|
input.blockHeight,
|
||||||
|
input.coinbaseValueSats.toString(),
|
||||||
|
input.windowEndShareIndex,
|
||||||
|
PPLNS_PAYOUT_MODE,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (snapshot?.id == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.getSnapshotById(manager, snapshot.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getSnapshotById(manager: EntityManager, id: string): Promise<PayoutSnapshotForTemplate | null> {
|
||||||
|
const [snapshot] = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
"id"::text AS "id",
|
||||||
|
"method",
|
||||||
|
"payoutMode",
|
||||||
|
"blockHeight"::int AS "blockHeight",
|
||||||
|
"coinbaseValueSats"::text AS "coinbaseValueSats",
|
||||||
|
"windowStartShareIndex"::text AS "windowStartShareIndex",
|
||||||
|
"windowEndShareIndex"::text AS "windowEndShareIndex",
|
||||||
|
"totalCreditedDifficulty"::float AS "totalCreditedDifficulty",
|
||||||
|
"totalAcceptedShareCount"::bigint AS "totalAcceptedShareCount",
|
||||||
|
"eligibleAddressCount",
|
||||||
|
"includedOutputCount",
|
||||||
|
"distributedSats"::text AS "distributedSats",
|
||||||
|
"unallocatedRemainderSats"::text AS "unallocatedRemainderSats"
|
||||||
|
FROM "payout_snapshot"
|
||||||
|
WHERE "id" = $1::bigint
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
`, [id, PPLNS_PAYOUT_MODE]);
|
||||||
|
if (snapshot == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
"address",
|
||||||
|
"payoutSats"::text AS "payoutSats"
|
||||||
|
FROM "payout_snapshot_entry"
|
||||||
|
WHERE "snapshotId" = $1::bigint
|
||||||
|
AND "payoutMode" = $2
|
||||||
|
AND "includedInCoinbase" = true
|
||||||
|
ORDER BY "rank"
|
||||||
|
`, [id, PPLNS_PAYOUT_MODE]);
|
||||||
|
const coinbaseValue = Number(snapshot.coinbaseValueSats);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: snapshot.id,
|
||||||
|
method: snapshot.method,
|
||||||
|
payoutMode: snapshot.payoutMode,
|
||||||
|
blockHeight: this.toNumber(snapshot.blockHeight),
|
||||||
|
coinbaseValueSats: snapshot.coinbaseValueSats,
|
||||||
|
windowStartShareIndex: snapshot.windowStartShareIndex,
|
||||||
|
windowEndShareIndex: snapshot.windowEndShareIndex,
|
||||||
|
totalCreditedDifficulty: this.toNumber(snapshot.totalCreditedDifficulty),
|
||||||
|
totalAcceptedShareCount: this.toNumber(snapshot.totalAcceptedShareCount),
|
||||||
|
eligibleAddressCount: this.toNumber(snapshot.eligibleAddressCount),
|
||||||
|
includedOutputCount: this.toNumber(snapshot.includedOutputCount),
|
||||||
|
distributedSats: snapshot.distributedSats,
|
||||||
|
unallocatedRemainderSats: snapshot.unallocatedRemainderSats,
|
||||||
|
payoutOutputs: entries.map(entry => ({
|
||||||
|
address: entry.address,
|
||||||
|
amountSats: this.toNumber(entry.payoutSats),
|
||||||
|
percent: coinbaseValue > 0
|
||||||
|
? (this.toNumber(entry.payoutSats) / coinbaseValue) * 100
|
||||||
|
: 0,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async insertSnapshotEntries(
|
||||||
|
manager: EntityManager,
|
||||||
|
snapshotId: string,
|
||||||
|
entries: PayoutDistributionEntry[],
|
||||||
|
): Promise<void> {
|
||||||
|
for (let offset = 0; offset < entries.length; offset += PAYOUT_SNAPSHOT_ENTRY_INSERT_BATCH_SIZE) {
|
||||||
|
const batch = entries.slice(offset, offset + PAYOUT_SNAPSHOT_ENTRY_INSERT_BATCH_SIZE);
|
||||||
|
await manager.query(`
|
||||||
|
INSERT INTO "payout_snapshot_entry" (
|
||||||
|
"snapshotId",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"creditedDifficulty",
|
||||||
|
"acceptedShareCount",
|
||||||
|
"payoutWeight",
|
||||||
|
"grossPayoutSats",
|
||||||
|
"payoutSats",
|
||||||
|
"balanceBeforeSats",
|
||||||
|
"balanceAfterSats",
|
||||||
|
"includedInCoinbase",
|
||||||
|
"rowType",
|
||||||
|
"rank"
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
$1::bigint,
|
||||||
|
$2,
|
||||||
|
entry."address",
|
||||||
|
entry."creditedDifficulty",
|
||||||
|
entry."acceptedShareCount",
|
||||||
|
entry."payoutWeight",
|
||||||
|
entry."grossPayoutSats",
|
||||||
|
entry."payoutSats",
|
||||||
|
entry."balanceBeforeSats",
|
||||||
|
entry."balanceAfterSats",
|
||||||
|
entry."includedInCoinbase",
|
||||||
|
entry."rowType",
|
||||||
|
entry."rank"
|
||||||
|
FROM UNNEST(
|
||||||
|
$3::varchar[],
|
||||||
|
$4::numeric[],
|
||||||
|
$5::bigint[],
|
||||||
|
$6::numeric[],
|
||||||
|
$7::bigint[],
|
||||||
|
$8::bigint[],
|
||||||
|
$9::bigint[],
|
||||||
|
$10::bigint[],
|
||||||
|
$11::boolean[],
|
||||||
|
$12::varchar[],
|
||||||
|
$13::int[]
|
||||||
|
) WITH ORDINALITY AS entry(
|
||||||
|
"address",
|
||||||
|
"creditedDifficulty",
|
||||||
|
"acceptedShareCount",
|
||||||
|
"payoutWeight",
|
||||||
|
"grossPayoutSats",
|
||||||
|
"payoutSats",
|
||||||
|
"balanceBeforeSats",
|
||||||
|
"balanceAfterSats",
|
||||||
|
"includedInCoinbase",
|
||||||
|
"rowType",
|
||||||
|
"rank",
|
||||||
|
"ordinality"
|
||||||
|
)
|
||||||
|
ORDER BY entry."ordinality"
|
||||||
|
`, [
|
||||||
|
snapshotId,
|
||||||
|
PPLNS_PAYOUT_MODE,
|
||||||
|
batch.map(entry => entry.address),
|
||||||
|
batch.map(entry => entry.creditedDifficulty),
|
||||||
|
batch.map(entry => entry.acceptedShareCount),
|
||||||
|
batch.map(entry => entry.payoutWeight),
|
||||||
|
batch.map(entry => entry.grossPayoutSats),
|
||||||
|
batch.map(entry => entry.payoutSats),
|
||||||
|
batch.map(entry => entry.balanceBeforeSats),
|
||||||
|
batch.map(entry => entry.balanceAfterSats),
|
||||||
|
batch.map(entry => entry.includedInCoinbase),
|
||||||
|
batch.map(entry => entry.includedInCoinbase ? 'coinbase' : 'pending'),
|
||||||
|
batch.map(entry => entry.rank),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private limitCoinbaseOutputs(entries: PayoutDistributionEntry[]): PayoutDistributionEntry[] {
|
||||||
|
let included = 0;
|
||||||
|
let removedPayoutSats = 0;
|
||||||
|
const limitedEntries = entries.map(entry => {
|
||||||
|
if (!entry.includedInCoinbase) {
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
included++;
|
||||||
|
if (included <= this.maxCoinbaseOutputs) {
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
removedPayoutSats += entry.payoutSats;
|
||||||
|
return {
|
||||||
|
...entry,
|
||||||
|
payoutSats: 0,
|
||||||
|
balanceAfterSats: entry.balanceAfterSats + entry.payoutSats,
|
||||||
|
includedInCoinbase: false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (removedPayoutSats <= 0) {
|
||||||
|
return limitedEntries;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keptActive = limitedEntries
|
||||||
|
.filter(entry => entry.includedInCoinbase && entry.creditedDifficulty > 0);
|
||||||
|
const keptDifficulty = keptActive.reduce((sum, entry) => sum + entry.creditedDifficulty, 0);
|
||||||
|
if (keptDifficulty <= 0) {
|
||||||
|
return limitedEntries;
|
||||||
|
}
|
||||||
|
|
||||||
|
let assigned = 0;
|
||||||
|
const allocations = keptActive
|
||||||
|
.map(entry => {
|
||||||
|
const exact = (entry.creditedDifficulty * removedPayoutSats) / keptDifficulty;
|
||||||
|
const whole = Math.floor(exact);
|
||||||
|
assigned += whole;
|
||||||
|
return {
|
||||||
|
entry,
|
||||||
|
whole,
|
||||||
|
fraction: exact - whole,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.fraction - a.fraction || b.entry.creditedDifficulty - a.entry.creditedDifficulty || a.entry.address.localeCompare(b.entry.address));
|
||||||
|
|
||||||
|
let residual = removedPayoutSats - assigned;
|
||||||
|
for (const allocation of allocations) {
|
||||||
|
const extra = allocation.whole + (residual > 0 ? 1 : 0);
|
||||||
|
if (residual > 0) {
|
||||||
|
residual--;
|
||||||
|
}
|
||||||
|
allocation.entry.payoutSats += extra;
|
||||||
|
allocation.entry.balanceAfterSats -= extra;
|
||||||
|
}
|
||||||
|
|
||||||
|
return limitedEntries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isSuccessfulBlockSubmission(result?: string | null): boolean {
|
||||||
|
return result == null || result === 'SUCCESS!';
|
||||||
|
}
|
||||||
|
|
||||||
|
private toNumber(value: unknown): number {
|
||||||
|
const parsed = Number(value ?? 0);
|
||||||
|
return Number.isFinite(parsed) ? parsed : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isInteger(value) && value > 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readNonNegativeInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isInteger(value) && value >= 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveNumber(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isFinite(value) && value > 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readNonNegativeNumber(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isFinite(value) && value >= 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readBoolean(name: string, defaultValue: boolean): boolean {
|
||||||
|
const value = process.env[name]?.toLowerCase();
|
||||||
|
if (value == null || value.length === 0) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
return value === 'true' || value === '1' || value === 'yes';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,9 +6,6 @@ export class RpcBlockEntity {
|
|||||||
@PrimaryColumn()
|
@PrimaryColumn()
|
||||||
blockHeight: number;
|
blockHeight: number;
|
||||||
|
|
||||||
@Column({ nullable: true })
|
|
||||||
lockedBy?: string;
|
|
||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
data?: string;
|
data?: string;
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { InsertResult, Repository } from 'typeorm';
|
||||||
|
|
||||||
import { RpcBlockEntity } from './rpc-block.entity';
|
import { RpcBlockEntity } from './rpc-block.entity';
|
||||||
|
|
||||||
@@ -12,17 +12,28 @@ export class RpcBlockService {
|
|||||||
) {
|
) {
|
||||||
|
|
||||||
}
|
}
|
||||||
public getBlock(blockHeight: number) {
|
public getSavedBlockTemplate(blockHeight: number) {
|
||||||
return this.rpcBlockRepository.findOne({
|
return this.rpcBlockRepository.findOne({
|
||||||
where: { blockHeight }
|
where: { blockHeight }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public lockBlock(blockHeight: number, process: string) {
|
public saveBlock(blockHeight: number, data: string): Promise<InsertResult> {
|
||||||
return this.rpcBlockRepository.save({ blockHeight, data: null, lockedBy: process });
|
return this.rpcBlockRepository.upsert({ blockHeight, data }, ['blockHeight']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public saveBlock(blockHeight: number, data: string) {
|
public async deleteOldBlocks() {
|
||||||
return this.rpcBlockRepository.update(blockHeight, { data })
|
const result = await this.rpcBlockRepository.createQueryBuilder('entity')
|
||||||
|
.select('MAX(entity.blockHeight)', 'maxNumber')
|
||||||
|
.getRawOne();
|
||||||
|
|
||||||
|
const newestBlock = result ? result.maxNumber : null;
|
||||||
|
|
||||||
|
await this.rpcBlockRepository.createQueryBuilder()
|
||||||
|
.delete()
|
||||||
|
.where('"blockHeight" < :newestBlock', { newestBlock })
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
|
||||||
|
import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity';
|
||||||
|
import { ShareAccountingService } from './share-accounting.service';
|
||||||
|
import { ShareHighScoreService } from './share-high-score.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([AcceptedShareEntity])],
|
||||||
|
providers: [ShareAccountingService, ShareHighScoreService],
|
||||||
|
exports: [TypeOrmModule, ShareAccountingService, ShareHighScoreService],
|
||||||
|
})
|
||||||
|
export class ShareAccountingModule { }
|
||||||
@@ -0,0 +1,524 @@
|
|||||||
|
import { ShareAccountingService } from './share-accounting.service';
|
||||||
|
|
||||||
|
describe('ShareAccountingService', () => {
|
||||||
|
const originalEnv = process.env;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
process.env = { ...originalEnv };
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
process.env = originalEnv;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should normalize and save accepted share records', async () => {
|
||||||
|
const repository = {
|
||||||
|
create: jest.fn(value => value),
|
||||||
|
insert: jest.fn().mockResolvedValue({}),
|
||||||
|
};
|
||||||
|
process.env.SHARE_ACCOUNTING_BATCH_SIZE = '1';
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
const acceptedAt = new Date('2026-06-07T12:00:00Z');
|
||||||
|
|
||||||
|
await expect(service.recordAcceptedShare({
|
||||||
|
protocol: 'sv1',
|
||||||
|
acceptedAt,
|
||||||
|
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
|
||||||
|
clientName: 'worker',
|
||||||
|
sessionId: '57a6f098',
|
||||||
|
clientId: '6df7beea-921a-46cb-b7dc-e8075f916232',
|
||||||
|
jobId: '1',
|
||||||
|
jobTemplateId: '2',
|
||||||
|
blockHeight: 900000,
|
||||||
|
creditedDifficulty: 1024,
|
||||||
|
submissionDifficulty: 2048,
|
||||||
|
networkDifficulty: 100000,
|
||||||
|
nonce: 123,
|
||||||
|
ntime: 456,
|
||||||
|
version: 536870912,
|
||||||
|
extraNonce2: 'c708000000000000',
|
||||||
|
isBlockCandidate: false,
|
||||||
|
blockSubmissionResult: null,
|
||||||
|
})).resolves.toEqual(expect.objectContaining({
|
||||||
|
protocol: 'sv1',
|
||||||
|
creditedDifficulty: 1024,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
acceptedAt,
|
||||||
|
payoutMode: 'solo',
|
||||||
|
nonce: '123',
|
||||||
|
ntime: '456',
|
||||||
|
version: '536870912',
|
||||||
|
blockSubmissionResult: null,
|
||||||
|
}));
|
||||||
|
expect(repository.insert).toHaveBeenCalledWith([expect.objectContaining({
|
||||||
|
protocol: 'sv1',
|
||||||
|
payoutMode: 'solo',
|
||||||
|
creditedDifficulty: 1024,
|
||||||
|
})]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should compact only PPLNS shares into payout rollup batches', async () => {
|
||||||
|
process.env.SHARE_ROLLUP_ENABLED = 'true';
|
||||||
|
const manager = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{ locked: true }])
|
||||||
|
.mockResolvedValueOnce([{ lastProcessedShareIndex: '10' }])
|
||||||
|
.mockResolvedValueOnce([{ startShareIndex: '11', endShareIndex: '20', acceptedShareCount: 10 }])
|
||||||
|
.mockResolvedValueOnce([{ startAcceptedAt: new Date('2026-06-14T00:00:00Z'), endAcceptedAt: new Date('2026-06-14T00:01:00Z'), acceptedShareCount: '10', creditedDifficulty: '1000' }])
|
||||||
|
.mockResolvedValueOnce([{ batchId: '99' }])
|
||||||
|
.mockResolvedValueOnce([]),
|
||||||
|
};
|
||||||
|
const repository = {
|
||||||
|
manager: {
|
||||||
|
transaction: jest.fn((callback: any) => callback(manager)),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.processPendingShareRollupBatch()).resolves.toEqual(expect.objectContaining({
|
||||||
|
processed: true,
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
batchId: '99',
|
||||||
|
startShareIndex: '11',
|
||||||
|
endShareIndex: '20',
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(manager.query).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
expect.stringContaining('"payoutMode" = $1'),
|
||||||
|
['pplns'],
|
||||||
|
);
|
||||||
|
expect(manager.query).toHaveBeenNthCalledWith(
|
||||||
|
3,
|
||||||
|
expect.stringContaining('"payoutMode" = $4'),
|
||||||
|
['10', expect.any(Number), expect.any(Number), 'pplns'],
|
||||||
|
);
|
||||||
|
expect(manager.query).toHaveBeenNthCalledWith(
|
||||||
|
6,
|
||||||
|
expect.stringContaining('"payoutMode" = $4'),
|
||||||
|
['99', '11', '20', 'pplns'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept TLS SV1 protocol labels for accounting', async () => {
|
||||||
|
const repository = {
|
||||||
|
create: jest.fn(value => value),
|
||||||
|
insert: jest.fn().mockResolvedValue({}),
|
||||||
|
};
|
||||||
|
process.env.SHARE_ACCOUNTING_BATCH_SIZE = '1';
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.recordAcceptedShare({
|
||||||
|
...buildRecord('sv1-tls'),
|
||||||
|
protocol: 'sv1_tls',
|
||||||
|
})).resolves.toEqual(expect.objectContaining({
|
||||||
|
protocol: 'sv1_tls',
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(repository.insert).toHaveBeenCalledWith([expect.objectContaining({
|
||||||
|
protocol: 'sv1_tls',
|
||||||
|
})]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should batch accepted share inserts until the batch size is reached', async () => {
|
||||||
|
process.env.SHARE_ACCOUNTING_BATCH_SIZE = '2';
|
||||||
|
process.env.SHARE_ACCOUNTING_FLUSH_INTERVAL_MS = '1000';
|
||||||
|
|
||||||
|
const repository = {
|
||||||
|
create: jest.fn(value => value),
|
||||||
|
insert: jest.fn().mockResolvedValue({}),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
const first = service.recordAcceptedShare(buildRecord('1'));
|
||||||
|
expect(repository.insert).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const second = service.recordAcceptedShare(buildRecord('2'));
|
||||||
|
await expect(Promise.all([first, second])).resolves.toHaveLength(2);
|
||||||
|
|
||||||
|
expect(repository.insert).toHaveBeenCalledTimes(1);
|
||||||
|
expect(repository.insert).toHaveBeenCalledWith([
|
||||||
|
expect.objectContaining({ jobId: '1' }),
|
||||||
|
expect.objectContaining({ jobId: '2' }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should flush partial batches on the flush interval', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
process.env.SHARE_ACCOUNTING_BATCH_SIZE = '10';
|
||||||
|
process.env.SHARE_ACCOUNTING_FLUSH_INTERVAL_MS = '25';
|
||||||
|
|
||||||
|
const repository = {
|
||||||
|
create: jest.fn(value => value),
|
||||||
|
insert: jest.fn().mockResolvedValue({}),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
const pending = service.recordAcceptedShare(buildRecord('interval'));
|
||||||
|
expect(repository.insert).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
jest.advanceTimersByTime(25);
|
||||||
|
await expect(pending).resolves.toEqual(expect.objectContaining({ jobId: 'interval' }));
|
||||||
|
expect(repository.insert).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject accepted shares when the accounting queue is full', async () => {
|
||||||
|
process.env.SHARE_ACCOUNTING_BATCH_SIZE = '10';
|
||||||
|
process.env.SHARE_ACCOUNTING_FLUSH_INTERVAL_MS = '1000';
|
||||||
|
process.env.SHARE_ACCOUNTING_MAX_QUEUE_SIZE = '1';
|
||||||
|
|
||||||
|
const repository = {
|
||||||
|
create: jest.fn(value => value),
|
||||||
|
insert: jest.fn().mockResolvedValue({}),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
const queued = service.recordAcceptedShare(buildRecord('queued'));
|
||||||
|
|
||||||
|
await expect(service.recordAcceptedShare(buildRecord('overflow')))
|
||||||
|
.rejects
|
||||||
|
.toThrow('Share accounting queue is full');
|
||||||
|
await service.flushPendingShares();
|
||||||
|
await expect(queued).resolves.toEqual(expect.objectContaining({ jobId: 'queued' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return numeric accounting summaries from the share rollup', async () => {
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '3',
|
||||||
|
totalCreditedDifficulty: '96',
|
||||||
|
acceptedSharesLast10Minutes: '2',
|
||||||
|
creditedDifficultyLast10Minutes: '64',
|
||||||
|
acceptedSharesLastHour: '3',
|
||||||
|
creditedDifficultyLastHour: '96',
|
||||||
|
acceptedSharesLastDay: '3',
|
||||||
|
creditedDifficultyLastDay: '96',
|
||||||
|
hashRateLast10Minutes: '458129844.9',
|
||||||
|
hashRateLastHour: '114532461.2',
|
||||||
|
latestShareAt: new Date('2026-06-07T12:10:00Z'),
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.getAddressSummary('bc1qtest')).resolves.toEqual({
|
||||||
|
totalAcceptedShares: 3,
|
||||||
|
totalCreditedDifficulty: 96,
|
||||||
|
acceptedSharesLast10Minutes: 2,
|
||||||
|
creditedDifficultyLast10Minutes: 64,
|
||||||
|
acceptedSharesLastHour: 3,
|
||||||
|
creditedDifficultyLastHour: 96,
|
||||||
|
acceptedSharesLastDay: 3,
|
||||||
|
creditedDifficultyLastDay: 96,
|
||||||
|
hashRateLast10Minutes: 458129844.9,
|
||||||
|
hashRateLastHour: 114532461.2,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
bestSubmissionDifficultyAt: null,
|
||||||
|
workSinceLastBlock: 0,
|
||||||
|
currentRoundAcceptedShares: 0,
|
||||||
|
currentRoundNetworkDifficulty: 0,
|
||||||
|
networkDifficultyPercent: 0,
|
||||||
|
blockCandidateCount: 0,
|
||||||
|
latestShareAt: '2026-06-07T12:10:00.000Z',
|
||||||
|
protocolBreakdown: [],
|
||||||
|
});
|
||||||
|
expect(repository.query).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
expect.stringContaining('"accepted_share_10m"'),
|
||||||
|
['bc1qtest'],
|
||||||
|
);
|
||||||
|
expect(repository.query).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should serve API-only address accounting from the share rollup instead of empty summaries', async () => {
|
||||||
|
process.env.API_ONLY = 'true';
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '12',
|
||||||
|
totalCreditedDifficulty: '384',
|
||||||
|
acceptedSharesLast10Minutes: '4',
|
||||||
|
creditedDifficultyLast10Minutes: '128',
|
||||||
|
acceptedSharesLastHour: '10',
|
||||||
|
creditedDifficultyLastHour: '320',
|
||||||
|
acceptedSharesLastDay: '12',
|
||||||
|
creditedDifficultyLastDay: '384',
|
||||||
|
hashRateLast10Minutes: '916259689.8',
|
||||||
|
hashRateLastHour: '381774870.2',
|
||||||
|
latestShareAt: new Date('2026-06-07T12:30:00Z'),
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.getAddressSummary('bc1qapi')).resolves.toEqual(expect.objectContaining({
|
||||||
|
totalAcceptedShares: 12,
|
||||||
|
totalCreditedDifficulty: 384,
|
||||||
|
acceptedSharesLast10Minutes: 4,
|
||||||
|
creditedDifficultyLast10Minutes: 128,
|
||||||
|
hashRateLast10Minutes: 916259689.8,
|
||||||
|
latestShareAt: '2026-06-07T12:30:00.000Z',
|
||||||
|
}));
|
||||||
|
expect(repository.query).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('FROM "accepted_share_10m"'),
|
||||||
|
['bc1qapi'],
|
||||||
|
);
|
||||||
|
expect(repository.query).not.toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('FROM "accepted_share_entity"'),
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use Redis cache for share accounting summaries across API workers', async () => {
|
||||||
|
process.env.SHARE_ACCOUNTING_SUMMARY_CACHE_MS = '0';
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '1',
|
||||||
|
totalCreditedDifficulty: '32',
|
||||||
|
acceptedSharesLast10Minutes: '1',
|
||||||
|
creditedDifficultyLast10Minutes: '32',
|
||||||
|
acceptedSharesLastHour: '1',
|
||||||
|
creditedDifficultyLastHour: '32',
|
||||||
|
acceptedSharesLastDay: '1',
|
||||||
|
creditedDifficultyLastDay: '32',
|
||||||
|
hashRateLast10Minutes: '1',
|
||||||
|
hashRateLastHour: '1',
|
||||||
|
latestShareAt: null,
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
const redis = {
|
||||||
|
getJsonCache: jest.fn()
|
||||||
|
.mockResolvedValueOnce(null)
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
...new ShareAccountingService(repository as any).emptySummary(),
|
||||||
|
totalAcceptedShares: 1,
|
||||||
|
}),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any, redis as any);
|
||||||
|
|
||||||
|
await service.getAddressSummary('bc1qcached');
|
||||||
|
await expect(service.getAddressSummary('bc1qcached')).resolves.toEqual(expect.objectContaining({
|
||||||
|
totalAcceptedShares: 1,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(repository.query).toHaveBeenCalledTimes(1);
|
||||||
|
expect(redis.setJsonCache).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('accounting:summary:'),
|
||||||
|
expect.objectContaining({ totalAcceptedShares: 1 }),
|
||||||
|
30000,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should refresh pool summaries from completed rollup buckets and current round rollups', async () => {
|
||||||
|
const redis = {
|
||||||
|
getJsonCache: jest.fn().mockResolvedValue(null),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '3',
|
||||||
|
totalCreditedDifficulty: '96',
|
||||||
|
acceptedSharesLast10Minutes: '2',
|
||||||
|
creditedDifficultyLast10Minutes: '64',
|
||||||
|
acceptedSharesLastHour: '3',
|
||||||
|
creditedDifficultyLastHour: '96',
|
||||||
|
acceptedSharesLastDay: '3',
|
||||||
|
creditedDifficultyLastDay: '96',
|
||||||
|
hashRateLast10Minutes: '458129844.9',
|
||||||
|
hashRateLastHour: '114532461.2',
|
||||||
|
latestShareAt: new Date('2026-06-07T12:10:00Z'),
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
bestSubmissionDifficulty: '4096',
|
||||||
|
bestSubmissionDifficultyAt: new Date('2026-06-07T12:10:00Z'),
|
||||||
|
currentRoundAcceptedShares: '11',
|
||||||
|
workSinceLastBlock: '352',
|
||||||
|
currentRoundNetworkDifficulty: '1000',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([]),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any, redis as any);
|
||||||
|
|
||||||
|
await expect(service.refreshPoolSummary()).resolves.toEqual(expect.objectContaining({
|
||||||
|
acceptedSharesLast10Minutes: 2,
|
||||||
|
creditedDifficultyLast10Minutes: 64,
|
||||||
|
hashRateLast10Minutes: 458129844.9,
|
||||||
|
bestSubmissionDifficulty: 4096,
|
||||||
|
bestSubmissionDifficultyAt: '2026-06-07T12:10:00.000Z',
|
||||||
|
workSinceLastBlock: 352,
|
||||||
|
currentRoundAcceptedShares: 11,
|
||||||
|
currentRoundNetworkDifficulty: 1000,
|
||||||
|
networkDifficultyPercent: 35.2,
|
||||||
|
latestShareAt: '2026-06-07T12:10:00.000Z',
|
||||||
|
}));
|
||||||
|
expect(repository.query).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
expect.stringContaining('FROM "accepted_share_block_10m"'),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
expect(repository.query).toHaveBeenNthCalledWith(
|
||||||
|
3,
|
||||||
|
expect.stringContaining('FROM "accepted_share_high_score"'),
|
||||||
|
['all'],
|
||||||
|
);
|
||||||
|
expect(repository.query).not.toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('FROM "accepted_share_entity"'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should retain best submitted share after raw share retention removes older rows', async () => {
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '3',
|
||||||
|
totalCreditedDifficulty: '96',
|
||||||
|
acceptedSharesLast10Minutes: '2',
|
||||||
|
creditedDifficultyLast10Minutes: '64',
|
||||||
|
acceptedSharesLastHour: '3',
|
||||||
|
creditedDifficultyLastHour: '96',
|
||||||
|
acceptedSharesLastDay: '3',
|
||||||
|
creditedDifficultyLastDay: '96',
|
||||||
|
hashRateLast10Minutes: '458129844.9',
|
||||||
|
hashRateLastHour: '114532461.2',
|
||||||
|
latestShareAt: new Date('2026-06-07T12:10:00Z'),
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
bestSubmissionDifficulty: '4096',
|
||||||
|
bestSubmissionDifficultyAt: new Date('2026-06-07T12:10:00Z'),
|
||||||
|
currentRoundAcceptedShares: '11',
|
||||||
|
workSinceLastBlock: '352',
|
||||||
|
currentRoundNetworkDifficulty: '1000',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
bestSubmissionDifficulty: '8192',
|
||||||
|
bestSubmissionDifficultyAt: new Date('2026-06-01T12:10:00Z'),
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.refreshPoolSummary()).resolves.toEqual(expect.objectContaining({
|
||||||
|
bestSubmissionDifficulty: 8192,
|
||||||
|
bestSubmissionDifficultyAt: '2026-06-01T12:10:00.000Z',
|
||||||
|
workSinceLastBlock: 352,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should cache accounting summaries briefly to protect hot dashboard endpoints', async () => {
|
||||||
|
process.env.SHARE_ACCOUNTING_SUMMARY_CACHE_MS = '1000';
|
||||||
|
const repository = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
totalAcceptedShares: '1',
|
||||||
|
totalCreditedDifficulty: '32',
|
||||||
|
acceptedSharesLast10Minutes: '1',
|
||||||
|
creditedDifficultyLast10Minutes: '32',
|
||||||
|
acceptedSharesLastHour: '1',
|
||||||
|
creditedDifficultyLastHour: '32',
|
||||||
|
acceptedSharesLastDay: '1',
|
||||||
|
creditedDifficultyLastDay: '32',
|
||||||
|
hashRateLast10Minutes: '1',
|
||||||
|
hashRateLastHour: '1',
|
||||||
|
latestShareAt: null,
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await service.getPoolSummary();
|
||||||
|
await service.getPoolSummary();
|
||||||
|
|
||||||
|
expect(repository.query).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should finalize accepted shares into an append-only share rollup batch', async () => {
|
||||||
|
const manager = {
|
||||||
|
query: jest.fn()
|
||||||
|
.mockResolvedValueOnce([{ locked: true }])
|
||||||
|
.mockResolvedValueOnce([{ lastProcessedShareIndex: '10' }])
|
||||||
|
.mockResolvedValueOnce([{ startShareIndex: '11', endShareIndex: '20', acceptedShareCount: 10 }])
|
||||||
|
.mockResolvedValueOnce([{
|
||||||
|
startAcceptedAt: new Date('2026-06-07T12:00:00Z'),
|
||||||
|
endAcceptedAt: new Date('2026-06-07T12:00:30Z'),
|
||||||
|
acceptedShareCount: '10',
|
||||||
|
creditedDifficulty: '2048',
|
||||||
|
}])
|
||||||
|
.mockResolvedValueOnce([{ batchId: '7' }])
|
||||||
|
.mockResolvedValueOnce([]),
|
||||||
|
};
|
||||||
|
const repository = {
|
||||||
|
manager: {
|
||||||
|
transaction: jest.fn(callback => callback(manager)),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.processPendingShareRollupBatch()).resolves.toEqual({
|
||||||
|
processed: true,
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
batchId: '7',
|
||||||
|
startShareIndex: '11',
|
||||||
|
endShareIndex: '20',
|
||||||
|
acceptedShareCount: 10,
|
||||||
|
creditedDifficulty: 2048,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repository.manager.transaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(manager.query).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
expect.stringContaining('pg_try_advisory_xact_lock'),
|
||||||
|
['1780962600'],
|
||||||
|
);
|
||||||
|
expect(manager.query).toHaveBeenNthCalledWith(
|
||||||
|
6,
|
||||||
|
expect.stringContaining('INSERT INTO "share_rollup_batch_summary"'),
|
||||||
|
['7', '11', '20', 'pplns'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should skip share rollup work when another process holds the advisory lock', async () => {
|
||||||
|
const manager = {
|
||||||
|
query: jest.fn().mockResolvedValueOnce([{ locked: false }]),
|
||||||
|
};
|
||||||
|
const repository = {
|
||||||
|
manager: {
|
||||||
|
transaction: jest.fn(callback => callback(manager)),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const service = new ShareAccountingService(repository as any);
|
||||||
|
|
||||||
|
await expect(service.processPendingShareRollupBatch()).resolves.toEqual({
|
||||||
|
processed: false,
|
||||||
|
reason: 'locked',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(manager.query).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function buildRecord(jobId: string) {
|
||||||
|
return {
|
||||||
|
protocol: 'sv1' as const,
|
||||||
|
acceptedAt: new Date('2026-06-07T12:00:00Z'),
|
||||||
|
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
|
||||||
|
clientName: 'worker',
|
||||||
|
sessionId: '57a6f098',
|
||||||
|
clientId: '6df7beea-921a-46cb-b7dc-e8075f916232',
|
||||||
|
jobId,
|
||||||
|
jobTemplateId: 'template',
|
||||||
|
blockHeight: 900000,
|
||||||
|
creditedDifficulty: 1024,
|
||||||
|
submissionDifficulty: 2048,
|
||||||
|
networkDifficulty: 100000,
|
||||||
|
nonce: 123,
|
||||||
|
ntime: 456,
|
||||||
|
version: 536870912,
|
||||||
|
extraNonce2: 'c708000000000000',
|
||||||
|
isBlockCandidate: false,
|
||||||
|
blockSubmissionResult: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,844 @@
|
|||||||
|
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
|
||||||
|
import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity';
|
||||||
|
import { RedisMessagingService } from '../../services/redis-messaging.service';
|
||||||
|
import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
export interface AcceptedShareRecord {
|
||||||
|
protocol: 'sv1' | 'sv1_tls' | 'sv2' | 'sv2_jdp' | 'datum';
|
||||||
|
payoutMode?: PayoutMode;
|
||||||
|
workSource?: 'pool_template' | 'miner_template';
|
||||||
|
workProtocol?: 'pool' | 'sv2_jdp' | 'datum';
|
||||||
|
acceptedAt?: Date;
|
||||||
|
address: string;
|
||||||
|
clientName: string;
|
||||||
|
sessionId: string;
|
||||||
|
clientId: string;
|
||||||
|
jobId: string;
|
||||||
|
jobTemplateId: string;
|
||||||
|
blockHeight: number;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
submissionDifficulty: number;
|
||||||
|
networkDifficulty: number;
|
||||||
|
nonce: string | number;
|
||||||
|
ntime: string | number;
|
||||||
|
version: string | number;
|
||||||
|
extraNonce2: string;
|
||||||
|
isBlockCandidate: boolean;
|
||||||
|
blockSubmissionResult?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareAccountingSummary {
|
||||||
|
totalAcceptedShares: number;
|
||||||
|
totalCreditedDifficulty: number;
|
||||||
|
acceptedSharesLast10Minutes: number;
|
||||||
|
creditedDifficultyLast10Minutes: number;
|
||||||
|
acceptedSharesLastHour: number;
|
||||||
|
creditedDifficultyLastHour: number;
|
||||||
|
acceptedSharesLastDay: number;
|
||||||
|
creditedDifficultyLastDay: number;
|
||||||
|
hashRateLast10Minutes: number;
|
||||||
|
hashRateLastHour: number;
|
||||||
|
bestSubmissionDifficulty: number;
|
||||||
|
bestSubmissionDifficultyAt: string | null;
|
||||||
|
workSinceLastBlock: number;
|
||||||
|
currentRoundAcceptedShares: number;
|
||||||
|
currentRoundNetworkDifficulty: number;
|
||||||
|
networkDifficultyPercent: number;
|
||||||
|
blockCandidateCount: number;
|
||||||
|
latestShareAt: string | null;
|
||||||
|
protocolBreakdown: {
|
||||||
|
protocol: string;
|
||||||
|
acceptedShares: number;
|
||||||
|
creditedDifficulty: number;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionShareSummary {
|
||||||
|
clientId: string;
|
||||||
|
latestShareAt: string | null;
|
||||||
|
hashRateLast10Minutes: number;
|
||||||
|
bestSubmissionDifficulty: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareRollupBatchResult {
|
||||||
|
processed: boolean;
|
||||||
|
reason?: 'disabled' | 'locked' | 'no-shares';
|
||||||
|
payoutMode?: PayoutMode;
|
||||||
|
batchId?: string;
|
||||||
|
startShareIndex?: string;
|
||||||
|
endShareIndex?: string;
|
||||||
|
acceptedShareCount?: number;
|
||||||
|
creditedDifficulty?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AccountingFilter {
|
||||||
|
address?: string;
|
||||||
|
clientName?: string;
|
||||||
|
clientId?: string;
|
||||||
|
payoutMode?: PayoutMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HASHES_PER_DIFFICULTY = 4294967296;
|
||||||
|
const ROLLUP_BUCKET_SECONDS = 600;
|
||||||
|
const DEFAULT_BATCH_SIZE = 500;
|
||||||
|
const DEFAULT_FLUSH_INTERVAL_MS = 25;
|
||||||
|
const DEFAULT_MAX_QUEUE_SIZE = 50000;
|
||||||
|
const DEFAULT_SUMMARY_CACHE_MS = 2500;
|
||||||
|
const DEFAULT_SUMMARY_CACHE_MAX = 10000;
|
||||||
|
const DEFAULT_REDIS_SUMMARY_CACHE_MS = 30000;
|
||||||
|
const DEFAULT_ROLLUP_INTERVAL_MS = 60000;
|
||||||
|
const DEFAULT_ROLLUP_SAFETY_LAG_SECONDS = 10;
|
||||||
|
const DEFAULT_ROLLUP_MAX_SHARES_PER_BATCH = 5000000;
|
||||||
|
const SHARE_ROLLUP_ADVISORY_LOCK = '1780962600';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private pendingShares: PendingShare[] = [];
|
||||||
|
private flushTimer: NodeJS.Timeout | null = null;
|
||||||
|
private activeFlush: Promise<void> | null = null;
|
||||||
|
private rollupTimer: NodeJS.Timeout | null = null;
|
||||||
|
private activeRollup: Promise<void> | null = null;
|
||||||
|
private summaryCache = new Map<string, SummaryCacheEntry>();
|
||||||
|
private readonly poolSummaryCacheKey = 'accounting:pool-summary';
|
||||||
|
private readonly batchSize = this.readPositiveInt('SHARE_ACCOUNTING_BATCH_SIZE', DEFAULT_BATCH_SIZE);
|
||||||
|
private readonly flushIntervalMs = this.readPositiveInt('SHARE_ACCOUNTING_FLUSH_INTERVAL_MS', DEFAULT_FLUSH_INTERVAL_MS);
|
||||||
|
private readonly maxQueueSize = this.readPositiveInt('SHARE_ACCOUNTING_MAX_QUEUE_SIZE', DEFAULT_MAX_QUEUE_SIZE);
|
||||||
|
private readonly summaryCacheMs = this.readNonNegativeInt('SHARE_ACCOUNTING_SUMMARY_CACHE_MS', DEFAULT_SUMMARY_CACHE_MS);
|
||||||
|
private readonly summaryCacheMax = this.readPositiveInt('SHARE_ACCOUNTING_SUMMARY_CACHE_MAX', DEFAULT_SUMMARY_CACHE_MAX);
|
||||||
|
private readonly redisSummaryCacheMs = this.readNonNegativeInt('SHARE_ACCOUNTING_REDIS_SUMMARY_CACHE_MS', DEFAULT_REDIS_SUMMARY_CACHE_MS);
|
||||||
|
private readonly shareRollupEnabled = this.readBoolean('SHARE_ROLLUP_ENABLED', true);
|
||||||
|
private readonly shareRollupIntervalMs = this.readPositiveInt('SHARE_ROLLUP_INTERVAL_MS', DEFAULT_ROLLUP_INTERVAL_MS);
|
||||||
|
private readonly shareRollupSafetyLagSeconds = this.readNonNegativeInt('SHARE_ROLLUP_SAFETY_LAG_SECONDS', DEFAULT_ROLLUP_SAFETY_LAG_SECONDS);
|
||||||
|
private readonly shareRollupMaxSharesPerBatch = this.readPositiveInt('SHARE_ROLLUP_MAX_SHARES_PER_BATCH', DEFAULT_ROLLUP_MAX_SHARES_PER_BATCH);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(AcceptedShareEntity)
|
||||||
|
private readonly acceptedShareRepository: Repository<AcceptedShareEntity>,
|
||||||
|
private readonly redisMessagingService?: RedisMessagingService,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
public onModuleInit(): void {
|
||||||
|
this.startShareRollupTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async recordAcceptedShare(record: AcceptedShareRecord): Promise<AcceptedShareEntity> {
|
||||||
|
const acceptedShare = this.acceptedShareRepository.create({
|
||||||
|
...record,
|
||||||
|
payoutMode: normalizePayoutMode(record.payoutMode),
|
||||||
|
workSource: record.workSource ?? 'pool_template',
|
||||||
|
workProtocol: record.workProtocol ?? 'pool',
|
||||||
|
acceptedAt: record.acceptedAt ?? new Date(),
|
||||||
|
nonce: record.nonce.toString(),
|
||||||
|
ntime: record.ntime.toString(),
|
||||||
|
version: record.version.toString(),
|
||||||
|
blockSubmissionResult: record.blockSubmissionResult == null
|
||||||
|
? null
|
||||||
|
: record.blockSubmissionResult.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.pendingShares.length >= this.maxQueueSize) {
|
||||||
|
throw new Error(`Share accounting queue is full (${this.maxQueueSize})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await new Promise<AcceptedShareEntity>((resolve, reject) => {
|
||||||
|
this.pendingShares.push({ entity: acceptedShare, resolve, reject });
|
||||||
|
|
||||||
|
if (this.pendingShares.length >= this.batchSize) {
|
||||||
|
this.startFlush();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleFlush();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async flushPendingShares(): Promise<void> {
|
||||||
|
while (this.pendingShares.length > 0 || this.activeFlush != null) {
|
||||||
|
if (this.activeFlush != null) {
|
||||||
|
await this.activeFlush;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.startFlush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async onModuleDestroy(): Promise<void> {
|
||||||
|
if (this.rollupTimer != null) {
|
||||||
|
clearInterval(this.rollupTimer);
|
||||||
|
this.rollupTimer = null;
|
||||||
|
}
|
||||||
|
if (this.activeRollup != null) {
|
||||||
|
await this.activeRollup;
|
||||||
|
}
|
||||||
|
await this.flushPendingShares();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async processPendingShareRollupBatch(): Promise<ShareRollupBatchResult> {
|
||||||
|
if (!this.shareRollupEnabled) {
|
||||||
|
return { processed: false, reason: 'disabled' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.acceptedShareRepository.manager.transaction(async manager => {
|
||||||
|
const [lockRow] = await manager.query(`
|
||||||
|
SELECT pg_try_advisory_xact_lock($1::bigint) AS "locked"
|
||||||
|
`, [SHARE_ROLLUP_ADVISORY_LOCK]);
|
||||||
|
|
||||||
|
if (lockRow?.locked !== true) {
|
||||||
|
return { processed: false, reason: 'locked' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const payoutMode: PayoutMode = 'pplns';
|
||||||
|
const [lastRow] = await manager.query(`
|
||||||
|
SELECT COALESCE(MAX("endShareIndex"), 0)::text AS "lastProcessedShareIndex"
|
||||||
|
FROM "share_rollup_batch"
|
||||||
|
WHERE "status" = 'finalized'
|
||||||
|
AND "payoutMode" = $1
|
||||||
|
`, [payoutMode]);
|
||||||
|
const lastProcessedShareIndex = lastRow?.lastProcessedShareIndex ?? '0';
|
||||||
|
|
||||||
|
const [rangeRow] = await manager.query(`
|
||||||
|
WITH last_state AS MATERIALIZED (
|
||||||
|
SELECT $1::bigint AS "lastProcessedShareIndex"
|
||||||
|
),
|
||||||
|
first_unstable AS MATERIALIZED (
|
||||||
|
SELECT MIN("shareIndex") AS "firstUnstableShareIndex"
|
||||||
|
FROM "accepted_share_entity", last_state
|
||||||
|
WHERE "shareIndex" > last_state."lastProcessedShareIndex"
|
||||||
|
AND "payoutMode" = $4
|
||||||
|
AND "acceptedAt" > NOW() - ($2::int * INTERVAL '1 second')
|
||||||
|
),
|
||||||
|
stable_bound AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
CASE
|
||||||
|
WHEN (SELECT "firstUnstableShareIndex" FROM first_unstable) IS NULL THEN (
|
||||||
|
SELECT MAX("shareIndex")
|
||||||
|
FROM "accepted_share_entity", last_state
|
||||||
|
WHERE "shareIndex" > last_state."lastProcessedShareIndex"
|
||||||
|
AND "payoutMode" = $4
|
||||||
|
)
|
||||||
|
ELSE (SELECT "firstUnstableShareIndex" FROM first_unstable) - 1
|
||||||
|
END AS "maxStableShareIndex"
|
||||||
|
),
|
||||||
|
bounded AS MATERIALIZED (
|
||||||
|
SELECT "shareIndex"
|
||||||
|
FROM "accepted_share_entity", last_state, stable_bound
|
||||||
|
WHERE "shareIndex" > last_state."lastProcessedShareIndex"
|
||||||
|
AND "shareIndex" <= stable_bound."maxStableShareIndex"
|
||||||
|
AND "payoutMode" = $4
|
||||||
|
ORDER BY "shareIndex" ASC
|
||||||
|
LIMIT $3::int
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MIN("shareIndex")::text AS "startShareIndex",
|
||||||
|
MAX("shareIndex")::text AS "endShareIndex",
|
||||||
|
COUNT(*)::int AS "acceptedShareCount"
|
||||||
|
FROM bounded
|
||||||
|
`, [
|
||||||
|
lastProcessedShareIndex,
|
||||||
|
this.shareRollupSafetyLagSeconds,
|
||||||
|
this.shareRollupMaxSharesPerBatch,
|
||||||
|
payoutMode,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (rangeRow?.startShareIndex == null || rangeRow?.endShareIndex == null || this.toNumber(rangeRow.acceptedShareCount) === 0) {
|
||||||
|
return { processed: false, reason: 'no-shares' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const [statsRow] = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
MIN("acceptedAt") AS "startAcceptedAt",
|
||||||
|
MAX("acceptedAt") AS "endAcceptedAt",
|
||||||
|
COUNT(*)::bigint AS "acceptedShareCount",
|
||||||
|
COALESCE(SUM("creditedDifficulty"), 0)::numeric AS "creditedDifficulty"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
WHERE "shareIndex" >= $1::bigint
|
||||||
|
AND "shareIndex" <= $2::bigint
|
||||||
|
AND "payoutMode" = $3
|
||||||
|
`, [rangeRow.startShareIndex, rangeRow.endShareIndex, payoutMode]);
|
||||||
|
|
||||||
|
if (statsRow?.startAcceptedAt == null || this.toNumber(statsRow.acceptedShareCount) === 0) {
|
||||||
|
return { processed: false, reason: 'no-shares' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const [batchRow] = await manager.query(`
|
||||||
|
INSERT INTO "share_rollup_batch" (
|
||||||
|
"startShareIndex",
|
||||||
|
"endShareIndex",
|
||||||
|
"payoutMode",
|
||||||
|
"startAcceptedAt",
|
||||||
|
"endAcceptedAt",
|
||||||
|
"acceptedShareCount",
|
||||||
|
"creditedDifficulty",
|
||||||
|
"status",
|
||||||
|
"finalizedAt"
|
||||||
|
) VALUES (
|
||||||
|
$1::bigint,
|
||||||
|
$2::bigint,
|
||||||
|
$3,
|
||||||
|
$4::timestamptz,
|
||||||
|
$5::timestamptz,
|
||||||
|
$6::bigint,
|
||||||
|
$7::numeric,
|
||||||
|
'finalized',
|
||||||
|
NOW()
|
||||||
|
)
|
||||||
|
RETURNING "id"::text AS "batchId"
|
||||||
|
`, [
|
||||||
|
rangeRow.startShareIndex,
|
||||||
|
rangeRow.endShareIndex,
|
||||||
|
payoutMode,
|
||||||
|
statsRow.startAcceptedAt,
|
||||||
|
statsRow.endAcceptedAt,
|
||||||
|
statsRow.acceptedShareCount,
|
||||||
|
statsRow.creditedDifficulty,
|
||||||
|
]);
|
||||||
|
|
||||||
|
await manager.query(`
|
||||||
|
INSERT INTO "share_rollup_batch_summary" (
|
||||||
|
"batchId",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"protocol",
|
||||||
|
"blockHeight",
|
||||||
|
"creditedDifficulty",
|
||||||
|
"acceptedShareCount",
|
||||||
|
"bestSubmissionDifficulty",
|
||||||
|
"firstShareAt",
|
||||||
|
"lastShareAt"
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
$1::bigint AS "batchId",
|
||||||
|
"payoutMode",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"protocol",
|
||||||
|
"blockHeight",
|
||||||
|
SUM("creditedDifficulty") AS "creditedDifficulty",
|
||||||
|
COUNT(*)::bigint AS "acceptedShareCount",
|
||||||
|
MAX("submissionDifficulty") AS "bestSubmissionDifficulty",
|
||||||
|
MIN("acceptedAt") AS "firstShareAt",
|
||||||
|
MAX("acceptedAt") AS "lastShareAt"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
WHERE "shareIndex" >= $2::bigint
|
||||||
|
AND "shareIndex" <= $3::bigint
|
||||||
|
AND "payoutMode" = $4
|
||||||
|
GROUP BY "payoutMode", "address", "clientName", "protocol", "blockHeight"
|
||||||
|
`, [
|
||||||
|
batchRow.batchId,
|
||||||
|
rangeRow.startShareIndex,
|
||||||
|
rangeRow.endShareIndex,
|
||||||
|
payoutMode,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
processed: true,
|
||||||
|
payoutMode,
|
||||||
|
batchId: batchRow.batchId,
|
||||||
|
startShareIndex: rangeRow.startShareIndex,
|
||||||
|
endShareIndex: rangeRow.endShareIndex,
|
||||||
|
acceptedShareCount: this.toNumber(statsRow.acceptedShareCount),
|
||||||
|
creditedDifficulty: this.toNumber(statsRow.creditedDifficulty),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getPoolSummary(payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
const mode = payoutMode == null ? undefined : normalizePayoutMode(payoutMode);
|
||||||
|
const poolSummaryCacheKey = mode == null ? this.poolSummaryCacheKey : `${this.poolSummaryCacheKey}:${mode}`;
|
||||||
|
const cached = await this.redisMessagingService
|
||||||
|
?.getJsonCache<ShareAccountingSummary>(poolSummaryCacheKey)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Pool accounting summary cache read failed: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.API_ONLY === 'true') {
|
||||||
|
return this.emptySummary();
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.getSummary({ payoutMode: mode });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refreshPoolSummary(payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
const mode = payoutMode == null ? undefined : normalizePayoutMode(payoutMode);
|
||||||
|
const poolSummaryCacheKey = mode == null ? this.poolSummaryCacheKey : `${this.poolSummaryCacheKey}:${mode}`;
|
||||||
|
const summary = await this.withPoolRollupOverlay(await this.getSummary({ payoutMode: mode }), mode);
|
||||||
|
await this.redisMessagingService
|
||||||
|
?.setJsonCache(poolSummaryCacheKey, summary, 10 * 60 * 1000)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Pool accounting summary cache write failed: ${error.message}`);
|
||||||
|
});
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async withPoolRollupOverlay(summary: ShareAccountingSummary, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
if (process.env.API_ONLY === 'true') {
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [currentRoundRow] = await this.acceptedShareRepository.query(`
|
||||||
|
WITH latest_found_block AS (
|
||||||
|
SELECT COALESCE(MAX("height"), 0) AS "height"
|
||||||
|
FROM "blocks_entity"
|
||||||
|
${payoutMode == null ? '' : 'WHERE "payoutMode" = $1'}
|
||||||
|
),
|
||||||
|
filtered_rows AS (
|
||||||
|
SELECT "accepted_share_block_10m".*
|
||||||
|
FROM "accepted_share_block_10m", latest_found_block
|
||||||
|
WHERE "blockHeight" > latest_found_block."height"
|
||||||
|
${payoutMode == null ? '' : 'AND "payoutMode" = $1'}
|
||||||
|
),
|
||||||
|
best_share AS (
|
||||||
|
SELECT
|
||||||
|
"bestSubmissionDifficulty",
|
||||||
|
"bucket"
|
||||||
|
FROM filtered_rows
|
||||||
|
ORDER BY "bestSubmissionDifficulty" DESC, "bucket" DESC
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM("acceptedCount"), 0)::int AS "currentRoundAcceptedShares",
|
||||||
|
COALESCE(SUM("shares"), 0)::float AS "workSinceLastBlock",
|
||||||
|
COALESCE(MAX("networkDifficulty"), 0)::float AS "currentRoundNetworkDifficulty",
|
||||||
|
COALESCE((SELECT "bestSubmissionDifficulty" FROM best_share), 0)::float AS "bestSubmissionDifficulty",
|
||||||
|
(SELECT "bucket" FROM best_share) AS "bestSubmissionDifficultyAt"
|
||||||
|
FROM filtered_rows
|
||||||
|
`, payoutMode == null ? [] : [payoutMode]);
|
||||||
|
const currentRoundNetworkDifficulty = this.toNumber(currentRoundRow?.currentRoundNetworkDifficulty);
|
||||||
|
const workSinceLastBlock = this.toNumber(currentRoundRow?.workSinceLastBlock);
|
||||||
|
const liveBestSubmissionDifficulty = this.toNumber(currentRoundRow?.bestSubmissionDifficulty);
|
||||||
|
const liveBestSubmissionDifficultyAt = currentRoundRow?.bestSubmissionDifficultyAt == null
|
||||||
|
? null
|
||||||
|
: new Date(currentRoundRow.bestSubmissionDifficultyAt).toISOString();
|
||||||
|
const retainedBest = await this.getRetainedBestSubmissionDifficulty(payoutMode);
|
||||||
|
const retainedBestSubmissionDifficulty = this.toNumber(retainedBest?.bestSubmissionDifficulty);
|
||||||
|
const useRetainedBest = retainedBestSubmissionDifficulty > liveBestSubmissionDifficulty;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...summary,
|
||||||
|
bestSubmissionDifficulty: useRetainedBest
|
||||||
|
? retainedBestSubmissionDifficulty
|
||||||
|
: liveBestSubmissionDifficulty,
|
||||||
|
bestSubmissionDifficultyAt: useRetainedBest
|
||||||
|
? retainedBest?.bestSubmissionDifficultyAt ?? null
|
||||||
|
: liveBestSubmissionDifficultyAt,
|
||||||
|
workSinceLastBlock,
|
||||||
|
currentRoundAcceptedShares: this.toNumber(currentRoundRow?.currentRoundAcceptedShares),
|
||||||
|
currentRoundNetworkDifficulty,
|
||||||
|
networkDifficultyPercent: currentRoundNetworkDifficulty > 0
|
||||||
|
? this.roundPercent((workSinceLastBlock / currentRoundNetworkDifficulty) * 100)
|
||||||
|
: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getRetainedBestSubmissionDifficulty(payoutMode?: PayoutMode): Promise<{
|
||||||
|
bestSubmissionDifficulty: number;
|
||||||
|
bestSubmissionDifficultyAt: string | null;
|
||||||
|
} | null> {
|
||||||
|
try {
|
||||||
|
const [row] = await this.acceptedShareRepository.query(`
|
||||||
|
SELECT
|
||||||
|
"submissionDifficulty"::float AS "bestSubmissionDifficulty",
|
||||||
|
"acceptedAt" AS "bestSubmissionDifficultyAt"
|
||||||
|
FROM "accepted_share_high_score"
|
||||||
|
WHERE "scope" = 'all_time'
|
||||||
|
AND "payoutMode" = $1
|
||||||
|
ORDER BY "submissionDifficulty" DESC, "acceptedAt" DESC
|
||||||
|
LIMIT 1
|
||||||
|
`, [payoutMode ?? 'all']);
|
||||||
|
|
||||||
|
if (row == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
bestSubmissionDifficulty: this.toNumber(row.bestSubmissionDifficulty),
|
||||||
|
bestSubmissionDifficultyAt: row.bestSubmissionDifficultyAt == null
|
||||||
|
? null
|
||||||
|
: new Date(row.bestSubmissionDifficultyAt).toISOString(),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === '42P01') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public emptySummary(): ShareAccountingSummary {
|
||||||
|
return {
|
||||||
|
totalAcceptedShares: 0,
|
||||||
|
totalCreditedDifficulty: 0,
|
||||||
|
acceptedSharesLast10Minutes: 0,
|
||||||
|
creditedDifficultyLast10Minutes: 0,
|
||||||
|
acceptedSharesLastHour: 0,
|
||||||
|
creditedDifficultyLastHour: 0,
|
||||||
|
acceptedSharesLastDay: 0,
|
||||||
|
creditedDifficultyLastDay: 0,
|
||||||
|
hashRateLast10Minutes: 0,
|
||||||
|
hashRateLastHour: 0,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
bestSubmissionDifficultyAt: null,
|
||||||
|
workSinceLastBlock: 0,
|
||||||
|
currentRoundAcceptedShares: 0,
|
||||||
|
currentRoundNetworkDifficulty: 0,
|
||||||
|
networkDifficultyPercent: 0,
|
||||||
|
blockCandidateCount: 0,
|
||||||
|
latestShareAt: null,
|
||||||
|
protocolBreakdown: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAddressSummary(address: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
return this.getSummary({ address, payoutMode });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getWorkerGroupSummary(address: string, clientName: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
return this.getSummary({ address, clientName, payoutMode });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getSessionSummary(clientId: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
|
||||||
|
return this.getSummary({ clientId, payoutMode });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getSessionSummaries(clientIds: string[]): Promise<Map<string, SessionShareSummary>> {
|
||||||
|
const uniqueClientIds = [...new Set(clientIds.filter(clientId => clientId != null))];
|
||||||
|
const summaries = new Map<string, SessionShareSummary>();
|
||||||
|
if (uniqueClientIds.length === 0 || process.env.API_ONLY === 'true') {
|
||||||
|
return summaries;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await this.acceptedShareRepository.query(`
|
||||||
|
WITH clock AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', NOW()) AS "currentBucket"
|
||||||
|
),
|
||||||
|
latest_bucket AS MATERIALIZED (
|
||||||
|
SELECT "bucket"
|
||||||
|
FROM "accepted_share_10m", clock
|
||||||
|
WHERE "bucket" < clock."currentBucket"
|
||||||
|
ORDER BY "bucket" DESC
|
||||||
|
LIMIT 1
|
||||||
|
),
|
||||||
|
bounds AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
"currentBucket",
|
||||||
|
COALESCE(
|
||||||
|
(SELECT "bucket" FROM latest_bucket),
|
||||||
|
"currentBucket" - INTERVAL '10 minutes'
|
||||||
|
) AS "latestCompletedBucket"
|
||||||
|
FROM clock
|
||||||
|
),
|
||||||
|
filtered_rows AS (
|
||||||
|
SELECT "accepted_share_10m".*, bounds."latestCompletedBucket"
|
||||||
|
FROM "accepted_share_10m", bounds
|
||||||
|
WHERE "clientId" = ANY($1::uuid[])
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
"clientId",
|
||||||
|
MAX("bucket") AS "latestShareAt",
|
||||||
|
COALESCE((SUM("shares") FILTER (WHERE "bucket" = "latestCompletedBucket") * ${HASHES_PER_DIFFICULTY}) / ${ROLLUP_BUCKET_SECONDS}, 0)::float AS "hashRateLast10Minutes"
|
||||||
|
FROM filtered_rows
|
||||||
|
GROUP BY "clientId"
|
||||||
|
`, [uniqueClientIds]);
|
||||||
|
|
||||||
|
rows.forEach(row => {
|
||||||
|
summaries.set(row.clientId, {
|
||||||
|
clientId: row.clientId,
|
||||||
|
latestShareAt: row.latestShareAt == null
|
||||||
|
? null
|
||||||
|
: new Date(row.latestShareAt).toISOString(),
|
||||||
|
hashRateLast10Minutes: this.toNumber(row.hashRateLast10Minutes),
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return summaries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getSummary(filter: AccountingFilter): Promise<ShareAccountingSummary> {
|
||||||
|
const cacheKey = this.getSummaryCacheKey(filter);
|
||||||
|
const cached = this.summaryCache.get(cacheKey);
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (cached != null && cached.expiresAt > now) {
|
||||||
|
return cached.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = this.loadCachedSummary(filter, cacheKey).catch(error => {
|
||||||
|
this.summaryCache.delete(cacheKey);
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.summaryCacheMs > 0) {
|
||||||
|
this.summaryCache.set(cacheKey, {
|
||||||
|
expiresAt: now + this.summaryCacheMs,
|
||||||
|
value,
|
||||||
|
});
|
||||||
|
this.trimSummaryCache();
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadCachedSummary(filter: AccountingFilter, cacheKey: string): Promise<ShareAccountingSummary> {
|
||||||
|
const redisCacheKey = `accounting:summary:${cacheKey}`;
|
||||||
|
const cached = await this.redisMessagingService
|
||||||
|
?.getJsonCache<ShareAccountingSummary>(redisCacheKey)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Share accounting summary cache read failed: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = await this.loadSummary(filter);
|
||||||
|
|
||||||
|
await this.redisMessagingService
|
||||||
|
?.setJsonCache(redisCacheKey, summary, this.redisSummaryCacheMs)
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Share accounting summary cache write failed: ${error.message}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadSummary(filter: AccountingFilter): Promise<ShareAccountingSummary> {
|
||||||
|
const { whereSql, params } = this.buildWhereClause(filter);
|
||||||
|
const [summary] = await this.acceptedShareRepository.query(`
|
||||||
|
WITH clock AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
time_bucket(INTERVAL '10 minutes', NOW()) AS "currentBucket"
|
||||||
|
),
|
||||||
|
latest_bucket AS MATERIALIZED (
|
||||||
|
SELECT "bucket"
|
||||||
|
FROM "accepted_share_10m", clock
|
||||||
|
WHERE "bucket" < clock."currentBucket"
|
||||||
|
ORDER BY "bucket" DESC
|
||||||
|
LIMIT 1
|
||||||
|
),
|
||||||
|
bounds AS MATERIALIZED (
|
||||||
|
SELECT
|
||||||
|
"currentBucket",
|
||||||
|
COALESCE(
|
||||||
|
(SELECT "bucket" FROM latest_bucket),
|
||||||
|
"currentBucket" - INTERVAL '10 minutes'
|
||||||
|
) AS "latestCompletedBucket"
|
||||||
|
FROM clock
|
||||||
|
),
|
||||||
|
filtered_rows AS (
|
||||||
|
SELECT "accepted_share_10m".*, bounds."currentBucket", bounds."latestCompletedBucket"
|
||||||
|
FROM "accepted_share_10m", bounds
|
||||||
|
${whereSql.length > 0
|
||||||
|
? `${whereSql} AND "accepted_share_10m"."bucket" <= bounds."latestCompletedBucket"`
|
||||||
|
: `WHERE "accepted_share_10m"."bucket" <= bounds."latestCompletedBucket"`}
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM("acceptedCount"), 0)::int AS "totalAcceptedShares",
|
||||||
|
COALESCE(SUM("shares"), 0)::float AS "totalCreditedDifficulty",
|
||||||
|
COALESCE(SUM("acceptedCount") FILTER (WHERE "bucket" = "latestCompletedBucket"), 0)::int AS "acceptedSharesLast10Minutes",
|
||||||
|
COALESCE(SUM("shares") FILTER (WHERE "bucket" = "latestCompletedBucket"), 0)::float AS "creditedDifficultyLast10Minutes",
|
||||||
|
COALESCE(SUM("acceptedCount") FILTER (WHERE "bucket" > "latestCompletedBucket" - INTERVAL '1 hour' AND "bucket" <= "latestCompletedBucket"), 0)::int AS "acceptedSharesLastHour",
|
||||||
|
COALESCE(SUM("shares") FILTER (WHERE "bucket" > "latestCompletedBucket" - INTERVAL '1 hour' AND "bucket" <= "latestCompletedBucket"), 0)::float AS "creditedDifficultyLastHour",
|
||||||
|
COALESCE(SUM("acceptedCount") FILTER (WHERE "bucket" > "latestCompletedBucket" - INTERVAL '1 day' AND "bucket" <= "latestCompletedBucket"), 0)::int AS "acceptedSharesLastDay",
|
||||||
|
COALESCE(SUM("shares") FILTER (WHERE "bucket" > "latestCompletedBucket" - INTERVAL '1 day' AND "bucket" <= "latestCompletedBucket"), 0)::float AS "creditedDifficultyLastDay",
|
||||||
|
COALESCE((SUM("shares") FILTER (WHERE "bucket" = "latestCompletedBucket") * ${HASHES_PER_DIFFICULTY}) / ${ROLLUP_BUCKET_SECONDS}, 0)::float AS "hashRateLast10Minutes",
|
||||||
|
COALESCE((SUM("shares") FILTER (WHERE "bucket" > "latestCompletedBucket" - INTERVAL '1 hour' AND "bucket" <= "latestCompletedBucket") * ${HASHES_PER_DIFFICULTY}) / 3600, 0)::float AS "hashRateLastHour",
|
||||||
|
MAX("bucket") AS "latestShareAt"
|
||||||
|
FROM filtered_rows
|
||||||
|
`, params);
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalAcceptedShares: this.toNumber(summary?.totalAcceptedShares),
|
||||||
|
totalCreditedDifficulty: this.toNumber(summary?.totalCreditedDifficulty),
|
||||||
|
acceptedSharesLast10Minutes: this.toNumber(summary?.acceptedSharesLast10Minutes),
|
||||||
|
creditedDifficultyLast10Minutes: this.toNumber(summary?.creditedDifficultyLast10Minutes),
|
||||||
|
acceptedSharesLastHour: this.toNumber(summary?.acceptedSharesLastHour),
|
||||||
|
creditedDifficultyLastHour: this.toNumber(summary?.creditedDifficultyLastHour),
|
||||||
|
acceptedSharesLastDay: this.toNumber(summary?.acceptedSharesLastDay),
|
||||||
|
creditedDifficultyLastDay: this.toNumber(summary?.creditedDifficultyLastDay),
|
||||||
|
hashRateLast10Minutes: this.toNumber(summary?.hashRateLast10Minutes),
|
||||||
|
hashRateLastHour: this.toNumber(summary?.hashRateLastHour),
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
bestSubmissionDifficultyAt: null,
|
||||||
|
workSinceLastBlock: 0,
|
||||||
|
currentRoundAcceptedShares: 0,
|
||||||
|
currentRoundNetworkDifficulty: 0,
|
||||||
|
networkDifficultyPercent: 0,
|
||||||
|
blockCandidateCount: 0,
|
||||||
|
latestShareAt: summary?.latestShareAt == null
|
||||||
|
? null
|
||||||
|
: new Date(summary.latestShareAt).toISOString(),
|
||||||
|
protocolBreakdown: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleFlush(): void {
|
||||||
|
if (this.flushTimer != null || this.activeFlush != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.flushTimer = setTimeout(() => {
|
||||||
|
this.flushTimer = null;
|
||||||
|
this.startFlush();
|
||||||
|
}, this.flushIntervalMs);
|
||||||
|
this.flushTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
private startFlush(): void {
|
||||||
|
if (this.activeFlush != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.flushTimer != null) {
|
||||||
|
clearTimeout(this.flushTimer);
|
||||||
|
this.flushTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const batch = this.pendingShares.splice(0, this.batchSize);
|
||||||
|
if (batch.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.activeFlush = this.flushBatch(batch).finally(() => {
|
||||||
|
this.activeFlush = null;
|
||||||
|
|
||||||
|
if (this.pendingShares.length >= this.batchSize) {
|
||||||
|
this.startFlush();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.pendingShares.length > 0) {
|
||||||
|
this.scheduleFlush();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async flushBatch(batch: PendingShare[]): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.acceptedShareRepository.insert(batch.map(item => item.entity));
|
||||||
|
batch.forEach(item => item.resolve(item.entity));
|
||||||
|
} catch (error) {
|
||||||
|
batch.forEach(item => item.reject(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startShareRollupTimer(): void {
|
||||||
|
if (!this.shareRollupEnabled || process.env.MASTER !== 'true') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rollupTimer = setInterval(() => {
|
||||||
|
if (this.activeRollup != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.activeRollup = this.processPendingShareRollupBatch()
|
||||||
|
.then(result => {
|
||||||
|
if (result.processed) {
|
||||||
|
console.log(`Share rollup batch ${result.batchId} finalized: indexes ${result.startShareIndex}-${result.endShareIndex}, shares ${result.acceptedShareCount}, difficulty ${result.creditedDifficulty}`);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Share rollup batch failed: ${error.message}`);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.activeRollup = null;
|
||||||
|
});
|
||||||
|
}, this.shareRollupIntervalMs);
|
||||||
|
this.rollupTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildWhereClause(filter: AccountingFilter): { whereSql: string; params: string[] } {
|
||||||
|
const where: string[] = [];
|
||||||
|
const params: string[] = [];
|
||||||
|
|
||||||
|
if (filter.address != null) {
|
||||||
|
params.push(filter.address);
|
||||||
|
where.push(`"address" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.clientName != null) {
|
||||||
|
params.push(filter.clientName);
|
||||||
|
where.push(`"clientName" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.clientId != null) {
|
||||||
|
params.push(filter.clientId);
|
||||||
|
where.push(`"clientId" = $${params.length}`);
|
||||||
|
}
|
||||||
|
if (filter.payoutMode != null) {
|
||||||
|
params.push(filter.payoutMode);
|
||||||
|
where.push(`"payoutMode" = $${params.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
whereSql: where.length > 0 ? `WHERE ${where.join(' AND ')}` : '',
|
||||||
|
params,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toNumber(value: unknown): number {
|
||||||
|
const parsed = Number(value ?? 0);
|
||||||
|
return Number.isFinite(parsed) ? parsed : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private roundPercent(value: number): number {
|
||||||
|
return Math.round(value * 1_000_000) / 1_000_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getSummaryCacheKey(filter: AccountingFilter): string {
|
||||||
|
return JSON.stringify({
|
||||||
|
address: filter.address ?? null,
|
||||||
|
clientName: filter.clientName ?? null,
|
||||||
|
clientId: filter.clientId ?? null,
|
||||||
|
payoutMode: filter.payoutMode ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private trimSummaryCache(): void {
|
||||||
|
while (this.summaryCache.size > this.summaryCacheMax) {
|
||||||
|
const firstKey = this.summaryCache.keys().next().value;
|
||||||
|
if (firstKey == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.summaryCache.delete(firstKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isInteger(value) && value > 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readNonNegativeInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isInteger(value) && value >= 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readBoolean(name: string, defaultValue: boolean): boolean {
|
||||||
|
const value = process.env[name]?.toLowerCase();
|
||||||
|
if (value == null || value.length === 0) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
return value === 'true' || value === '1' || value === 'yes';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PendingShare {
|
||||||
|
entity: AcceptedShareEntity;
|
||||||
|
resolve: (entity: AcceptedShareEntity) => void;
|
||||||
|
reject: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SummaryCacheEntry {
|
||||||
|
expiresAt: number;
|
||||||
|
value: Promise<ShareAccountingSummary>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { DataSource, EntityManager } from 'typeorm';
|
||||||
|
|
||||||
|
import { PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
type HighScorePayoutMode = PayoutMode | 'all';
|
||||||
|
|
||||||
|
interface HighScoreCandidate {
|
||||||
|
bucketDate: string;
|
||||||
|
bucket: Date;
|
||||||
|
blockHeight: string;
|
||||||
|
bestSubmissionDifficulty: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExactHighScore {
|
||||||
|
submissionDifficulty: string;
|
||||||
|
acceptedAt: Date | null;
|
||||||
|
blockHeight: string | null;
|
||||||
|
address: string | null;
|
||||||
|
clientName: string | null;
|
||||||
|
protocol: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HighScoreRecord {
|
||||||
|
scope: 'all_time' | 'daily';
|
||||||
|
payoutMode: HighScorePayoutMode;
|
||||||
|
bucketDate: string;
|
||||||
|
submissionDifficulty: string;
|
||||||
|
acceptedAt: Date | null;
|
||||||
|
bucket: Date | null;
|
||||||
|
blockHeight: string | null;
|
||||||
|
address: string | null;
|
||||||
|
clientName: string | null;
|
||||||
|
protocol: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HighScoreRefreshResult {
|
||||||
|
processed: boolean;
|
||||||
|
reason?: 'locked';
|
||||||
|
updatedRows: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_HIGH_SCORE_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
|
||||||
|
const DEFAULT_HIGH_SCORE_LOOKBACK_DAYS = 7;
|
||||||
|
const HIGH_SCORE_ADVISORY_LOCK = '1781309000';
|
||||||
|
const ALL_TIME_BUCKET_DATE = '1970-01-01';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ShareHighScoreService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private timer: NodeJS.Timeout | null = null;
|
||||||
|
private activeRefresh: Promise<HighScoreRefreshResult> | null = null;
|
||||||
|
private readonly refreshIntervalMs = this.readPositiveInt(
|
||||||
|
'SHARE_HIGH_SCORE_REFRESH_INTERVAL_MS',
|
||||||
|
DEFAULT_HIGH_SCORE_REFRESH_INTERVAL_MS,
|
||||||
|
);
|
||||||
|
private readonly lookbackDays = this.readPositiveInt(
|
||||||
|
'SHARE_HIGH_SCORE_LOOKBACK_DAYS',
|
||||||
|
DEFAULT_HIGH_SCORE_LOOKBACK_DAYS,
|
||||||
|
);
|
||||||
|
|
||||||
|
constructor(private readonly dataSource: DataSource) { }
|
||||||
|
|
||||||
|
public onModuleInit(): void {
|
||||||
|
if (process.env.MASTER !== 'true' || process.env.API_ONLY === 'true') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.timer = setInterval(() => {
|
||||||
|
if (this.activeRefresh != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.activeRefresh = this.refreshHighScores()
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Accepted share high-score refresh failed: ${error.message}`);
|
||||||
|
return { processed: false, updatedRows: 0 };
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.activeRefresh = null;
|
||||||
|
});
|
||||||
|
}, this.refreshIntervalMs);
|
||||||
|
this.timer.unref?.();
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.activeRefresh == null) {
|
||||||
|
this.activeRefresh = this.refreshHighScores()
|
||||||
|
.catch(error => {
|
||||||
|
console.error(`Accepted share high-score refresh failed: ${error.message}`);
|
||||||
|
return { processed: false, updatedRows: 0 };
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.activeRefresh = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 30_000).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async onModuleDestroy(): Promise<void> {
|
||||||
|
if (this.timer != null) {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
if (this.activeRefresh != null) {
|
||||||
|
await this.activeRefresh;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refreshHighScores(): Promise<HighScoreRefreshResult> {
|
||||||
|
return this.dataSource.transaction(async manager => {
|
||||||
|
const [lockRow] = await manager.query(`
|
||||||
|
SELECT pg_try_advisory_xact_lock($1::bigint) AS "locked"
|
||||||
|
`, [HIGH_SCORE_ADVISORY_LOCK]);
|
||||||
|
|
||||||
|
if (lockRow?.locked !== true) {
|
||||||
|
return { processed: false, reason: 'locked', updatedRows: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
let updatedRows = 0;
|
||||||
|
for (const payoutMode of ['all', 'solo', 'pplns'] as HighScorePayoutMode[]) {
|
||||||
|
updatedRows += await this.refreshForPayoutMode(manager, payoutMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { processed: true, updatedRows };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async refreshForPayoutMode(manager: EntityManager, payoutMode: HighScorePayoutMode): Promise<number> {
|
||||||
|
const candidates = await this.loadDailyCandidates(manager, payoutMode);
|
||||||
|
let updatedRows = 0;
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const exact = await this.loadExactHighScore(manager, candidate, payoutMode);
|
||||||
|
const record = this.toRecord('daily', payoutMode, candidate.bucketDate, candidate, exact);
|
||||||
|
updatedRows += await this.upsertHighScore(manager, record);
|
||||||
|
updatedRows += await this.upsertHighScore(manager, {
|
||||||
|
...record,
|
||||||
|
scope: 'all_time',
|
||||||
|
bucketDate: ALL_TIME_BUCKET_DATE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return updatedRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadDailyCandidates(manager: EntityManager, payoutMode: HighScorePayoutMode): Promise<HighScoreCandidate[]> {
|
||||||
|
const params: unknown[] = [this.lookbackDays];
|
||||||
|
const modeFilter = payoutMode === 'all'
|
||||||
|
? ''
|
||||||
|
: `AND "payoutMode" = $${params.push(payoutMode)}`;
|
||||||
|
|
||||||
|
return manager.query(`
|
||||||
|
WITH candidate_rows AS (
|
||||||
|
SELECT
|
||||||
|
date_trunc('day', "bucket")::date AS "bucketDate",
|
||||||
|
"bucket",
|
||||||
|
"blockHeight",
|
||||||
|
"bestSubmissionDifficulty"
|
||||||
|
FROM "accepted_share_block_10m"
|
||||||
|
WHERE "bucket" >= NOW() - ($1::int * INTERVAL '1 day')
|
||||||
|
AND "bestSubmissionDifficulty" IS NOT NULL
|
||||||
|
AND "bestSubmissionDifficulty" > 0
|
||||||
|
${modeFilter}
|
||||||
|
)
|
||||||
|
SELECT DISTINCT ON ("bucketDate")
|
||||||
|
"bucketDate"::text AS "bucketDate",
|
||||||
|
"bucket",
|
||||||
|
"blockHeight"::text AS "blockHeight",
|
||||||
|
"bestSubmissionDifficulty"::text AS "bestSubmissionDifficulty"
|
||||||
|
FROM candidate_rows
|
||||||
|
ORDER BY "bucketDate", "bestSubmissionDifficulty" DESC, "bucket" DESC
|
||||||
|
`, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadExactHighScore(
|
||||||
|
manager: EntityManager,
|
||||||
|
candidate: HighScoreCandidate,
|
||||||
|
payoutMode: HighScorePayoutMode,
|
||||||
|
): Promise<ExactHighScore | null> {
|
||||||
|
const params: unknown[] = [candidate.bucket, candidate.blockHeight];
|
||||||
|
const modeFilter = payoutMode === 'all'
|
||||||
|
? ''
|
||||||
|
: `AND "payoutMode" = $${params.push(payoutMode)}`;
|
||||||
|
const rows = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
"submissionDifficulty"::text AS "submissionDifficulty",
|
||||||
|
"acceptedAt",
|
||||||
|
"blockHeight"::text AS "blockHeight",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"protocol"
|
||||||
|
FROM "accepted_share_entity"
|
||||||
|
WHERE "acceptedAt" >= $1::timestamptz
|
||||||
|
AND "acceptedAt" < $1::timestamptz + INTERVAL '10 minutes'
|
||||||
|
AND "blockHeight" = $2::bigint
|
||||||
|
${modeFilter}
|
||||||
|
ORDER BY "submissionDifficulty" DESC, "acceptedAt" DESC
|
||||||
|
LIMIT 1
|
||||||
|
`, params);
|
||||||
|
|
||||||
|
return rows[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toRecord(
|
||||||
|
scope: HighScoreRecord['scope'],
|
||||||
|
payoutMode: HighScorePayoutMode,
|
||||||
|
bucketDate: string,
|
||||||
|
candidate: HighScoreCandidate,
|
||||||
|
exact: ExactHighScore | null,
|
||||||
|
): HighScoreRecord {
|
||||||
|
return {
|
||||||
|
scope,
|
||||||
|
payoutMode,
|
||||||
|
bucketDate,
|
||||||
|
submissionDifficulty: exact?.submissionDifficulty ?? candidate.bestSubmissionDifficulty,
|
||||||
|
acceptedAt: exact?.acceptedAt ?? candidate.bucket,
|
||||||
|
bucket: candidate.bucket,
|
||||||
|
blockHeight: exact?.blockHeight ?? candidate.blockHeight,
|
||||||
|
address: exact?.address ?? null,
|
||||||
|
clientName: exact?.clientName ?? null,
|
||||||
|
protocol: exact?.protocol ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async upsertHighScore(manager: EntityManager, record: HighScoreRecord): Promise<number> {
|
||||||
|
const rows = await manager.query(`
|
||||||
|
INSERT INTO "accepted_share_high_score" (
|
||||||
|
"scope",
|
||||||
|
"payoutMode",
|
||||||
|
"bucketDate",
|
||||||
|
"submissionDifficulty",
|
||||||
|
"acceptedAt",
|
||||||
|
"bucket",
|
||||||
|
"blockHeight",
|
||||||
|
"address",
|
||||||
|
"clientName",
|
||||||
|
"protocol"
|
||||||
|
) VALUES (
|
||||||
|
$1,
|
||||||
|
$2,
|
||||||
|
$3::date,
|
||||||
|
$4::numeric,
|
||||||
|
$5::timestamptz,
|
||||||
|
$6::timestamptz,
|
||||||
|
$7::bigint,
|
||||||
|
$8,
|
||||||
|
$9,
|
||||||
|
$10
|
||||||
|
)
|
||||||
|
ON CONFLICT ("scope", "payoutMode", "bucketDate")
|
||||||
|
DO UPDATE SET
|
||||||
|
"submissionDifficulty" = EXCLUDED."submissionDifficulty",
|
||||||
|
"acceptedAt" = EXCLUDED."acceptedAt",
|
||||||
|
"bucket" = EXCLUDED."bucket",
|
||||||
|
"blockHeight" = EXCLUDED."blockHeight",
|
||||||
|
"address" = EXCLUDED."address",
|
||||||
|
"clientName" = EXCLUDED."clientName",
|
||||||
|
"protocol" = EXCLUDED."protocol",
|
||||||
|
"updatedAt" = NOW()
|
||||||
|
WHERE EXCLUDED."submissionDifficulty" > "accepted_share_high_score"."submissionDifficulty"
|
||||||
|
OR (
|
||||||
|
EXCLUDED."submissionDifficulty" = "accepted_share_high_score"."submissionDifficulty"
|
||||||
|
AND EXCLUDED."acceptedAt" > COALESCE("accepted_share_high_score"."acceptedAt", '-infinity'::timestamptz)
|
||||||
|
)
|
||||||
|
RETURNING 1
|
||||||
|
`, [
|
||||||
|
record.scope,
|
||||||
|
record.payoutMode,
|
||||||
|
record.bucketDate,
|
||||||
|
record.submissionDifficulty,
|
||||||
|
record.acceptedAt,
|
||||||
|
record.bucket,
|
||||||
|
record.blockHeight,
|
||||||
|
record.address,
|
||||||
|
record.clientName,
|
||||||
|
record.protocol,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return rows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
return Number.isInteger(value) && value > 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
import { Column, Entity, Index } from 'typeorm';
|
||||||
|
|
||||||
|
import { PrimaryGeneratedBigIntColumn } from '../utils/PrimaryGeneratedBigIntColumn';
|
||||||
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
import { TrackedEntity } from '../utils/TrackedEntity.entity';
|
||||||
|
|
||||||
@Entity()
|
@Entity()
|
||||||
export class TelegramSubscriptionsEntity extends TrackedEntity {
|
export class TelegramSubscriptionsEntity extends TrackedEntity {
|
||||||
|
|
||||||
@PrimaryGeneratedColumn()
|
@PrimaryGeneratedBigIntColumn()
|
||||||
id: number;
|
id: number;
|
||||||
|
|
||||||
@Index()
|
@Index()
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
export const PrimaryGeneratedBigIntColumn = () => PrimaryGeneratedColumn({
|
||||||
|
type: process.env.NODE_ENV === 'test' ? 'integer' : 'bigint'
|
||||||
|
});
|
||||||
@@ -1,14 +1,12 @@
|
|||||||
import { CreateDateColumn, DeleteDateColumn, UpdateDateColumn } from 'typeorm';
|
import { CreateDateColumn, DeleteDateColumn, UpdateDateColumn } from 'typeorm';
|
||||||
|
|
||||||
import { DateTimeTransformer } from './DateTimeTransformer';
|
|
||||||
|
|
||||||
export abstract class TrackedEntity {
|
export abstract class TrackedEntity {
|
||||||
@DeleteDateColumn({ nullable: true, type: 'datetime', transformer: new DateTimeTransformer() })
|
@DeleteDateColumn({ nullable: true })
|
||||||
public deletedAt?: Date;
|
public deletedAt?: Date;
|
||||||
|
|
||||||
@CreateDateColumn({ type: 'datetime', transformer: new DateTimeTransformer() })
|
@CreateDateColumn()
|
||||||
public createdAt?: Date
|
public createdAt?: Date
|
||||||
|
|
||||||
@UpdateDateColumn({ type: 'datetime', transformer: new DateTimeTransformer() })
|
@UpdateDateColumn()
|
||||||
public updatedAt?: Date
|
public updatedAt?: Date
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { AppController } from './app.controller';
|
||||||
|
|
||||||
|
describe('AppController', () => {
|
||||||
|
const createController = (overrides: {
|
||||||
|
cacheManager?: any;
|
||||||
|
blocksService?: any;
|
||||||
|
addressSettingsService?: any;
|
||||||
|
userAgentReportService?: any;
|
||||||
|
stratumV2Service?: any;
|
||||||
|
redisMessagingService?: any;
|
||||||
|
} = {}) => {
|
||||||
|
return new AppController(
|
||||||
|
overrides.cacheManager ?? {
|
||||||
|
get: jest.fn().mockResolvedValue(null),
|
||||||
|
set: jest.fn().mockResolvedValue(undefined),
|
||||||
|
},
|
||||||
|
{} as any,
|
||||||
|
{} as any,
|
||||||
|
overrides.blocksService ?? {
|
||||||
|
getFoundBlocks: jest.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
|
{} as any,
|
||||||
|
overrides.addressSettingsService ?? {
|
||||||
|
getHighScores: jest.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
|
overrides.userAgentReportService ?? {
|
||||||
|
getReport: jest.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
|
overrides.stratumV2Service ?? {
|
||||||
|
getPoolAuthorityPublicKey: jest.fn().mockResolvedValue({
|
||||||
|
publicKey: '',
|
||||||
|
configured: false,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{} as any,
|
||||||
|
overrides.redisMessagingService ?? {
|
||||||
|
getJsonCache: jest.fn().mockResolvedValue(null),
|
||||||
|
setJsonCache: jest.fn().mockResolvedValue(undefined),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('refreshes found blocks even when site info is served from cache', async () => {
|
||||||
|
const cachedInfo = {
|
||||||
|
blockData: [{ height: 1 }],
|
||||||
|
userAgents: [],
|
||||||
|
highScores: [],
|
||||||
|
sv2: {
|
||||||
|
poolAuthorityPublicKey: '',
|
||||||
|
authorityKeyConfigured: false,
|
||||||
|
},
|
||||||
|
uptime: new Date('2026-01-01T00:00:00.000Z'),
|
||||||
|
};
|
||||||
|
const freshBlocks = [{ height: 2 }];
|
||||||
|
const cacheManager = {
|
||||||
|
get: jest.fn().mockResolvedValue(cachedInfo),
|
||||||
|
set: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const blocksService = {
|
||||||
|
getFoundBlocks: jest.fn().mockResolvedValue(freshBlocks),
|
||||||
|
};
|
||||||
|
const controller = createController({
|
||||||
|
cacheManager,
|
||||||
|
blocksService,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.info()).resolves.toEqual({
|
||||||
|
...cachedInfo,
|
||||||
|
blockData: freshBlocks,
|
||||||
|
});
|
||||||
|
expect(blocksService.getFoundBlocks).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps small user-agent reports expanded so local protocol workers are visible', async () => {
|
||||||
|
const controller = createController({
|
||||||
|
userAgentReportService: {
|
||||||
|
getReport: jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
userAgent: 'unknown/sv2',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 100,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
userAgent: 'v0.4.1-beta/datum',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 0,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.info()).resolves.toMatchObject({
|
||||||
|
userAgents: [
|
||||||
|
{
|
||||||
|
userAgent: 'unknown/sv2',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 100,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
userAgent: 'v0.4.1-beta/datum',
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: 0,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('groups small user-agent rows only when the report is large', () => {
|
||||||
|
const controller = createController() as any;
|
||||||
|
const report = Array.from({ length: 21 }, (_, index) => ({
|
||||||
|
userAgent: `small-${index}`,
|
||||||
|
count: '1',
|
||||||
|
bestDifficulty: index,
|
||||||
|
totalHashRate: '0',
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(controller.groupSmallUserAgents(report)).toEqual([
|
||||||
|
{
|
||||||
|
userAgent: 'Other',
|
||||||
|
count: '21',
|
||||||
|
bestDifficulty: 20,
|
||||||
|
totalHashRate: '0',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+251
-30
@@ -1,69 +1,197 @@
|
|||||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||||
import { Controller, Get, Inject } from '@nestjs/common';
|
import { Controller, Get, Inject, Query } from '@nestjs/common';
|
||||||
import { Cache } from 'cache-manager';
|
import { Cache } from 'cache-manager';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
|
import { UserAgentReportService } from './ORM/_views/user-agent-report/user-agent-report.service';
|
||||||
|
import { AddressSettingsService } from './ORM/address-settings/address-settings.service';
|
||||||
import { BlocksService } from './ORM/blocks/blocks.service';
|
import { BlocksService } from './ORM/blocks/blocks.service';
|
||||||
import { ClientStatisticsService } from './ORM/client-statistics/client-statistics.service';
|
import { ClientStatisticsService } from './ORM/client-statistics/client-statistics.service';
|
||||||
import { ClientService } from './ORM/client/client.service';
|
import { ClientService } from './ORM/client/client.service';
|
||||||
import { BitcoinRpcService } from './services/bitcoin-rpc.service';
|
import { BitcoinRpcService } from './services/bitcoin-rpc.service';
|
||||||
|
import { UserAgentReportView } from './ORM/_views/user-agent-report/user-agent-report.view';
|
||||||
|
import { StratumV2Service } from './services/stratum-v2.service';
|
||||||
|
import { ShareAccountingService } from './ORM/share-accounting/share-accounting.service';
|
||||||
|
import { RedisMessagingService } from './services/redis-messaging.service';
|
||||||
|
import { normalizePayoutMode } from './types/payout-mode';
|
||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class AppController {
|
export class AppController {
|
||||||
|
|
||||||
private uptime = new Date();
|
private uptime = new Date();
|
||||||
|
private siteInfoRefreshPromise: Promise<SiteInfoResponse> | null = null;
|
||||||
|
private readonly userAgentOtherGroupThreshold = 20;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
||||||
private readonly clientService: ClientService,
|
private readonly clientService: ClientService,
|
||||||
private readonly clientStatisticsService: ClientStatisticsService,
|
private readonly clientStatisticsService: ClientStatisticsService,
|
||||||
private readonly blocksService: BlocksService,
|
private readonly blocksService: BlocksService,
|
||||||
private readonly bitcoinRpcService: BitcoinRpcService
|
private readonly bitcoinRpcService: BitcoinRpcService,
|
||||||
|
private readonly addressSettingsService: AddressSettingsService,
|
||||||
|
private readonly userAgentReportService: UserAgentReportService,
|
||||||
|
private readonly stratumV2Service: StratumV2Service,
|
||||||
|
private readonly shareAccountingService: ShareAccountingService,
|
||||||
|
private readonly redisMessagingService: RedisMessagingService
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
@Get('info')
|
@Get('info')
|
||||||
public async info() {
|
public async info() {
|
||||||
|
|
||||||
|
|
||||||
const CACHE_KEY = 'SITE_INFO';
|
const CACHE_KEY = 'SITE_INFO';
|
||||||
const cachedResult = await this.cacheManager.get(CACHE_KEY);
|
const STALE_CACHE_KEY = 'SITE_INFO_STALE';
|
||||||
|
const cachedResult = await this.getCached<SiteInfoResponse>(CACHE_KEY, 5 * 60 * 1000);
|
||||||
|
|
||||||
|
if (cachedResult != null) {
|
||||||
|
return await this.withFreshFoundBlocks(cachedResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
const staleResult = await this.getCached<SiteInfoResponse>(STALE_CACHE_KEY, 60 * 60 * 1000);
|
||||||
|
if (staleResult != null) {
|
||||||
|
void this.refreshSiteInfo(staleResult);
|
||||||
|
return await this.withFreshFoundBlocks(staleResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.refreshSiteInfo(null);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private async refreshSiteInfo(staleInfo: SiteInfoResponse | null): Promise<SiteInfoResponse> {
|
||||||
|
if (this.siteInfoRefreshPromise != null) {
|
||||||
|
return this.siteInfoRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.siteInfoRefreshPromise = this.loadSiteInfo(staleInfo)
|
||||||
|
.finally(() => {
|
||||||
|
this.siteInfoRefreshPromise = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.siteInfoRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadSiteInfo(staleInfo: SiteInfoResponse | null): Promise<SiteInfoResponse> {
|
||||||
|
const CACHE_KEY = 'SITE_INFO';
|
||||||
|
const STALE_CACHE_KEY = 'SITE_INFO_STALE';
|
||||||
|
const withInfoTimeout = async <T>(label: string, promise: Promise<T>, fallback: T): Promise<T> => {
|
||||||
|
return await this.withTimeout(label, promise, fallback);
|
||||||
|
};
|
||||||
|
|
||||||
|
const [blockData, highScores, poolAuthority, userAgentReport] = await Promise.all([
|
||||||
|
withInfoTimeout('found blocks', this.blocksService.getFoundBlocks(), staleInfo?.blockData ?? []),
|
||||||
|
withInfoTimeout('high scores', this.addressSettingsService.getHighScores(), staleInfo?.highScores ?? []),
|
||||||
|
withInfoTimeout('SV2 authority', this.stratumV2Service.getPoolAuthorityPublicKey(), {
|
||||||
|
publicKey: staleInfo?.sv2?.poolAuthorityPublicKey ?? '',
|
||||||
|
configured: staleInfo?.sv2?.authorityKeyConfigured ?? false
|
||||||
|
}),
|
||||||
|
withInfoTimeout<UserAgentReportView[]>('user agent report', this.userAgentReportService.getReport(), staleInfo?.userAgents ?? []),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const userAgents = this.groupSmallUserAgents(userAgentReport);
|
||||||
|
|
||||||
|
const data: SiteInfoResponse = {
|
||||||
|
blockData,
|
||||||
|
userAgents,
|
||||||
|
highScores,
|
||||||
|
sv2: {
|
||||||
|
poolAuthorityPublicKey: poolAuthority.publicKey,
|
||||||
|
authorityKeyConfigured: poolAuthority.configured
|
||||||
|
},
|
||||||
|
uptime: this.uptime
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cache a complete response even when one slow component falls back to stale data.
|
||||||
|
// A short retry loop here causes repeated DB work because timed-out TypeORM queries are not cancelled.
|
||||||
|
await this.setCached(CACHE_KEY, data, 5 * 60 * 1000);
|
||||||
|
await this.setCached(STALE_CACHE_KEY, data, 60 * 60 * 1000);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private groupSmallUserAgents(userAgentReport: UserAgentReportView[]): UserAgentReportView[] {
|
||||||
|
if (userAgentReport.length <= this.userAgentOtherGroupThreshold) {
|
||||||
|
return userAgentReport;
|
||||||
|
}
|
||||||
|
|
||||||
|
const other: {
|
||||||
|
count: number,
|
||||||
|
bestDifficulty: number,
|
||||||
|
totalHashRate: number;
|
||||||
|
} = {
|
||||||
|
count: 0,
|
||||||
|
bestDifficulty: 0,
|
||||||
|
totalHashRate: 0
|
||||||
|
};
|
||||||
|
const userAgents: UserAgentReportView[] = userAgentReport.reduce((pre, cur) => {
|
||||||
|
// If less than 10Th/s and less than 100 devices, add to 'other'
|
||||||
|
if (parseInt(cur.totalHashRate) < 10000000000000 && parseInt(cur.count) < 200) {
|
||||||
|
other.totalHashRate += parseFloat(cur.totalHashRate);
|
||||||
|
other.count += parseInt(cur.count);
|
||||||
|
if (other.bestDifficulty < cur.bestDifficulty) {
|
||||||
|
other.bestDifficulty = cur.bestDifficulty;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pre.push(cur);
|
||||||
|
}
|
||||||
|
return pre;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (other.count > 0) {
|
||||||
|
userAgents.push({ userAgent: 'Other', count: other.count.toString(), bestDifficulty: other.bestDifficulty, totalHashRate: other.totalHashRate.toString() })
|
||||||
|
}
|
||||||
|
|
||||||
|
return userAgents;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async withFreshFoundBlocks(info: SiteInfoResponse): Promise<SiteInfoResponse> {
|
||||||
|
const blockData = await this.withTimeout(
|
||||||
|
'found blocks cache refresh',
|
||||||
|
this.blocksService.getFoundBlocks(),
|
||||||
|
info.blockData,
|
||||||
|
() => undefined,
|
||||||
|
500
|
||||||
|
);
|
||||||
|
|
||||||
|
if (blockData === info.blockData) {
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...info,
|
||||||
|
blockData
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('info/accounting')
|
||||||
|
public async infoAccounting(@Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = normalizePayoutMode(payoutMode ?? 'pplns');
|
||||||
|
const CACHE_KEY = `SITE_ACCOUNTING:${mode}`;
|
||||||
|
const cachedResult = await this.getCached(CACHE_KEY, 15 * 1000);
|
||||||
|
|
||||||
if (cachedResult != null) {
|
if (cachedResult != null) {
|
||||||
return cachedResult;
|
return cachedResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const data = await this.shareAccountingService.getPoolSummary(mode);
|
||||||
|
|
||||||
const blockData = await this.blocksService.getFoundBlocks();
|
//15 sec
|
||||||
const userAgents = await this.clientService.getUserAgents();
|
await this.setCached(CACHE_KEY, data, 15 * 1000);
|
||||||
|
|
||||||
const data = {
|
|
||||||
blockData,
|
|
||||||
userAgents,
|
|
||||||
uptime: this.uptime
|
|
||||||
};
|
|
||||||
|
|
||||||
//1 min
|
|
||||||
await this.cacheManager.set(CACHE_KEY, data, 1 * 60 * 1000);
|
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('pool')
|
@Get('pool')
|
||||||
public async pool() {
|
public async pool() {
|
||||||
|
|
||||||
const CACHE_KEY = 'POOL_INFO';
|
const CACHE_KEY = 'POOL_INFO';
|
||||||
const cachedResult = await this.cacheManager.get(CACHE_KEY);
|
const cachedResult = await this.getCached(CACHE_KEY, 15 * 1000);
|
||||||
|
|
||||||
if (cachedResult != null) {
|
if (cachedResult != null) {
|
||||||
return cachedResult;
|
return cachedResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const userAgents = await this.userAgentReportService.getReport();
|
||||||
|
|
||||||
const userAgents = await this.clientService.getUserAgents();
|
|
||||||
const totalHashRate = userAgents.reduce((acc, userAgent) => acc + parseFloat(userAgent.totalHashRate), 0);
|
const totalHashRate = userAgents.reduce((acc, userAgent) => acc + parseFloat(userAgent.totalHashRate), 0);
|
||||||
const totalMiners = userAgents.reduce((acc, userAgent) => acc + parseInt(userAgent.count), 0);
|
const totalMiners = userAgents.reduce((acc, userAgent) => acc + parseFloat(userAgent.count), 0);
|
||||||
const blockHeight = (await firstValueFrom(this.bitcoinRpcService.newBlock$)).blocks;
|
const blockHeight = this.bitcoinRpcService.miningInfo.blocks;
|
||||||
const blocksFound = await this.blocksService.getFoundBlocks();
|
const blocksFound = await this.blocksService.getFoundBlocks();
|
||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
@@ -74,24 +202,21 @@ export class AppController {
|
|||||||
fee: 0
|
fee: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
//5 min
|
// Keep online miner counts responsive after reconnect cleanup.
|
||||||
await this.cacheManager.set(CACHE_KEY, data, 5 * 60 * 1000);
|
await this.setCached(CACHE_KEY, data, 15 * 1000);
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('network')
|
@Get('network')
|
||||||
public async network() {
|
public async network() {
|
||||||
const miningInfo = await firstValueFrom(this.bitcoinRpcService.newBlock$);
|
return this.bitcoinRpcService.miningInfo ?? {};
|
||||||
return miningInfo;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('info/chart')
|
@Get('info/chart')
|
||||||
public async infoChart() {
|
public async infoChart() {
|
||||||
|
|
||||||
|
|
||||||
const CACHE_KEY = 'SITE_HASHRATE_GRAPH';
|
const CACHE_KEY = 'SITE_HASHRATE_GRAPH';
|
||||||
const cachedResult = await this.cacheManager.get(CACHE_KEY);
|
const cachedResult = await this.getCached(CACHE_KEY, 10 * 60 * 1000);
|
||||||
|
|
||||||
if (cachedResult != null) {
|
if (cachedResult != null) {
|
||||||
return cachedResult;
|
return cachedResult;
|
||||||
@@ -100,11 +225,107 @@ export class AppController {
|
|||||||
const chartData = await this.clientStatisticsService.getChartDataForSite();
|
const chartData = await this.clientStatisticsService.getChartDataForSite();
|
||||||
|
|
||||||
//10 min
|
//10 min
|
||||||
await this.cacheManager.set(CACHE_KEY, chartData, 10 * 60 * 1000);
|
await this.setCached(CACHE_KEY, chartData, 10 * 60 * 1000);
|
||||||
|
|
||||||
return chartData;
|
return chartData;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('info/chart/payout-modes')
|
||||||
|
public async infoChartByPayoutMode(@Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = payoutMode == null || payoutMode === 'all'
|
||||||
|
? undefined
|
||||||
|
: normalizePayoutMode(payoutMode);
|
||||||
|
const CACHE_KEY = `SITE_HASHRATE_GRAPH_BY_PAYOUT_MODE:${mode ?? 'all'}`;
|
||||||
|
const cachedResult = await this.getCached(CACHE_KEY, 10 * 60 * 1000);
|
||||||
|
|
||||||
|
if (cachedResult != null) {
|
||||||
|
return cachedResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chartData = await this.clientStatisticsService.getChartDataForSiteByPayoutMode(mode);
|
||||||
|
|
||||||
|
await this.setCached(CACHE_KEY, chartData, 10 * 60 * 1000);
|
||||||
|
|
||||||
|
return chartData;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getCached<T>(key: string, localTtlMs: number): Promise<T | null> {
|
||||||
|
const local = await this.cacheManager.get<T>(key);
|
||||||
|
if (local != null) {
|
||||||
|
return local;
|
||||||
|
}
|
||||||
|
|
||||||
|
const shared = await this.withSecondaryCacheTimeout(
|
||||||
|
this.redisMessagingService.getJsonCache<T>(`api:${key}`).catch(error => {
|
||||||
|
console.error(`Shared API cache read failed for ${key}: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
}),
|
||||||
|
100
|
||||||
|
);
|
||||||
|
if (shared != null) {
|
||||||
|
await this.cacheManager.set(key, shared, localTtlMs);
|
||||||
|
return shared;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async setCached(key: string, value: unknown, ttlMs: number): Promise<void> {
|
||||||
|
await this.cacheManager.set(key, value, ttlMs);
|
||||||
|
void this.redisMessagingService.setJsonCache(`api:${key}`, value, ttlMs).catch(error => {
|
||||||
|
console.error(`Shared API cache write failed for ${key}: ${error.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async withTimeout<T>(
|
||||||
|
label: string,
|
||||||
|
promise: Promise<T>,
|
||||||
|
fallback: T,
|
||||||
|
onTimeout: () => void = () => undefined,
|
||||||
|
timeoutMs = 1500
|
||||||
|
): Promise<T> {
|
||||||
|
let timeout: NodeJS.Timeout;
|
||||||
|
const timeoutPromise = new Promise<T>(resolve => {
|
||||||
|
timeout = setTimeout(() => {
|
||||||
|
onTimeout();
|
||||||
|
console.error(`/api/info ${label} timed out after ${timeoutMs}ms`);
|
||||||
|
resolve(fallback);
|
||||||
|
}, timeoutMs);
|
||||||
|
timeout.unref?.();
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await Promise.race([promise, timeoutPromise]);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async withSecondaryCacheTimeout<T>(promise: Promise<T | null>, timeoutMs: number): Promise<T | null> {
|
||||||
|
let timeout: NodeJS.Timeout;
|
||||||
|
const timeoutPromise = new Promise<null>(resolve => {
|
||||||
|
timeout = setTimeout(() => resolve(null), timeoutMs);
|
||||||
|
timeout.unref?.();
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await Promise.race([promise, timeoutPromise]);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SiteInfoResponse {
|
||||||
|
blockData: unknown[];
|
||||||
|
userAgents: UserAgentReportView[];
|
||||||
|
highScores: unknown[];
|
||||||
|
sv2: {
|
||||||
|
poolAuthorityPublicKey: string;
|
||||||
|
authorityKeyConfigured: boolean;
|
||||||
|
};
|
||||||
|
uptime: Date;
|
||||||
}
|
}
|
||||||
|
|||||||
+40
-13
@@ -1,7 +1,7 @@
|
|||||||
import { HttpModule } from '@nestjs/axios';
|
import { HttpModule } from '@nestjs/axios';
|
||||||
import { CacheModule } from '@nestjs/cache-manager';
|
import { CacheModule } from '@nestjs/cache-manager';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { ScheduleModule } from '@nestjs/schedule';
|
import { ScheduleModule } from '@nestjs/schedule';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
|
||||||
@@ -9,22 +9,33 @@ import { AppController } from './app.controller';
|
|||||||
import { AddressController } from './controllers/address/address.controller';
|
import { AddressController } from './controllers/address/address.controller';
|
||||||
import { ClientController } from './controllers/client/client.controller';
|
import { ClientController } from './controllers/client/client.controller';
|
||||||
import { BitcoinAddressValidator } from './models/validators/bitcoin-address.validator';
|
import { BitcoinAddressValidator } from './models/validators/bitcoin-address.validator';
|
||||||
|
import { UserAgentReportModule } from './ORM/_views/user-agent-report/user-agent-report.module';
|
||||||
import { AddressSettingsModule } from './ORM/address-settings/address-settings.module';
|
import { AddressSettingsModule } from './ORM/address-settings/address-settings.module';
|
||||||
import { BlocksModule } from './ORM/blocks/blocks.module';
|
import { BlocksModule } from './ORM/blocks/blocks.module';
|
||||||
import { ClientStatisticsModule } from './ORM/client-statistics/client-statistics.module';
|
import { ClientStatisticsModule } from './ORM/client-statistics/client-statistics.module';
|
||||||
import { ClientModule } from './ORM/client/client.module';
|
import { ClientModule } from './ORM/client/client.module';
|
||||||
|
import { PayoutSnapshotModule } from './ORM/payout-snapshot/payout-snapshot.module';
|
||||||
import { RpcBlocksModule } from './ORM/rpc-block/rpc-block.module';
|
import { RpcBlocksModule } from './ORM/rpc-block/rpc-block.module';
|
||||||
|
import { ShareAccountingModule } from './ORM/share-accounting/share-accounting.module';
|
||||||
import { TelegramSubscriptionsModule } from './ORM/telegram-subscriptions/telegram-subscriptions.module';
|
import { TelegramSubscriptionsModule } from './ORM/telegram-subscriptions/telegram-subscriptions.module';
|
||||||
|
import { createDatabaseOptions } from './database.config';
|
||||||
import { AppService } from './services/app.service';
|
import { AppService } from './services/app.service';
|
||||||
import { BitcoinRpcService } from './services/bitcoin-rpc.service';
|
import { BitcoinRpcService } from './services/bitcoin-rpc.service';
|
||||||
import { BraiinsService } from './services/braiins.service';
|
import { BraiinsService } from './services/braiins.service';
|
||||||
import { BTCPayService } from './services/btc-pay.service';
|
import { BTCPayService } from './services/btc-pay.service';
|
||||||
import { DiscordService } from './services/discord.service';
|
import { DiscordService } from './services/discord.service';
|
||||||
|
import { CustomWorkService } from './services/custom-work.service';
|
||||||
|
import { DatumService } from './services/datum.service';
|
||||||
import { NotificationService } from './services/notification.service';
|
import { NotificationService } from './services/notification.service';
|
||||||
import { ProxyService } from './services/proxy.service';
|
import { RedisMessagingModule } from './services/redis-messaging.module';
|
||||||
import { StratumV1JobsService } from './services/stratum-v1-jobs.service';
|
import { StratumV1JobsService } from './services/stratum-v1-jobs.service';
|
||||||
import { StratumV1Service } from './services/stratum-v1.service';
|
import { StratumV1Service } from './services/stratum-v1.service';
|
||||||
|
import { Sv2JobDeclarationRegistryService } from './services/sv2-job-declaration-registry.service';
|
||||||
|
import { Sv2JobDeclarationService } from './services/sv2-job-declaration.service';
|
||||||
|
import { Sv2TemplateDistributionService } from './services/sv2-template-distribution.service';
|
||||||
|
import { StratumV2Service } from './services/stratum-v2.service';
|
||||||
import { TelegramService } from './services/telegram.service';
|
import { TelegramService } from './services/telegram.service';
|
||||||
|
import { TemplateProviderService } from './services/template-provider.service';
|
||||||
|
|
||||||
|
|
||||||
const ORMModules = [
|
const ORMModules = [
|
||||||
@@ -33,25 +44,35 @@ const ORMModules = [
|
|||||||
AddressSettingsModule,
|
AddressSettingsModule,
|
||||||
TelegramSubscriptionsModule,
|
TelegramSubscriptionsModule,
|
||||||
BlocksModule,
|
BlocksModule,
|
||||||
RpcBlocksModule
|
RpcBlocksModule,
|
||||||
|
UserAgentReportModule,
|
||||||
|
ShareAccountingModule,
|
||||||
|
PayoutSnapshotModule
|
||||||
]
|
]
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
TypeOrmModule.forRoot({
|
TypeOrmModule.forRootAsync({
|
||||||
type: 'sqlite',
|
useFactory: (configService: ConfigService) => {
|
||||||
database: './DB/public-pool.sqlite',
|
return createDatabaseOptions({
|
||||||
synchronize: true,
|
...process.env,
|
||||||
autoLoadEntities: true,
|
DB_HOST: configService.get('DB_HOST'),
|
||||||
logging: false,
|
DB_PORT: configService.get('DB_PORT'),
|
||||||
enableWAL: true,
|
DB_USERNAME: configService.get('DB_USERNAME'),
|
||||||
busyTimeout: 30 * 1000,
|
DB_PASSWORD: configService.get('DB_PASSWORD'),
|
||||||
|
DB_DATABASE: configService.get('DB_DATABASE'),
|
||||||
|
DB_LOGGING: configService.get('DB_LOGGING'),
|
||||||
|
DB_POOL_SIZE: configService.get('DB_POOL_SIZE'),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService]
|
||||||
}),
|
}),
|
||||||
CacheModule.register(),
|
CacheModule.register(),
|
||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
HttpModule,
|
HttpModule,
|
||||||
|
RedisMessagingModule,
|
||||||
...ORMModules
|
...ORMModules
|
||||||
],
|
],
|
||||||
controllers: [
|
controllers: [
|
||||||
@@ -68,7 +89,13 @@ const ORMModules = [
|
|||||||
NotificationService,
|
NotificationService,
|
||||||
BitcoinAddressValidator,
|
BitcoinAddressValidator,
|
||||||
StratumV1JobsService,
|
StratumV1JobsService,
|
||||||
ProxyService,
|
StratumV2Service,
|
||||||
|
TemplateProviderService,
|
||||||
|
Sv2JobDeclarationRegistryService,
|
||||||
|
Sv2JobDeclarationService,
|
||||||
|
Sv2TemplateDistributionService,
|
||||||
|
CustomWorkService,
|
||||||
|
DatumService,
|
||||||
BTCPayService,
|
BTCPayService,
|
||||||
BraiinsService
|
BraiinsService
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { Controller, Patch } from '@nestjs/common';
|
import { Controller, Patch } from '@nestjs/common';
|
||||||
import * as bitcoinMessage from 'bitcoinjs-message';
|
|
||||||
|
|
||||||
|
|
||||||
@Controller('address')
|
@Controller('address')
|
||||||
@@ -7,16 +6,6 @@ export class AddressController {
|
|||||||
|
|
||||||
@Patch('settings')
|
@Patch('settings')
|
||||||
async settings() {
|
async settings() {
|
||||||
|
return;
|
||||||
const publicKey = '...'; // Public key corresponding to the private key used for signing
|
|
||||||
const message = '...'; // The message that was signed
|
|
||||||
const signature = '...'; // The signature of the message
|
|
||||||
|
|
||||||
const isValid: boolean = bitcoinMessage.verify(message, publicKey, signature);
|
|
||||||
if (isValid) {
|
|
||||||
console.log('Signature is valid!');
|
|
||||||
} else {
|
|
||||||
console.log('Signature is not valid!');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,256 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
|
|
||||||
import { AddressSettingsModule } from '../../ORM/address-settings/address-settings.module';
|
import { AddressSettingsService } from '../../ORM/address-settings/address-settings.service';
|
||||||
import { ClientStatisticsModule } from '../../ORM/client-statistics/client-statistics.module';
|
import { ClientStatisticsService } from '../../ORM/client-statistics/client-statistics.service';
|
||||||
import { ClientModule } from '../../ORM/client/client.module';
|
import { ClientService } from '../../ORM/client/client.service';
|
||||||
|
import { PayoutSnapshotService } from '../../ORM/payout-snapshot/payout-snapshot.service';
|
||||||
|
import { ShareAccountingService } from '../../ORM/share-accounting/share-accounting.service';
|
||||||
import { ClientController } from './client.controller';
|
import { ClientController } from './client.controller';
|
||||||
|
|
||||||
describe('ClientController', () => {
|
describe('ClientController', () => {
|
||||||
let controller: ClientController;
|
let controller: ClientController;
|
||||||
|
let clientService: { getByAddress: jest.Mock; getBySessionId: jest.Mock };
|
||||||
|
let addressSettingsService: { getSettings: jest.Mock };
|
||||||
|
let shareAccountingService: {
|
||||||
|
getAddressSummary: jest.Mock;
|
||||||
|
getWorkerGroupSummary: jest.Mock;
|
||||||
|
getSessionSummary: jest.Mock;
|
||||||
|
getSessionSummaries: jest.Mock;
|
||||||
|
};
|
||||||
|
let payoutSnapshotService: { getLatestExpectedPayoutForAddress: jest.Mock };
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
imports: [
|
|
||||||
TypeOrmModule.forRoot({
|
|
||||||
type: 'sqlite',
|
|
||||||
database: './DB/public-pool.test.sqlite',
|
|
||||||
synchronize: true,
|
|
||||||
autoLoadEntities: true,
|
|
||||||
cache: true,
|
|
||||||
logging: false
|
|
||||||
}),
|
|
||||||
AddressSettingsModule,
|
|
||||||
ClientModule,
|
|
||||||
ClientStatisticsModule
|
|
||||||
],
|
|
||||||
controllers: [ClientController],
|
controllers: [ClientController],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: ClientService,
|
||||||
|
useValue: {
|
||||||
|
getByAddress: jest.fn().mockResolvedValue([]),
|
||||||
|
getByName: jest.fn(),
|
||||||
|
getBySessionId: jest.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ClientStatisticsService,
|
||||||
|
useValue: {
|
||||||
|
getChartDataForAddress: jest.fn(),
|
||||||
|
getChartDataForGroup: jest.fn(),
|
||||||
|
getChartDataForSession: jest.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: AddressSettingsService,
|
||||||
|
useValue: {
|
||||||
|
getSettings: jest.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ShareAccountingService,
|
||||||
|
useValue: {
|
||||||
|
getAddressSummary: jest.fn(),
|
||||||
|
getWorkerGroupSummary: jest.fn(),
|
||||||
|
getSessionSummary: jest.fn(),
|
||||||
|
getSessionSummaries: jest.fn().mockResolvedValue(new Map()),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: PayoutSnapshotService,
|
||||||
|
useValue: {
|
||||||
|
getLatestExpectedPayoutForAddress: jest.fn().mockResolvedValue(null),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
controller = module.get<ClientController>(ClientController);
|
controller = module.get<ClientController>(ClientController);
|
||||||
|
clientService = module.get(ClientService);
|
||||||
|
addressSettingsService = module.get(AddressSettingsService);
|
||||||
|
shareAccountingService = module.get(ShareAccountingService);
|
||||||
|
payoutSnapshotService = module.get(PayoutSnapshotService);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(controller).toBeDefined();
|
expect(controller).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should expose the existing address best difficulty in accounting when rollup best is empty', async () => {
|
||||||
|
clientService.getByAddress.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: '92f5302f-5e32-487e-af67-f56fd78b13c7',
|
||||||
|
sessionId: 'abcd1234',
|
||||||
|
clientName: 'worker',
|
||||||
|
bestDifficulty: 64,
|
||||||
|
hashRate: 1024,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
lastSeen: '2026-06-08T12:10:00.000Z',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
addressSettingsService.getSettings.mockResolvedValue({ bestDifficulty: 4096 });
|
||||||
|
shareAccountingService.getSessionSummaries.mockResolvedValue(new Map());
|
||||||
|
shareAccountingService.getAddressSummary.mockResolvedValue({
|
||||||
|
totalAcceptedShares: 10,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.getClientInfo('bc1qtest')).resolves.toEqual(expect.objectContaining({
|
||||||
|
bestDifficulty: 4096,
|
||||||
|
accounting: expect.objectContaining({
|
||||||
|
bestSubmissionDifficulty: 4096,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should read address best difficulty in API-only mode', async () => {
|
||||||
|
const originalApiOnly = process.env.API_ONLY;
|
||||||
|
process.env.API_ONLY = 'true';
|
||||||
|
try {
|
||||||
|
addressSettingsService.getSettings.mockResolvedValue({ bestDifficulty: 8192 });
|
||||||
|
shareAccountingService.getSessionSummaries.mockResolvedValue(new Map());
|
||||||
|
shareAccountingService.getAddressSummary.mockResolvedValue({
|
||||||
|
totalAcceptedShares: 10,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.getClientInfo('bc1qtest')).resolves.toEqual(expect.objectContaining({
|
||||||
|
bestDifficulty: 8192,
|
||||||
|
accounting: expect.objectContaining({
|
||||||
|
bestSubmissionDifficulty: 8192,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
expect(addressSettingsService.getSettings).toHaveBeenCalledWith('bc1qtest', false);
|
||||||
|
} finally {
|
||||||
|
if (originalApiOnly == null) {
|
||||||
|
delete process.env.API_ONLY;
|
||||||
|
} else {
|
||||||
|
process.env.API_ONLY = originalApiOnly;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expose the latest current PPLNS expected payout for an address', async () => {
|
||||||
|
addressSettingsService.getSettings.mockResolvedValue(null);
|
||||||
|
shareAccountingService.getAddressSummary.mockResolvedValue({
|
||||||
|
totalAcceptedShares: 10,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
payoutSnapshotService.getLatestExpectedPayoutForAddress.mockResolvedValue({
|
||||||
|
snapshotId: '19',
|
||||||
|
blockHeight: 900001,
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
payoutSats: 1234,
|
||||||
|
creditedDifficulty: 50,
|
||||||
|
percent: 12.34,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.getClientInfo('bc1qtest')).resolves.toEqual(expect.objectContaining({
|
||||||
|
expectedPayout: expect.objectContaining({
|
||||||
|
snapshotId: '19',
|
||||||
|
payoutSats: 1234,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
expect(payoutSnapshotService.getLatestExpectedPayoutForAddress).toHaveBeenCalledWith('bc1qtest');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not query expected PPLNS payout for solo-only address requests', async () => {
|
||||||
|
addressSettingsService.getSettings.mockResolvedValue(null);
|
||||||
|
shareAccountingService.getAddressSummary.mockResolvedValue({
|
||||||
|
totalAcceptedShares: 10,
|
||||||
|
totalCreditedDifficulty: 100,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.getClientInfo('bc1qtest', 'solo')).resolves.toEqual(expect.objectContaining({
|
||||||
|
expectedPayout: null,
|
||||||
|
}));
|
||||||
|
expect(payoutSnapshotService.getLatestExpectedPayoutForAddress).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expose active database workers for an address', async () => {
|
||||||
|
const recent = new Date(Date.now() - 60 * 1000).toISOString();
|
||||||
|
const stale = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
||||||
|
clientService.getByAddress.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'active-client',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
sessionId: 'active1',
|
||||||
|
clientName: 'active-worker',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
bestDifficulty: 64,
|
||||||
|
hashRate: 1024,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
updatedAt: recent,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'solo-client',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
sessionId: 'solo1',
|
||||||
|
clientName: 'solo-worker',
|
||||||
|
payoutMode: 'solo',
|
||||||
|
bestDifficulty: 128,
|
||||||
|
hashRate: 2048,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
updatedAt: recent,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stale-client',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
sessionId: 'stale1',
|
||||||
|
clientName: 'stale-worker',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
bestDifficulty: 256,
|
||||||
|
hashRate: 4096,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
updatedAt: stale,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'idle-client',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
sessionId: 'idle1',
|
||||||
|
clientName: 'idle-worker',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
bestDifficulty: 512,
|
||||||
|
hashRate: 0,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
updatedAt: recent,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'deleted-client',
|
||||||
|
address: 'bc1qtest',
|
||||||
|
sessionId: 'deleted1',
|
||||||
|
clientName: 'deleted-worker',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
bestDifficulty: 1024,
|
||||||
|
hashRate: 8192,
|
||||||
|
startTime: '2026-06-08T12:00:00.000Z',
|
||||||
|
updatedAt: recent,
|
||||||
|
deletedAt: recent,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
addressSettingsService.getSettings.mockResolvedValue(null);
|
||||||
|
shareAccountingService.getSessionSummaries.mockResolvedValue(new Map());
|
||||||
|
shareAccountingService.getAddressSummary.mockResolvedValue({
|
||||||
|
totalAcceptedShares: 0,
|
||||||
|
totalCreditedDifficulty: 0,
|
||||||
|
bestSubmissionDifficulty: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(controller.getClientInfo('bc1qtest', 'pplns')).resolves.toMatchObject({
|
||||||
|
workersCount: 1,
|
||||||
|
workers: [
|
||||||
|
{
|
||||||
|
sessionId: 'active1',
|
||||||
|
name: 'active-worker',
|
||||||
|
payoutMode: 'pplns',
|
||||||
|
hashRate: 1024,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,55 +1,89 @@
|
|||||||
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';
|
import { Controller, Get, NotFoundException, Param, Query } from '@nestjs/common';
|
||||||
|
|
||||||
import { AddressSettingsService } from '../../ORM/address-settings/address-settings.service';
|
import { AddressSettingsService } from '../../ORM/address-settings/address-settings.service';
|
||||||
import { ClientStatisticsService } from '../../ORM/client-statistics/client-statistics.service';
|
import { ClientStatisticsService } from '../../ORM/client-statistics/client-statistics.service';
|
||||||
import { ClientService } from '../../ORM/client/client.service';
|
import { ClientService } from '../../ORM/client/client.service';
|
||||||
|
import { PayoutSnapshotService } from '../../ORM/payout-snapshot/payout-snapshot.service';
|
||||||
|
import { ShareAccountingService } from '../../ORM/share-accounting/share-accounting.service';
|
||||||
|
import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
|
const DEFAULT_CLIENT_ACTIVE_WINDOW_MS = 30 * 60 * 1000;
|
||||||
|
|
||||||
@Controller('client')
|
@Controller('client')
|
||||||
export class ClientController {
|
export class ClientController {
|
||||||
|
private readonly activeWindowMs = this.readPositiveInt('CLIENT_REPORT_ACTIVE_WINDOW_MS', DEFAULT_CLIENT_ACTIVE_WINDOW_MS);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly clientService: ClientService,
|
private readonly clientService: ClientService,
|
||||||
private readonly clientStatisticsService: ClientStatisticsService,
|
private readonly clientStatisticsService: ClientStatisticsService,
|
||||||
private readonly addressSettingsService: AddressSettingsService
|
private readonly addressSettingsService: AddressSettingsService,
|
||||||
|
private readonly shareAccountingService: ShareAccountingService,
|
||||||
|
private readonly payoutSnapshotService: PayoutSnapshotService,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
|
|
||||||
@Get(':address')
|
@Get(':address')
|
||||||
async getClientInfo(@Param('address') address: string) {
|
async getClientInfo(@Param('address') address: string, @Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = this.getRequestedPayoutMode(payoutMode);
|
||||||
const workers = await this.clientService.getByAddress(address);
|
const workers = await this.getActiveAddressWorkers(address, mode);
|
||||||
|
const sessionSummaries = await this.shareAccountingService.getSessionSummaries(workers.map(worker => worker.clientId));
|
||||||
|
|
||||||
const addressSettings = await this.addressSettingsService.getSettings(address, false);
|
const addressSettings = await this.addressSettingsService.getSettings(address, false);
|
||||||
|
const bestDifficulty = addressSettings?.bestDifficulty ?? workers.reduce((best, worker) => {
|
||||||
|
return Math.max(best, Number(worker.bestDifficulty ?? 0));
|
||||||
|
}, 0);
|
||||||
|
const accountingSummary = mode == null
|
||||||
|
? await this.shareAccountingService.getAddressSummary(address)
|
||||||
|
: await this.shareAccountingService.getAddressSummary(address, mode);
|
||||||
|
const accounting = this.withBestSubmissionDifficulty(accountingSummary, bestDifficulty);
|
||||||
|
const expectedPayout = mode === 'solo'
|
||||||
|
? null
|
||||||
|
: await this.payoutSnapshotService.getLatestExpectedPayoutForAddress(address);
|
||||||
|
|
||||||
return {
|
const response = {
|
||||||
bestDifficulty: addressSettings?.bestDifficulty,
|
bestDifficulty,
|
||||||
workersCount: workers.length,
|
workersCount: workers.length,
|
||||||
|
accounting,
|
||||||
|
expectedPayout,
|
||||||
workers: await Promise.all(
|
workers: await Promise.all(
|
||||||
workers.map(async (worker) => {
|
workers.map(async (worker) => {
|
||||||
|
const sessionSummary = sessionSummaries.get(worker.clientId);
|
||||||
|
const bestDifficulty = Math.max(
|
||||||
|
Number(worker.bestDifficulty ?? 0),
|
||||||
|
Number(sessionSummary?.bestSubmissionDifficulty ?? 0),
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
sessionId: worker.sessionId,
|
sessionId: worker.sessionId,
|
||||||
name: worker.clientName,
|
name: worker.clientName,
|
||||||
bestDifficulty: worker.bestDifficulty.toFixed(2),
|
payoutMode: worker.payoutMode,
|
||||||
hashRate: worker.hashRate,
|
bestDifficulty: bestDifficulty.toFixed(2),
|
||||||
|
hashRate: sessionSummary?.hashRateLast10Minutes ?? worker.hashRate,
|
||||||
startTime: worker.startTime,
|
startTime: worker.startTime,
|
||||||
lastSeen: worker.updatedAt
|
lastSeen: sessionSummary?.latestShareAt ?? worker.lastSeen
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':address/chart')
|
@Get(':address/chart')
|
||||||
async getClientInfoChart(@Param('address') address: string) {
|
async getClientInfoChart(@Param('address') address: string) {
|
||||||
const chartData = await this.clientStatisticsService.getChartDataForAddress(address);
|
return await this.clientStatisticsService.getChartDataForAddress(address);
|
||||||
return chartData;
|
}
|
||||||
|
|
||||||
|
@Get(':address/chart/payout-modes')
|
||||||
|
async getClientInfoChartByPayoutMode(@Param('address') address: string, @Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = this.getRequestedPayoutMode(payoutMode);
|
||||||
|
return await this.clientStatisticsService.getChartDataForAddressByPayoutMode(address, mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':address/:workerName')
|
@Get(':address/:workerName')
|
||||||
async getWorkerGroupInfo(@Param('address') address: string, @Param('workerName') workerName: string) {
|
async getWorkerGroupInfo(@Param('address') address: string, @Param('workerName') workerName: string, @Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = this.getRequestedPayoutMode(payoutMode);
|
||||||
const workers = await this.clientService.getByName(address, workerName);
|
const addressWorkers = await this.getActiveAddressWorkers(address, mode);
|
||||||
|
const workers = addressWorkers
|
||||||
|
.filter(worker => worker.clientName === workerName);
|
||||||
|
|
||||||
const bestDifficulty = workers.reduce((pre, cur, idx, arr) => {
|
const bestDifficulty = workers.reduce((pre, cur, idx, arr) => {
|
||||||
if (cur.bestDifficulty > pre) {
|
if (cur.bestDifficulty > pre) {
|
||||||
@@ -59,30 +93,119 @@ export class ClientController {
|
|||||||
}, 0);
|
}, 0);
|
||||||
|
|
||||||
const chartData = await this.clientStatisticsService.getChartDataForGroup(address, workerName);
|
const chartData = await this.clientStatisticsService.getChartDataForGroup(address, workerName);
|
||||||
return {
|
const chartDataByPayoutMode = await this.clientStatisticsService.getChartDataForGroupByPayoutMode(address, workerName, mode);
|
||||||
|
const accountingSummary = mode == null
|
||||||
|
? await this.shareAccountingService.getWorkerGroupSummary(address, workerName)
|
||||||
|
: await this.shareAccountingService.getWorkerGroupSummary(address, workerName, mode);
|
||||||
|
const accounting = this.withBestSubmissionDifficulty(accountingSummary, bestDifficulty);
|
||||||
|
const response = {
|
||||||
|
|
||||||
name: workerName,
|
name: workerName,
|
||||||
bestDifficulty: Math.floor(bestDifficulty),
|
bestDifficulty: Math.floor(bestDifficulty),
|
||||||
|
payoutModes: [...new Set(workers.map(worker => worker.payoutMode))],
|
||||||
|
accounting,
|
||||||
chartData: chartData,
|
chartData: chartData,
|
||||||
|
chartDataByPayoutMode,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':address/:workerName/:sessionId')
|
@Get(':address/:workerName/:sessionId')
|
||||||
async getWorkerInfo(@Param('address') address: string, @Param('workerName') workerName: string, @Param('sessionId') sessionId: string) {
|
async getWorkerInfo(@Param('address') address: string, @Param('workerName') workerName: string, @Param('sessionId') sessionId: string, @Query('payoutMode') payoutMode?: string) {
|
||||||
|
const mode = this.getRequestedPayoutMode(payoutMode);
|
||||||
const worker = await this.clientService.getBySessionId(address, workerName, sessionId);
|
const addressWorkers = await this.getActiveAddressWorkers(address, mode);
|
||||||
|
const presenceWorker = addressWorkers
|
||||||
|
.find(worker => worker.clientName === workerName && worker.sessionId === sessionId);
|
||||||
|
const worker = presenceWorker == null
|
||||||
|
? await this.clientService.getBySessionId(address, workerName, sessionId)
|
||||||
|
: {
|
||||||
|
id: presenceWorker.clientId,
|
||||||
|
sessionId: presenceWorker.sessionId,
|
||||||
|
clientName: presenceWorker.clientName,
|
||||||
|
bestDifficulty: presenceWorker.bestDifficulty,
|
||||||
|
payoutMode: presenceWorker.payoutMode,
|
||||||
|
startTime: presenceWorker.startTime,
|
||||||
|
};
|
||||||
if (worker == null) {
|
if (worker == null) {
|
||||||
return new NotFoundException();
|
return new NotFoundException();
|
||||||
}
|
}
|
||||||
const chartData = await this.clientStatisticsService.getChartDataForSession(worker.address, worker.clientName, worker.sessionId);
|
const chartData = await this.clientStatisticsService.getChartDataForSession(worker.id);
|
||||||
|
const chartDataByPayoutMode = await this.clientStatisticsService.getChartDataForSessionByPayoutMode(worker.id, mode);
|
||||||
|
const accounting = this.withBestSubmissionDifficulty(
|
||||||
|
mode == null
|
||||||
|
? await this.shareAccountingService.getSessionSummary(worker.id)
|
||||||
|
: await this.shareAccountingService.getSessionSummary(worker.id, mode),
|
||||||
|
worker.bestDifficulty,
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
const response = {
|
||||||
sessionId: worker.sessionId,
|
sessionId: worker.sessionId,
|
||||||
name: worker.clientName,
|
name: worker.clientName,
|
||||||
bestDifficulty: Math.floor(worker.bestDifficulty),
|
bestDifficulty: Math.floor(worker.bestDifficulty),
|
||||||
|
payoutMode: worker.payoutMode,
|
||||||
|
accounting,
|
||||||
chartData: chartData,
|
chartData: chartData,
|
||||||
|
chartDataByPayoutMode,
|
||||||
startTime: worker.startTime
|
startTime: worker.startTime
|
||||||
}
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private withBestSubmissionDifficulty<T extends { bestSubmissionDifficulty?: number }>(
|
||||||
|
accounting: T,
|
||||||
|
fallbackBestDifficulty: unknown,
|
||||||
|
): T {
|
||||||
|
const existing = Number(accounting?.bestSubmissionDifficulty ?? 0);
|
||||||
|
const fallback = Number(fallbackBestDifficulty ?? 0);
|
||||||
|
|
||||||
|
if (!Number.isFinite(fallback) || fallback <= existing) {
|
||||||
|
return accounting;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...accounting,
|
||||||
|
bestSubmissionDifficulty: fallback,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private getRequestedPayoutMode(payoutMode?: string): PayoutMode | undefined {
|
||||||
|
if (payoutMode == null || payoutMode === 'all') {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return normalizePayoutMode(payoutMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getActiveAddressWorkers(address: string, payoutMode?: PayoutMode) {
|
||||||
|
const workers = await this.clientService.getByAddress(address);
|
||||||
|
const activeSince = Date.now() - this.activeWindowMs;
|
||||||
|
return workers
|
||||||
|
.filter(worker => payoutMode == null || worker.payoutMode === payoutMode)
|
||||||
|
.filter(worker => worker.deletedAt == null)
|
||||||
|
.filter(worker => Number(worker.hashRate ?? 0) > 0)
|
||||||
|
.filter(worker => {
|
||||||
|
const updatedAt = worker.updatedAt == null ? 0 : new Date(worker.updatedAt).getTime();
|
||||||
|
return Number.isFinite(updatedAt) && updatedAt > activeSince;
|
||||||
|
})
|
||||||
|
.map(worker => ({
|
||||||
|
clientId: worker.id,
|
||||||
|
address: worker.address,
|
||||||
|
clientName: worker.clientName,
|
||||||
|
sessionId: worker.sessionId,
|
||||||
|
payoutMode: worker.payoutMode,
|
||||||
|
userAgent: worker.userAgent,
|
||||||
|
startTime: worker.startTime,
|
||||||
|
lastSeen: worker.updatedAt,
|
||||||
|
hashRate: Number(worker.hashRate ?? 0),
|
||||||
|
bestDifficulty: Number(worker.bestDifficulty ?? 0),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private readPositiveInt(name: string, defaultValue: number): number {
|
||||||
|
const value = Number(process.env[name]);
|
||||||
|
if (Number.isInteger(value) && value > 0) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return defaultValue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import 'dotenv/config';
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
|
||||||
|
import { createDatabaseOptions } from './database.config';
|
||||||
|
|
||||||
|
export const AppDataSource = new DataSource(createDatabaseOptions(process.env));
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
|
||||||
|
import { DataSourceOptions } from 'typeorm';
|
||||||
|
|
||||||
|
import { InitialTimescaleSchema1780859300000 } from './ORM/_migrations/InitialTimescaleSchema1780859300000';
|
||||||
|
import { ActiveOnlyUserAgentReport1780860200000 } from './ORM/_migrations/ActiveOnlyUserAgentReport1780860200000';
|
||||||
|
import { TimescaleOperationalHardening1780861200000 } from './ORM/_migrations/TimescaleOperationalHardening1780861200000';
|
||||||
|
import { AcceptedShareIndex1780862400000 } from './ORM/_migrations/AcceptedShareIndex1780862400000';
|
||||||
|
import { AcceptedShareRollupIndexes1780865400000 } from './ORM/_migrations/AcceptedShareRollupIndexes1780865400000';
|
||||||
|
import { PoolAccountingDashboardIndexes1780867200000 } from './ORM/_migrations/PoolAccountingDashboardIndexes1780867200000';
|
||||||
|
import { CurrentRoundBestShareIndex1780897600000 } from './ORM/_migrations/CurrentRoundBestShareIndex1780897600000';
|
||||||
|
import { CurrentRoundWorkRollup1780899000000 } from './ORM/_migrations/CurrentRoundWorkRollup1780899000000';
|
||||||
|
import { ShareRollupBatches1780962600000 } from './ORM/_migrations/ShareRollupBatches1780962600000';
|
||||||
|
import { AcceptedShareRetentionCompression1780966200000 } from './ORM/_migrations/AcceptedShareRetentionCompression1780966200000';
|
||||||
|
import { PayoutSnapshots1780969800000 } from './ORM/_migrations/PayoutSnapshots1780969800000';
|
||||||
|
import { AcceptedShareProtocolMetadata1781130600000 } from './ORM/_migrations/AcceptedShareProtocolMetadata1781130600000';
|
||||||
|
import { BlocksSubmissionMetadata1781220000000 } from './ORM/_migrations/BlocksSubmissionMetadata1781220000000';
|
||||||
|
import { PayoutModes1781300000000 } from './ORM/_migrations/PayoutModes1781300000000';
|
||||||
|
import { ShareRollupStoragePolicy1781305000000 } from './ORM/_migrations/ShareRollupStoragePolicy1781305000000';
|
||||||
|
import { AcceptedShareHighScores1781309000000 } from './ORM/_migrations/AcceptedShareHighScores1781309000000';
|
||||||
|
import { UserAgentReportNonzeroHashrate1781313000000 } from './ORM/_migrations/UserAgentReportNonzeroHashrate1781313000000';
|
||||||
|
import { UserAgentReportView } from './ORM/_views/user-agent-report/user-agent-report.view';
|
||||||
|
import { AcceptedShareEntity } from './ORM/accepted-share/accepted-share.entity';
|
||||||
|
import { AddressSettingsEntity } from './ORM/address-settings/address-settings.entity';
|
||||||
|
import { BlocksEntity } from './ORM/blocks/blocks.entity';
|
||||||
|
import { ClientEntity } from './ORM/client/client.entity';
|
||||||
|
import { PayoutBalanceEntity } from './ORM/payout-snapshot/payout-balance.entity';
|
||||||
|
import { PayoutHistoryEntity } from './ORM/payout-snapshot/payout-history.entity';
|
||||||
|
import { PayoutSnapshotEntity } from './ORM/payout-snapshot/payout-snapshot.entity';
|
||||||
|
import { PayoutSnapshotEntryEntity } from './ORM/payout-snapshot/payout-snapshot-entry.entity';
|
||||||
|
import { RpcBlockEntity } from './ORM/rpc-block/rpc-block.entity';
|
||||||
|
import { TelegramSubscriptionsEntity } from './ORM/telegram-subscriptions/telegram-subscriptions.entity';
|
||||||
|
|
||||||
|
export const databaseEntities = [
|
||||||
|
ClientEntity,
|
||||||
|
AddressSettingsEntity,
|
||||||
|
BlocksEntity,
|
||||||
|
RpcBlockEntity,
|
||||||
|
TelegramSubscriptionsEntity,
|
||||||
|
UserAgentReportView,
|
||||||
|
AcceptedShareEntity,
|
||||||
|
PayoutBalanceEntity,
|
||||||
|
PayoutHistoryEntity,
|
||||||
|
PayoutSnapshotEntity,
|
||||||
|
PayoutSnapshotEntryEntity,
|
||||||
|
];
|
||||||
|
|
||||||
|
export const databaseMigrations = [
|
||||||
|
InitialTimescaleSchema1780859300000,
|
||||||
|
ActiveOnlyUserAgentReport1780860200000,
|
||||||
|
TimescaleOperationalHardening1780861200000,
|
||||||
|
AcceptedShareIndex1780862400000,
|
||||||
|
AcceptedShareRollupIndexes1780865400000,
|
||||||
|
PoolAccountingDashboardIndexes1780867200000,
|
||||||
|
CurrentRoundBestShareIndex1780897600000,
|
||||||
|
CurrentRoundWorkRollup1780899000000,
|
||||||
|
ShareRollupBatches1780962600000,
|
||||||
|
AcceptedShareRetentionCompression1780966200000,
|
||||||
|
PayoutSnapshots1780969800000,
|
||||||
|
AcceptedShareProtocolMetadata1781130600000,
|
||||||
|
BlocksSubmissionMetadata1781220000000,
|
||||||
|
PayoutModes1781300000000,
|
||||||
|
ShareRollupStoragePolicy1781305000000,
|
||||||
|
AcceptedShareHighScores1781309000000,
|
||||||
|
UserAgentReportNonzeroHashrate1781313000000,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function createDatabaseOptions(env: NodeJS.ProcessEnv): TypeOrmModuleOptions & DataSourceOptions {
|
||||||
|
return {
|
||||||
|
type: 'postgres',
|
||||||
|
host: env.DB_HOST,
|
||||||
|
port: parseInt(env.DB_PORT ?? '5432', 10),
|
||||||
|
username: env.DB_USERNAME,
|
||||||
|
password: env.DB_PASSWORD,
|
||||||
|
database: env.DB_DATABASE,
|
||||||
|
entities: databaseEntities,
|
||||||
|
synchronize: false,
|
||||||
|
logging: env.DB_LOGGING === 'true',
|
||||||
|
poolSize: parseInt(env.DB_POOL_SIZE ?? '10', 10),
|
||||||
|
ssl: env.DB_SSL === 'true'
|
||||||
|
? { rejectUnauthorized: env.DB_SSL_REJECT_UNAUTHORIZED !== 'false' }
|
||||||
|
: undefined,
|
||||||
|
migrations: databaseMigrations,
|
||||||
|
migrationsTransactionMode: 'none',
|
||||||
|
};
|
||||||
|
}
|
||||||
+61
-10
@@ -3,38 +3,43 @@ import { NestFactory } from '@nestjs/core';
|
|||||||
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
|
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||||
import * as bitcoinjs from 'bitcoinjs-lib';
|
import * as bitcoinjs from 'bitcoinjs-lib';
|
||||||
import { useContainer } from 'class-validator';
|
import { useContainer } from 'class-validator';
|
||||||
import { readFileSync } from 'fs';
|
import { readFileSync, watch } from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
import * as ecc from 'tiny-secp256k1';
|
import * as ecc from 'tiny-secp256k1';
|
||||||
|
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
|
|
||||||
if (process.env.API_PORT == null) {
|
if (process.env.API_PORT == null) {
|
||||||
console.error('It appears your environment is not configured, create and populate an .env file.');
|
console.error('It appears your environment is not configured, create and populate an .env file.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let options = {};
|
const apiEnabled = process.env.API_ENABLED?.toLowerCase();
|
||||||
const secure = process.env.API_SECURE?.toLowerCase() == 'true';
|
const serveApi = apiEnabled == null ? process.env.MASTER !== 'false' : apiEnabled === 'true';
|
||||||
if (secure) {
|
const secure = serveApi && process.env.API_SECURE?.toLowerCase() === 'true';
|
||||||
const currentDirectory = process.cwd();
|
const currentDirectory = process.cwd();
|
||||||
|
const keyPath = path.join(currentDirectory, 'secrets', 'key.pem');
|
||||||
|
const certPath = path.join(currentDirectory, 'secrets', 'cert.pem');
|
||||||
|
|
||||||
|
let options: any = {};
|
||||||
|
if (secure) {
|
||||||
options = {
|
options = {
|
||||||
https: {
|
https: {
|
||||||
key: readFileSync(`${currentDirectory}/secrets/key.pem`),
|
key: readFileSync(keyPath),
|
||||||
cert: readFileSync(`${currentDirectory}/secrets/cert.pem`),
|
cert: readFileSync(certPath),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter(options));
|
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter(options));
|
||||||
app.setGlobalPrefix('api')
|
app.setGlobalPrefix('api');
|
||||||
app.useGlobalPipes(
|
app.useGlobalPipes(
|
||||||
new ValidationPipe({
|
new ValidationPipe({
|
||||||
transform: true,
|
transform: true,
|
||||||
whitelist: true,
|
whitelist: true,
|
||||||
forbidNonWhitelisted: true,
|
//forbidNonWhitelisted: true,
|
||||||
forbidUnknownValues: true
|
//forbidUnknownValues: true
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -54,10 +59,56 @@ async function bootstrap() {
|
|||||||
// Taproot
|
// Taproot
|
||||||
bitcoinjs.initEccLib(ecc);
|
bitcoinjs.initEccLib(ecc);
|
||||||
|
|
||||||
|
if (!serveApi) {
|
||||||
|
await app.init();
|
||||||
|
console.log('Worker process skipping API listener');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await app.listen(process.env.API_PORT, '0.0.0.0', (err, address) => {
|
await app.listen(process.env.API_PORT, '0.0.0.0', (err, address) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
console.log(`API listening on ${address}`);
|
console.log(`API listening on ${address}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Live-reload TLS certs/keys when they change on disk ---
|
||||||
|
if (secure) {
|
||||||
|
// Fastify's underlying Node https server
|
||||||
|
const server: any = app.getHttpServer();
|
||||||
|
|
||||||
|
// Guard: only HTTPS servers expose setSecureContext
|
||||||
|
if (typeof server?.setSecureContext === 'function') {
|
||||||
|
let reloadTimer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
const scheduleReload = () => {
|
||||||
|
if (reloadTimer) clearTimeout(reloadTimer);
|
||||||
|
// Debounce multiple fs events during a single write/replace
|
||||||
|
reloadTimer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
const key = readFileSync(keyPath);
|
||||||
|
const cert = readFileSync(certPath);
|
||||||
|
server.setSecureContext({ key, cert });
|
||||||
|
console.log(`[TLS] Reloaded certificate @ ${new Date().toISOString()}`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[TLS] Failed to reload certificate:', e);
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Watch both files; handle 'change' and 'rename' (rename often fired on atomic replace)
|
||||||
|
try {
|
||||||
|
watch(keyPath, { persistent: true }, scheduleReload);
|
||||||
|
watch(certPath, { persistent: true }, scheduleReload);
|
||||||
|
console.log('[TLS] Watching cert/key for changes');
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[TLS] Failed to watch cert/key files:', e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('[TLS] Dynamic cert reload not available (non-HTTPS server?)');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
import * as bitcoinjs from 'bitcoinjs-lib';
|
||||||
|
import { BehaviorSubject, firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
|
import { MockRecording1 } from '../../test/models/MockRecording1';
|
||||||
|
import { createSubsidyOnlyBlockTemplate } from '../services/subsidy-only-template.factory';
|
||||||
|
import { StratumV1JobsService } from '../services/stratum-v1-jobs.service';
|
||||||
|
import { MiningJob } from './MiningJob';
|
||||||
|
|
||||||
|
describe('MiningJob', () => {
|
||||||
|
let jobTemplate;
|
||||||
|
let job: MiningJob;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(new Date(parseInt(MockRecording1.TIME, 16) * 1000));
|
||||||
|
|
||||||
|
const blockTemplate$ = new BehaviorSubject(MockRecording1.BLOCK_TEMPLATE);
|
||||||
|
const bitcoinRpcService = {
|
||||||
|
newBlockTemplate$: blockTemplate$.asObservable(),
|
||||||
|
miningInfo: { blocks: MockRecording1.BLOCK_TEMPLATE.height }
|
||||||
|
};
|
||||||
|
jest.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
const jobsService = new StratumV1JobsService(bitcoinRpcService as any);
|
||||||
|
jobTemplate = await firstValueFrom(jobsService.newMiningJob$);
|
||||||
|
job = new MiningJob(
|
||||||
|
bitcoinjs.networks.testnet,
|
||||||
|
'1',
|
||||||
|
[{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', percent: 100 }],
|
||||||
|
jobTemplate
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should split coinbase around 12 bytes of extranonce space', () => {
|
||||||
|
const notify = JSON.parse(job.response(jobTemplate));
|
||||||
|
const coinbasePart1 = notify.params[2];
|
||||||
|
const coinbasePart2 = notify.params[3];
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const coinbase = bitcoinjs.Transaction.fromHex(`${coinbasePart1}${extraNonce1}${extraNonce2}${coinbasePart2}`);
|
||||||
|
|
||||||
|
expect(Buffer.byteLength(extraNonce1 + extraNonce2, 'hex')).toBe(12);
|
||||||
|
expect(coinbase.ins[0].script.toString('hex')).toContain(`${extraNonce1}${extraNonce2}`);
|
||||||
|
expect(coinbase.ins[0].script.toString('hex').endsWith(`${extraNonce1}${extraNonce2}`)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ height: 1, expectedPrefix: '51' },
|
||||||
|
{ height: 16, expectedPrefix: '60' },
|
||||||
|
{ height: 17, expectedPrefix: '0111' },
|
||||||
|
])('minimally encodes BIP34 coinbase height $height', ({ height, expectedPrefix }) => {
|
||||||
|
const heightTemplate = {
|
||||||
|
...jobTemplate,
|
||||||
|
blockData: { ...jobTemplate.blockData, height },
|
||||||
|
};
|
||||||
|
const heightJob = new MiningJob(
|
||||||
|
bitcoinjs.networks.testnet,
|
||||||
|
`height-${height}`,
|
||||||
|
[{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', percent: 100 }],
|
||||||
|
heightTemplate,
|
||||||
|
);
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const coinbase = bitcoinjs.Transaction.fromHex([
|
||||||
|
heightJob.getCoinbasePrefixBuffer().toString('hex'),
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
heightJob.getCoinbaseSuffixBuffer().toString('hex'),
|
||||||
|
].join(''));
|
||||||
|
|
||||||
|
expect(coinbase.ins[0].script.toString('hex').startsWith(expectedPrefix)).toBe(true);
|
||||||
|
expect(coinbase.ins[0].script.toString('hex').endsWith(`${extraNonce1}${extraNonce2}`)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expose coinbase prefix and suffix buffers for SV2 extended jobs', () => {
|
||||||
|
const notify = JSON.parse(job.response(jobTemplate));
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const fromNotify = Buffer.from(`${notify.params[2]}${extraNonce1}${extraNonce2}${notify.params[3]}`, 'hex');
|
||||||
|
const fromBuffers = Buffer.concat([
|
||||||
|
job.getCoinbasePrefixBuffer(),
|
||||||
|
Buffer.from(`${extraNonce1}${extraNonce2}`, 'hex'),
|
||||||
|
job.getCoinbaseSuffixBuffer(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(fromBuffers).toEqual(fromNotify);
|
||||||
|
expect(bitcoinjs.Transaction.fromBuffer(fromBuffers).ins[0].script.toString('hex'))
|
||||||
|
.toContain(`${extraNonce1}${extraNonce2}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should support exact satoshi payout outputs', () => {
|
||||||
|
const firstAmount = Math.floor(jobTemplate.blockData.coinbasevalue / 3);
|
||||||
|
const secondAmount = jobTemplate.blockData.coinbasevalue - firstAmount;
|
||||||
|
const exactPayoutJob = new MiningJob(
|
||||||
|
bitcoinjs.networks.testnet,
|
||||||
|
'2',
|
||||||
|
[
|
||||||
|
{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', amountSats: firstAmount },
|
||||||
|
{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', amountSats: secondAmount },
|
||||||
|
],
|
||||||
|
jobTemplate
|
||||||
|
);
|
||||||
|
const coinbase = exactPayoutJob.cloneCoinbaseTransaction();
|
||||||
|
|
||||||
|
expect(coinbase.outs[0].value).toBe(firstAmount);
|
||||||
|
expect(coinbase.outs[1].value).toBe(secondAmount);
|
||||||
|
expect(coinbase.outs[2].value).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update block nonce, timestamp, version mask, and coinbase script', () => {
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const timestamp = parseInt(MockRecording1.TIME, 16);
|
||||||
|
const originalMerkleRoot = Buffer.from(jobTemplate.block.merkleRoot);
|
||||||
|
|
||||||
|
const updatedBlock = job.copyAndUpdateBlock(
|
||||||
|
jobTemplate,
|
||||||
|
parseInt('00002000', 16),
|
||||||
|
parseInt('ed460d91', 16),
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
timestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(updatedBlock.nonce).toBe(parseInt('ed460d91', 16));
|
||||||
|
expect(updatedBlock.timestamp).toBe(timestamp);
|
||||||
|
expect(updatedBlock.version).toBe(jobTemplate.block.version ^ parseInt('00002000', 16));
|
||||||
|
expect(updatedBlock.transactions[0].ins[0].script.toString('hex').endsWith(`${extraNonce1}${extraNonce2}`)).toBe(true);
|
||||||
|
expect(updatedBlock.merkleRoot.equals(originalMerkleRoot)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replaces negotiated BIP310 bits without toggling bits already set in the job version', () => {
|
||||||
|
const versionRollingMask = 0x1fffe000;
|
||||||
|
const versionBits = 0x00002000;
|
||||||
|
const baseVersion = 0xa0002000 | 0;
|
||||||
|
const versionedTemplate = {
|
||||||
|
...jobTemplate,
|
||||||
|
block: Object.assign(new bitcoinjs.Block(), jobTemplate.block, {
|
||||||
|
version: baseVersion,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const expectedVersion = 0xa0002000 >>> 0;
|
||||||
|
|
||||||
|
expect(MiningJob.applyVersionRolling(baseVersion, versionBits, versionRollingMask))
|
||||||
|
.toBe(expectedVersion);
|
||||||
|
const updatedBlock = job.copyAndUpdateBlock(
|
||||||
|
versionedTemplate,
|
||||||
|
versionBits,
|
||||||
|
parseInt('ed460d91', 16),
|
||||||
|
'57a6f098',
|
||||||
|
'c708000000000000',
|
||||||
|
parseInt(MockRecording1.TIME, 16),
|
||||||
|
versionRollingMask,
|
||||||
|
);
|
||||||
|
const header = job.buildHeaderBuffer(
|
||||||
|
versionedTemplate,
|
||||||
|
versionBits,
|
||||||
|
parseInt('ed460d91', 16),
|
||||||
|
'57a6f098',
|
||||||
|
'c708000000000000',
|
||||||
|
parseInt(MockRecording1.TIME, 16),
|
||||||
|
versionRollingMask,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(updatedBlock.version >>> 0).toBe(expectedVersion);
|
||||||
|
expect(header.readUInt32LE(0)).toBe(expectedVersion);
|
||||||
|
expect(header).toEqual(updatedBlock.toBuffer(true));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should leave block version unchanged without a version mask', () => {
|
||||||
|
const updatedBlock = job.copyAndUpdateBlock(
|
||||||
|
jobTemplate,
|
||||||
|
0,
|
||||||
|
parseInt('ed460d91', 16),
|
||||||
|
'57a6f098',
|
||||||
|
'c708000000000000',
|
||||||
|
parseInt(MockRecording1.TIME, 16)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(updatedBlock.version).toBe(jobTemplate.block.version);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should build the same header as the full block update path', () => {
|
||||||
|
const versionMask = parseInt('00002000', 16);
|
||||||
|
const nonce = parseInt('ed460d91', 16);
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const timestamp = parseInt(MockRecording1.TIME, 16);
|
||||||
|
|
||||||
|
const updatedBlock = job.copyAndUpdateBlock(
|
||||||
|
jobTemplate,
|
||||||
|
versionMask,
|
||||||
|
nonce,
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
timestamp
|
||||||
|
);
|
||||||
|
const fastHeader = job.buildHeaderBuffer(
|
||||||
|
jobTemplate,
|
||||||
|
versionMask,
|
||||||
|
nonce,
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
timestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fastHeader.equals(updatedBlock.toBuffer(true))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hydrates the raw transaction body only when reconstructing a full candidate', () => {
|
||||||
|
const versionMask = parseInt('00002000', 16);
|
||||||
|
const nonce = parseInt('ed460d91', 16);
|
||||||
|
const extraNonce1 = '57a6f098';
|
||||||
|
const extraNonce2 = 'c708000000000000';
|
||||||
|
const timestamp = parseInt(MockRecording1.TIME, 16);
|
||||||
|
const fromHexSpy = jest.spyOn(bitcoinjs.Transaction, 'fromHex');
|
||||||
|
|
||||||
|
const merkleRoot = job.buildCoinbaseMerkleRoot(extraNonce1, extraNonce2);
|
||||||
|
job.buildHeaderBuffer(
|
||||||
|
jobTemplate,
|
||||||
|
versionMask,
|
||||||
|
nonce,
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
timestamp,
|
||||||
|
);
|
||||||
|
expect(fromHexSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const candidate = job.copyAndUpdateBlock(
|
||||||
|
jobTemplate,
|
||||||
|
versionMask,
|
||||||
|
nonce,
|
||||||
|
extraNonce1,
|
||||||
|
extraNonce2,
|
||||||
|
timestamp,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fromHexSpy).toHaveBeenCalledTimes(jobTemplate.blockData.transactions.length);
|
||||||
|
expect(candidate.transactions).toHaveLength(jobTemplate.blockData.transactions.length + 1);
|
||||||
|
expect(candidate.transactions.slice(1).map(transaction => transaction.toHex()))
|
||||||
|
.toEqual(jobTemplate.blockData.transactions.map(transaction => transaction.data));
|
||||||
|
expect(candidate.transactions.slice(1).map(transaction => transaction.getId()))
|
||||||
|
.toEqual(jobTemplate.blockData.transactions.map(transaction => transaction.txid));
|
||||||
|
expect(candidate.merkleRoot).toEqual(merkleRoot);
|
||||||
|
expect(bitcoinjs.Block.calculateMerkleRoot(candidate.transactions, false))
|
||||||
|
.toEqual(candidate.merkleRoot);
|
||||||
|
expect(candidate.checkTxRoots()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a lazily hydrated candidate body whose bytes do not match the GBT txid', () => {
|
||||||
|
const corruptedTemplate = {
|
||||||
|
...jobTemplate,
|
||||||
|
blockData: {
|
||||||
|
...jobTemplate.blockData,
|
||||||
|
transactions: jobTemplate.blockData.transactions.map((transaction, index) => ({
|
||||||
|
...transaction,
|
||||||
|
txid: index === 0 ? '00'.repeat(32) : transaction.txid,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(() => job.copyAndUpdateBlock(
|
||||||
|
corruptedTemplate,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
'57a6f098',
|
||||||
|
'c708000000000000',
|
||||||
|
parseInt(MockRecording1.TIME, 16),
|
||||||
|
)).toThrow('data does not match its txid');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds a consensus-shaped subsidy bridge with one coinbase and a clean notify', async () => {
|
||||||
|
const authoritative = {
|
||||||
|
...MockRecording1.BLOCK_TEMPLATE,
|
||||||
|
height: 840_000,
|
||||||
|
transactions: MockRecording1.BLOCK_TEMPLATE.transactions.map(tx => ({ ...tx })),
|
||||||
|
};
|
||||||
|
authoritative.coinbasevalue = 312_500_000
|
||||||
|
+ authoritative.transactions.reduce((sum, transaction) => sum + transaction.fee, 0);
|
||||||
|
const emptyTemplate = createSubsidyOnlyBlockTemplate({
|
||||||
|
authoritativeTemplate: authoritative,
|
||||||
|
network: 'mainnet',
|
||||||
|
payoutMode: 'solo',
|
||||||
|
});
|
||||||
|
const emptyTemplate$ = new BehaviorSubject(emptyTemplate);
|
||||||
|
const jobsService = new StratumV1JobsService({
|
||||||
|
newBlockTemplate$: emptyTemplate$.asObservable(),
|
||||||
|
miningInfo: { blocks: emptyTemplate.height - 1 },
|
||||||
|
} as any);
|
||||||
|
const emptyJobTemplate = await firstValueFrom(jobsService.newMiningJob$);
|
||||||
|
const emptyJob = new MiningJob(
|
||||||
|
bitcoinjs.networks.testnet,
|
||||||
|
'bridge',
|
||||||
|
[{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', percent: 100 }],
|
||||||
|
emptyJobTemplate,
|
||||||
|
);
|
||||||
|
|
||||||
|
const notify = JSON.parse(emptyJob.response(emptyJobTemplate));
|
||||||
|
const fromHexSpy = jest.spyOn(bitcoinjs.Transaction, 'fromHex');
|
||||||
|
const reconstructed = emptyJob.copyAndUpdateBlock(
|
||||||
|
emptyJobTemplate,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
'57a6f098',
|
||||||
|
'c708000000000000',
|
||||||
|
emptyJobTemplate.block.timestamp,
|
||||||
|
);
|
||||||
|
const coinbaseScript = reconstructed.transactions[0].ins[0].script;
|
||||||
|
const encodedHeight = coinbaseScript.subarray(1, 1 + coinbaseScript[0]);
|
||||||
|
|
||||||
|
expect(emptyJobTemplate.merkle_branch).toEqual([]);
|
||||||
|
expect(notify.params[8]).toBe(true);
|
||||||
|
expect(fromHexSpy).not.toHaveBeenCalled();
|
||||||
|
expect(reconstructed.transactions).toHaveLength(1);
|
||||||
|
expect(reconstructed.transactions[0].outs.reduce((sum, output) => sum + output.value, 0))
|
||||||
|
.toBe(312_500_000);
|
||||||
|
expect(bitcoinjs.script.number.decode(encodedHeight)).toBe(840_000);
|
||||||
|
expect(reconstructed.transactions[0].outs[1].script.toString('hex'))
|
||||||
|
.toBe(emptyTemplate.default_witness_commitment);
|
||||||
|
expect(bitcoinjs.Block.calculateMerkleRoot(reconstructed.transactions, false))
|
||||||
|
.toEqual(reconstructed.merkleRoot);
|
||||||
|
});
|
||||||
|
});
|
||||||
+213
-54
@@ -2,32 +2,55 @@ import { AddressType, getAddressInfo } from 'bitcoin-address-validation';
|
|||||||
import * as bitcoinjs from 'bitcoinjs-lib';
|
import * as bitcoinjs from 'bitcoinjs-lib';
|
||||||
|
|
||||||
import { IJobTemplate } from '../services/stratum-v1-jobs.service';
|
import { IJobTemplate } from '../services/stratum-v1-jobs.service';
|
||||||
|
import { PayoutMode } from '../types/payout-mode';
|
||||||
|
import { hash256 } from '../utils/hash.utils';
|
||||||
import { eResponseMethod } from './enums/eResponseMethod';
|
import { eResponseMethod } from './enums/eResponseMethod';
|
||||||
import { IMiningNotify } from './stratum-messages/IMiningNotify';
|
import { IMiningNotify } from './stratum-messages/IMiningNotify';
|
||||||
|
import { TOTAL_EXTRANONCE_SIZE_BYTES } from './stratum.constants';
|
||||||
|
|
||||||
|
|
||||||
interface AddressObject {
|
export interface AddressObject {
|
||||||
address: string;
|
address: string;
|
||||||
percent: number;
|
percent?: number;
|
||||||
|
amountSats?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MiningJobOwnership {
|
||||||
|
payoutMode: PayoutMode;
|
||||||
|
payoutIdentity: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class MiningJob {
|
export class MiningJob {
|
||||||
|
|
||||||
|
private static readonly paymentScriptCache = new Map<string, Buffer>();
|
||||||
|
private static readonly paymentScriptCacheMaxEntries = 250_000;
|
||||||
|
|
||||||
private coinbaseTransaction: bitcoinjs.Transaction;
|
private coinbaseTransaction: bitcoinjs.Transaction;
|
||||||
private coinbasePart1: string;
|
private coinbasePart1: string;
|
||||||
private coinbasePart2: string;
|
private coinbasePart2: string;
|
||||||
|
private coinbasePart1Buffer: Buffer;
|
||||||
|
private coinbasePart2Buffer: Buffer;
|
||||||
|
private merkleBranchBuffers: Buffer[];
|
||||||
|
private miningNotifyResponse: string;
|
||||||
|
private miningNotifyResponseBuffer: Buffer;
|
||||||
|
|
||||||
public jobTemplateId: string;
|
public jobTemplateId: string;
|
||||||
|
public tipKey: string;
|
||||||
public networkDifficulty: number;
|
public networkDifficulty: number;
|
||||||
|
public creation: number;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private network: bitcoinjs.networks.Network,
|
private network: bitcoinjs.networks.Network,
|
||||||
public jobId: string,
|
public jobId: string,
|
||||||
payoutInformation: AddressObject[],
|
payoutInformation: AddressObject[],
|
||||||
jobTemplate: IJobTemplate
|
jobTemplate: IJobTemplate,
|
||||||
|
public readonly ownership?: MiningJobOwnership,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
this.creation = new Date().getTime();
|
||||||
this.jobTemplateId = jobTemplate.blockData.id;
|
this.jobTemplateId = jobTemplate.blockData.id;
|
||||||
|
this.tipKey = jobTemplate.blockData.tipKey;
|
||||||
|
this.merkleBranchBuffers = jobTemplate.merkle_branch.map(branch => Buffer.from(branch, 'hex'));
|
||||||
|
|
||||||
this.coinbaseTransaction = this.createCoinbaseTransaction(payoutInformation, jobTemplate.blockData.coinbasevalue);
|
this.coinbaseTransaction = this.createCoinbaseTransaction(payoutInformation, jobTemplate.blockData.coinbasevalue);
|
||||||
|
|
||||||
@@ -39,20 +62,17 @@ export class MiningJob {
|
|||||||
// 32-byte - Commitment hash: Double-SHA256(witness root hash|witness reserved value)
|
// 32-byte - Commitment hash: Double-SHA256(witness root hash|witness reserved value)
|
||||||
|
|
||||||
// 39th byte onwards: Optional data with no consensus meaning
|
// 39th byte onwards: Optional data with no consensus meaning
|
||||||
const extra = Buffer.from('\\public-pool\\');
|
const extra = Buffer.from('Public-Pool');
|
||||||
|
|
||||||
// Encode the block height
|
// BIP34 uses Bitcoin Script's minimally encoded integer push. Heights
|
||||||
// https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki
|
// 1..16 are OP_1..OP_16, not a one-byte PUSHDATA operation. Keeping the
|
||||||
const blockHeightEncoded = bitcoinjs.script.number.encode(jobTemplate.blockData.height);
|
// extranonce padding independent of the height width also prevents a
|
||||||
|
// future four-byte height from consuming part of the pool tag.
|
||||||
|
const blockHeightPrefix = this.encodeCoinbaseHeight(jobTemplate.blockData.height);
|
||||||
|
const padding = Buffer.alloc(TOTAL_EXTRANONCE_SIZE_BYTES, 0);
|
||||||
|
|
||||||
// Get the length of the block height encoding
|
// Build the script with the extranonce placeholder at the very end.
|
||||||
const blockHeightLengthByte = Buffer.from([blockHeightEncoded.length]);
|
this.coinbaseTransaction.ins[0].script = Buffer.concat([blockHeightPrefix, extra, padding]);
|
||||||
|
|
||||||
// generate padding and take length of encode blockHeight into account
|
|
||||||
const padding = Buffer.alloc(8 + (3 - blockHeightEncoded.length), 0)
|
|
||||||
|
|
||||||
// build the script
|
|
||||||
this.coinbaseTransaction.ins[0].script = Buffer.concat([blockHeightLengthByte, blockHeightEncoded, extra, padding])
|
|
||||||
|
|
||||||
this.coinbaseTransaction.addOutput(bitcoinjs.script.compile([bitcoinjs.opcodes.OP_RETURN, Buffer.concat([segwitMagicBits, jobTemplate.block.witnessCommit])]), 0);
|
this.coinbaseTransaction.addOutput(bitcoinjs.script.compile([bitcoinjs.opcodes.OP_RETURN, Buffer.concat([segwitMagicBits, jobTemplate.block.witnessCommit])]), 0);
|
||||||
|
|
||||||
@@ -64,35 +84,135 @@ export class MiningJob {
|
|||||||
|
|
||||||
const partOneIndex = serializedCoinbaseTx.indexOf(inputScript) + inputScript.length;
|
const partOneIndex = serializedCoinbaseTx.indexOf(inputScript) + inputScript.length;
|
||||||
|
|
||||||
this.coinbasePart1 = serializedCoinbaseTx.slice(0, partOneIndex - 16);
|
this.coinbasePart1 = serializedCoinbaseTx.slice(0, partOneIndex - (TOTAL_EXTRANONCE_SIZE_BYTES * 2));
|
||||||
this.coinbasePart2 = serializedCoinbaseTx.slice(partOneIndex);
|
this.coinbasePart2 = serializedCoinbaseTx.slice(partOneIndex);
|
||||||
|
this.coinbasePart1Buffer = Buffer.from(this.coinbasePart1, 'hex');
|
||||||
|
this.coinbasePart2Buffer = Buffer.from(this.coinbasePart2, 'hex');
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public copyAndUpdateBlock(jobTemplate: IJobTemplate, versionMask: number, nonce: number, extraNonce: string, extraNonce2: string, timestamp: number): bitcoinjs.Block {
|
public cloneCoinbaseTransaction(): bitcoinjs.Transaction {
|
||||||
|
return bitcoinjs.Transaction.fromBuffer(this.coinbaseTransaction.toBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
public getCoinbasePrefixBuffer(): Buffer {
|
||||||
|
return Buffer.from(this.coinbasePart1Buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getCoinbaseSuffixBuffer(): Buffer {
|
||||||
|
return Buffer.from(this.coinbasePart2Buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public buildCoinbaseMerkleRoot(extraNonce: string, extraNonce2: string): Buffer {
|
||||||
|
const coinbaseBuffer = Buffer.concat([
|
||||||
|
this.coinbasePart1Buffer,
|
||||||
|
Buffer.from(`${extraNonce}${extraNonce2}`, 'hex'),
|
||||||
|
this.coinbasePart2Buffer,
|
||||||
|
]);
|
||||||
|
return MiningJob.calculateMerkleRootFromCoinbaseHash(
|
||||||
|
hash256(coinbaseBuffer),
|
||||||
|
this.merkleBranchBuffers,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static calculateMerkleRootFromCoinbaseHash(
|
||||||
|
coinbaseHash: Buffer,
|
||||||
|
merkleBranches: readonly Buffer[],
|
||||||
|
): Buffer {
|
||||||
|
let merkleRoot = coinbaseHash;
|
||||||
|
const bothMerkles = Buffer.alloc(64);
|
||||||
|
for (const merkleBranch of merkleBranches) {
|
||||||
|
bothMerkles.set(merkleRoot, 0);
|
||||||
|
bothMerkles.set(merkleBranch, 32);
|
||||||
|
merkleRoot = hash256(bothMerkles);
|
||||||
|
}
|
||||||
|
return merkleRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static applyVersionRolling(jobVersion: number, versionBits: number, mask: number): number {
|
||||||
|
const unsignedJobVersion = jobVersion >>> 0;
|
||||||
|
const unsignedVersionBits = versionBits >>> 0;
|
||||||
|
const unsignedMask = mask >>> 0;
|
||||||
|
return (
|
||||||
|
(unsignedJobVersion & (~unsignedMask >>> 0))
|
||||||
|
| (unsignedVersionBits & unsignedMask)
|
||||||
|
) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public buildHeaderBuffer(
|
||||||
|
jobTemplate: IJobTemplate,
|
||||||
|
versionBits: number,
|
||||||
|
nonce: number,
|
||||||
|
extraNonce: string,
|
||||||
|
extraNonce2: string,
|
||||||
|
timestamp: number,
|
||||||
|
versionRollingMask?: number,
|
||||||
|
): Buffer {
|
||||||
|
const merkleRoot = this.buildCoinbaseMerkleRoot(extraNonce, extraNonce2);
|
||||||
|
|
||||||
|
const version = versionRollingMask == null
|
||||||
|
// SV2 standard-channel reconstruction passes an XOR delta because
|
||||||
|
// its submit message contains the complete version field.
|
||||||
|
? (jobTemplate.block.version ^ versionBits) >>> 0
|
||||||
|
: MiningJob.applyVersionRolling(jobTemplate.block.version, versionBits, versionRollingMask);
|
||||||
|
|
||||||
|
const header = Buffer.alloc(80);
|
||||||
|
header.writeUInt32LE(version, 0);
|
||||||
|
jobTemplate.block.prevHash.copy(header, 4);
|
||||||
|
merkleRoot.copy(header, 36);
|
||||||
|
header.writeUInt32LE(timestamp, 68);
|
||||||
|
header.writeUInt32LE(jobTemplate.block.bits, 72);
|
||||||
|
header.writeUInt32LE(nonce, 76);
|
||||||
|
|
||||||
|
return header;
|
||||||
|
}
|
||||||
|
|
||||||
|
public copyAndUpdateBlock(
|
||||||
|
jobTemplate: IJobTemplate,
|
||||||
|
versionBits: number,
|
||||||
|
nonce: number,
|
||||||
|
extraNonce: string,
|
||||||
|
extraNonce2: string,
|
||||||
|
timestamp: number,
|
||||||
|
versionRollingMask?: number,
|
||||||
|
): bitcoinjs.Block {
|
||||||
|
|
||||||
const testBlock = Object.assign(new bitcoinjs.Block(), jobTemplate.block);
|
const testBlock = Object.assign(new bitcoinjs.Block(), jobTemplate.block);
|
||||||
testBlock.transactions = jobTemplate.block.transactions.map(tx => {
|
const rawTransactions = jobTemplate.blockData.transactions;
|
||||||
return Object.assign(new bitcoinjs.Transaction(), tx);
|
testBlock.transactions = [
|
||||||
});
|
this.cloneCoinbaseTransaction(),
|
||||||
|
...(rawTransactions == null
|
||||||
testBlock.transactions[0] = this.coinbaseTransaction;
|
? jobTemplate.block.transactions.slice(1).map(tx =>
|
||||||
|
Object.assign(new bitcoinjs.Transaction(), tx))
|
||||||
|
: rawTransactions.map((rawTransaction, index) => {
|
||||||
|
const transaction = bitcoinjs.Transaction.fromHex(rawTransaction.data);
|
||||||
|
if (transaction.getId().toLowerCase() !== rawTransaction.txid.toLowerCase()) {
|
||||||
|
throw new Error(`transactions[${index}] data does not match its txid`);
|
||||||
|
}
|
||||||
|
return transaction;
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
testBlock.nonce = nonce;
|
testBlock.nonce = nonce;
|
||||||
|
|
||||||
// recompute version mask
|
const version = versionRollingMask == null
|
||||||
if (versionMask !== undefined && versionMask != 0) {
|
? (testBlock.version ^ versionBits) >>> 0
|
||||||
testBlock.version = (testBlock.version ^ versionMask);
|
: MiningJob.applyVersionRolling(testBlock.version, versionBits, versionRollingMask);
|
||||||
}
|
// bitcoinjs-lib serializes Block.version as a signed int32, while the
|
||||||
|
// protocol and bit-mask arithmetic use the corresponding uint32 bits.
|
||||||
|
testBlock.version = version | 0;
|
||||||
|
|
||||||
// set the nonces
|
// set the nonces
|
||||||
const nonceScript = testBlock.transactions[0].ins[0].script.toString('hex');
|
const nonceScript = testBlock.transactions[0].ins[0].script.toString('hex');
|
||||||
|
|
||||||
testBlock.transactions[0].ins[0].script = Buffer.from(`${nonceScript.substring(0, nonceScript.length - 16)}${extraNonce}${extraNonce2}`, 'hex');
|
testBlock.transactions[0].ins[0].script = Buffer.from(`${nonceScript.substring(0, nonceScript.length - (TOTAL_EXTRANONCE_SIZE_BYTES * 2))}${extraNonce}${extraNonce2}`, 'hex');
|
||||||
|
|
||||||
//recompute the root since we updated the coinbase script with the nonces
|
//recompute the root since we updated the coinbase script with the nonces
|
||||||
testBlock.merkleRoot = this.calculateMerkleRootHash(testBlock.transactions[0].getHash(false), jobTemplate.merkle_branch);
|
testBlock.merkleRoot = MiningJob.calculateMerkleRootFromCoinbaseHash(
|
||||||
|
testBlock.transactions[0].getHash(false),
|
||||||
|
this.merkleBranchBuffers,
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
testBlock.timestamp = timestamp;
|
testBlock.timestamp = timestamp;
|
||||||
@@ -101,22 +221,6 @@ export class MiningJob {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private calculateMerkleRootHash(newRoot: Buffer, merkleBranches: string[]): Buffer {
|
|
||||||
|
|
||||||
const bothMerkles = Buffer.alloc(64);
|
|
||||||
|
|
||||||
bothMerkles.set(newRoot);
|
|
||||||
|
|
||||||
for (let i = 0; i < merkleBranches.length; i++) {
|
|
||||||
bothMerkles.set(Buffer.from(merkleBranches[i], 'hex'), 32);
|
|
||||||
newRoot = bitcoinjs.crypto.hash256(bothMerkles);
|
|
||||||
bothMerkles.set(newRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return bothMerkles.subarray(0, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private createCoinbaseTransaction(addresses: AddressObject[], reward: number): bitcoinjs.Transaction {
|
private createCoinbaseTransaction(addresses: AddressObject[], reward: number): bitcoinjs.Transaction {
|
||||||
// Part 1
|
// Part 1
|
||||||
const coinbaseTransaction = new bitcoinjs.Transaction();
|
const coinbaseTransaction = new bitcoinjs.Transaction();
|
||||||
@@ -131,7 +235,9 @@ export class MiningJob {
|
|||||||
let rewardBalance = reward;
|
let rewardBalance = reward;
|
||||||
|
|
||||||
addresses.forEach(recipientAddress => {
|
addresses.forEach(recipientAddress => {
|
||||||
const amount = Math.floor((recipientAddress.percent / 100) * reward);
|
const amount = recipientAddress.amountSats == null
|
||||||
|
? Math.floor(((recipientAddress.percent ?? 0) / 100) * reward)
|
||||||
|
: recipientAddress.amountSats;
|
||||||
rewardBalance -= amount;
|
rewardBalance -= amount;
|
||||||
coinbaseTransaction.addOutput(this.getPaymentScript(recipientAddress.address), amount);
|
coinbaseTransaction.addOutput(this.getPaymentScript(recipientAddress.address), amount);
|
||||||
})
|
})
|
||||||
@@ -147,32 +253,76 @@ export class MiningJob {
|
|||||||
return coinbaseTransaction;
|
return coinbaseTransaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private encodeCoinbaseHeight(height: number): Buffer {
|
||||||
|
if (!Number.isSafeInteger(height) || height < 0) {
|
||||||
|
throw new Error('Coinbase height must be a non-negative safe integer');
|
||||||
|
}
|
||||||
|
if (height === 0) {
|
||||||
|
return Buffer.from([bitcoinjs.opcodes.OP_0]);
|
||||||
|
}
|
||||||
|
if (height <= 16) {
|
||||||
|
return Buffer.from([bitcoinjs.opcodes.OP_1 + height - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const encoded = bitcoinjs.script.number.encode(height);
|
||||||
|
if (encoded.length >= bitcoinjs.opcodes.OP_PUSHDATA1) {
|
||||||
|
throw new Error('Coinbase height encoding is unexpectedly large');
|
||||||
|
}
|
||||||
|
return Buffer.concat([Buffer.from([encoded.length]), encoded]);
|
||||||
|
}
|
||||||
|
|
||||||
private getPaymentScript(address: string): Buffer {
|
private getPaymentScript(address: string): Buffer {
|
||||||
|
const cacheKey = `${this.network.bech32}:${this.network.pubKeyHash}:${this.network.scriptHash}:${address}`;
|
||||||
|
const cached = MiningJob.paymentScriptCache.get(cacheKey);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
const addressInfo = getAddressInfo(address);
|
const addressInfo = getAddressInfo(address);
|
||||||
|
let paymentScript: Buffer;
|
||||||
switch (addressInfo.type) {
|
switch (addressInfo.type) {
|
||||||
case AddressType.p2wpkh: {
|
case AddressType.p2wpkh: {
|
||||||
return bitcoinjs.payments.p2wpkh({ address, network: this.network }).output;
|
paymentScript = bitcoinjs.payments.p2wpkh({ address, network: this.network }).output;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
case AddressType.p2pkh: {
|
case AddressType.p2pkh: {
|
||||||
return bitcoinjs.payments.p2pkh({ address, network: this.network }).output;
|
paymentScript = bitcoinjs.payments.p2pkh({ address, network: this.network }).output;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
case AddressType.p2sh: {
|
case AddressType.p2sh: {
|
||||||
return bitcoinjs.payments.p2sh({ address, network: this.network }).output;
|
paymentScript = bitcoinjs.payments.p2sh({ address, network: this.network }).output;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
case AddressType.p2tr: {
|
case AddressType.p2tr: {
|
||||||
return bitcoinjs.payments.p2tr({ address, network: this.network }).output;
|
paymentScript = bitcoinjs.payments.p2tr({ address, network: this.network }).output;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
case AddressType.p2wsh: {
|
case AddressType.p2wsh: {
|
||||||
return bitcoinjs.payments.p2wsh({ address, network: this.network }).output;
|
paymentScript = bitcoinjs.payments.p2wsh({ address, network: this.network }).output;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
return Buffer.alloc(0);
|
paymentScript = Buffer.alloc(0);
|
||||||
}
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
MiningJob.paymentScriptCache.set(cacheKey, paymentScript);
|
||||||
|
if (MiningJob.paymentScriptCache.size > MiningJob.paymentScriptCacheMaxEntries) {
|
||||||
|
const oldest = MiningJob.paymentScriptCache.keys().next().value;
|
||||||
|
if (oldest != null) {
|
||||||
|
MiningJob.paymentScriptCache.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return paymentScript;
|
||||||
|
}
|
||||||
|
|
||||||
public response(jobTemplate: IJobTemplate): string {
|
public response(jobTemplate: IJobTemplate): string {
|
||||||
|
|
||||||
|
if (this.miningNotifyResponse != null) {
|
||||||
|
return this.miningNotifyResponse;
|
||||||
|
}
|
||||||
|
|
||||||
const job: IMiningNotify = {
|
const job: IMiningNotify = {
|
||||||
id: null,
|
id: null,
|
||||||
method: eResponseMethod.MINING_NOTIFY,
|
method: eResponseMethod.MINING_NOTIFY,
|
||||||
@@ -189,7 +339,16 @@ export class MiningJob {
|
|||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
return JSON.stringify(job) + '\n';
|
this.miningNotifyResponse = JSON.stringify(job) + '\n';
|
||||||
|
this.miningNotifyResponseBuffer = Buffer.from(this.miningNotifyResponse);
|
||||||
|
return this.miningNotifyResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
public responseBuffer(jobTemplate: IJobTemplate): Buffer {
|
||||||
|
if (this.miningNotifyResponseBuffer == null) {
|
||||||
|
this.response(jobTemplate);
|
||||||
|
}
|
||||||
|
return this.miningNotifyResponseBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,235 +0,0 @@
|
|||||||
import Big from 'big.js';
|
|
||||||
import { Block } from 'bitcoinjs-lib';
|
|
||||||
import * as bitcoinjs from 'bitcoinjs-lib';
|
|
||||||
import { plainToInstance } from 'class-transformer';
|
|
||||||
import { validate, ValidatorOptions } from 'class-validator';
|
|
||||||
import { Socket } from 'net';
|
|
||||||
|
|
||||||
import { eRequestMethod } from './enums/eRequestMethod';
|
|
||||||
import { eResponseMethod } from './enums/eResponseMethod';
|
|
||||||
import { IMiningNotify } from './stratum-messages/IMiningNotify';
|
|
||||||
import { MiningSubmitMessage } from './stratum-messages/MiningSubmitMessage';
|
|
||||||
|
|
||||||
export class ProxyClient {
|
|
||||||
|
|
||||||
|
|
||||||
public braiinsSocket: Socket;
|
|
||||||
public serverDifficulty: number;
|
|
||||||
public jobs: { [jobId: string]: IMiningNotify } = {};
|
|
||||||
private extraNonce: string;
|
|
||||||
|
|
||||||
constructor(public socket: Socket) {
|
|
||||||
this.braiinsSocket = new Socket();
|
|
||||||
this.braiinsSocket.connect(3333, 'us-east.stratum.braiins.com', () => {
|
|
||||||
console.log('Connected to braiins');
|
|
||||||
});
|
|
||||||
|
|
||||||
this.braiinsSocket.on('data', (data) => {
|
|
||||||
data.toString()
|
|
||||||
.split('\n')
|
|
||||||
.filter(m => m.length > 0)
|
|
||||||
.forEach(async (m) => {
|
|
||||||
try {
|
|
||||||
await this.toClient(m);
|
|
||||||
} catch (e) {
|
|
||||||
await socket.end();
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
this.braiinsSocket.on('close', () => {
|
|
||||||
console.log('Braiins closed connection');
|
|
||||||
socket.end();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
socket.on('error', async (error: Error) => { });
|
|
||||||
|
|
||||||
socket.on('data', (data: Buffer) => {
|
|
||||||
data.toString()
|
|
||||||
.split('\n')
|
|
||||||
.filter(m => m.length > 0)
|
|
||||||
.forEach(async (m) => {
|
|
||||||
try {
|
|
||||||
await this.toServer(m);
|
|
||||||
} catch (e) {
|
|
||||||
await socket.end();
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
socket.on('close', () => {
|
|
||||||
console.log('Client closed connection');
|
|
||||||
this.braiinsSocket.end();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private async toClient(message: string) {
|
|
||||||
let parsedMessage: IMiningNotify | any;
|
|
||||||
try {
|
|
||||||
parsedMessage = JSON.parse(message);
|
|
||||||
} catch (e) {
|
|
||||||
//console.log("Invalid JSON");
|
|
||||||
await this.socket.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsedMessage.method == null && Array.isArray(parsedMessage.result)) {
|
|
||||||
this.extraNonce = parsedMessage.result[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (parsedMessage.method) {
|
|
||||||
case eResponseMethod.SET_DIFFICULTY: {
|
|
||||||
this.serverDifficulty = parsedMessage.params[0];
|
|
||||||
parsedMessage.params[0] = 512;
|
|
||||||
message = JSON.stringify(parsedMessage);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case eResponseMethod.MINING_NOTIFY: {
|
|
||||||
// clear jobs
|
|
||||||
if ((parsedMessage as IMiningNotify).params[8]) {
|
|
||||||
this.jobs = {};
|
|
||||||
}
|
|
||||||
this.jobs[parsedMessage.params[0]] = parsedMessage;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log('Server:');
|
|
||||||
console.log(message);
|
|
||||||
this.socket.write(message + `\n`);
|
|
||||||
}
|
|
||||||
private async toServer(message: string) {
|
|
||||||
|
|
||||||
let parsedMessage = null;
|
|
||||||
try {
|
|
||||||
parsedMessage = JSON.parse(message);
|
|
||||||
} catch (e) {
|
|
||||||
//console.log("Invalid JSON");
|
|
||||||
await this.socket.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (parsedMessage.method) {
|
|
||||||
|
|
||||||
case eRequestMethod.AUTHORIZE: {
|
|
||||||
parsedMessage.params[0] = 'battlechicken';
|
|
||||||
message = JSON.stringify(parsedMessage);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case eRequestMethod.SUBMIT: {
|
|
||||||
parsedMessage.params[0] = 'battlechicken';
|
|
||||||
|
|
||||||
message = JSON.stringify(parsedMessage);
|
|
||||||
|
|
||||||
const miningSubmitMessage = plainToInstance(
|
|
||||||
MiningSubmitMessage,
|
|
||||||
parsedMessage,
|
|
||||||
);
|
|
||||||
|
|
||||||
const validatorOptions: ValidatorOptions = {
|
|
||||||
whitelist: true,
|
|
||||||
forbidNonWhitelisted: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const errors = await validate(miningSubmitMessage, validatorOptions);
|
|
||||||
|
|
||||||
if (errors.length === 0) {
|
|
||||||
this.checkSubmission(miningSubmitMessage);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
console.log('parsing error')
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log('Client:');
|
|
||||||
console.log(message);
|
|
||||||
this.braiinsSocket.write(message + '\n');
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private checkSubmission(submission: MiningSubmitMessage) {
|
|
||||||
console.log('Submission:');
|
|
||||||
console.log(submission);
|
|
||||||
|
|
||||||
const job = this.jobs[submission.jobId];
|
|
||||||
if (job == null) {
|
|
||||||
console.log('Job not found');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const versionMask = parseInt(submission.versionMask, 16);
|
|
||||||
|
|
||||||
const block = new Block();
|
|
||||||
|
|
||||||
block.version = parseInt(job.params[5], 16);
|
|
||||||
if (submission.versionMask !== undefined && versionMask != 0) {
|
|
||||||
block.version = (block.version ^ versionMask);
|
|
||||||
}
|
|
||||||
|
|
||||||
const prevHash = this.swapEndianWords(job.params[1]);
|
|
||||||
block.prevHash = Buffer.from(prevHash, 'hex');
|
|
||||||
const coinbase = Buffer.from(`${job.params[2]}${this.extraNonce}${submission.extraNonce2}${job.params[3]}`, 'hex');
|
|
||||||
const coinbaseHash = bitcoinjs.crypto.hash256(coinbase);
|
|
||||||
block.merkleRoot = this.calculateMerkleRootHash(coinbaseHash, job.params[4]);
|
|
||||||
block.timestamp = parseInt(submission.ntime, 16);
|
|
||||||
block.bits = parseInt(job.params[6], 16);
|
|
||||||
block.nonce = parseInt(submission.nonce, 16);
|
|
||||||
|
|
||||||
const header = block.toBuffer(true);
|
|
||||||
|
|
||||||
const diff = this.calculateDifficulty(header);
|
|
||||||
|
|
||||||
console.log(`DIFFICULTY: ${diff.submissionDifficulty}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private calculateMerkleRootHash(newRoot: Buffer, merkleBranches: string[]): Buffer {
|
|
||||||
|
|
||||||
const bothMerkles = Buffer.alloc(64);
|
|
||||||
|
|
||||||
bothMerkles.set(newRoot);
|
|
||||||
|
|
||||||
for (let i = 0; i < merkleBranches.length; i++) {
|
|
||||||
bothMerkles.set(Buffer.from(merkleBranches[i], 'hex'), 32);
|
|
||||||
newRoot = bitcoinjs.crypto.hash256(bothMerkles);
|
|
||||||
bothMerkles.set(newRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return bothMerkles.subarray(0, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
private calculateDifficulty(header: Buffer): { submissionDifficulty: number, submissionHash: string } {
|
|
||||||
|
|
||||||
const hashResult = bitcoinjs.crypto.hash256(header);
|
|
||||||
|
|
||||||
let s64 = this.le256todouble(hashResult);
|
|
||||||
|
|
||||||
const truediffone = Big('26959535291011309493156476344723991336010898738574164086137773096960');
|
|
||||||
const difficulty = truediffone.div(s64.toString());
|
|
||||||
return { submissionDifficulty: difficulty.toNumber(), submissionHash: hashResult.toString('hex') };
|
|
||||||
}
|
|
||||||
|
|
||||||
private le256todouble(target: Buffer): bigint {
|
|
||||||
|
|
||||||
const number = target.reduceRight((acc, byte) => {
|
|
||||||
// Shift the number 8 bits to the left and OR with the current byte
|
|
||||||
return (acc << BigInt(8)) | BigInt(byte);
|
|
||||||
}, BigInt(0));
|
|
||||||
|
|
||||||
return number;
|
|
||||||
}
|
|
||||||
|
|
||||||
private swapEndianWords(str: string) {
|
|
||||||
const hexGroups = str.match(/.{1,8}/g);
|
|
||||||
// Reverse each group and concatenate them
|
|
||||||
const reversedHexString = hexGroups.reduce((pre, cur, indx, arr) => {
|
|
||||||
const reversed = cur.match(/.{2}/g).reverse();
|
|
||||||
return `${pre}${reversed.join('')}`;
|
|
||||||
}, '');
|
|
||||||
return reversedHexString;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
+771
-215
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
|||||||
|
import { StratumV1ClientStatistics } from './StratumV1ClientStatistics';
|
||||||
|
|
||||||
|
describe('StratumV1ClientStatistics', () => {
|
||||||
|
const client = {
|
||||||
|
id: 'client-id',
|
||||||
|
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
|
||||||
|
clientName: 'bitaxe3',
|
||||||
|
sessionId: '57a6f098'
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
let statistics: StratumV1ClientStatistics;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(new Date('2026-05-06T12:00:00Z'));
|
||||||
|
statistics = new StratumV1ClientStatistics();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should keep runtime hashrate at zero before enough time passes', async () => {
|
||||||
|
await statistics.addShares(client, 64);
|
||||||
|
|
||||||
|
expect(statistics.hashRate).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update runtime hashrate from accepted shares', async () => {
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
jest.setSystemTime(new Date(Date.parse('2026-05-06T12:00:00Z') + (i * 31000)));
|
||||||
|
await statistics.addShares(client, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(statistics.hashRate).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not suggest a difficulty change before enough time or shares have passed', () => {
|
||||||
|
expect(statistics.getSuggestedDifficulty(64)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should lower difficulty when a miner has not submitted shares for several minutes', () => {
|
||||||
|
jest.setSystemTime(new Date('2026-05-06T12:06:00Z'));
|
||||||
|
|
||||||
|
expect(statistics.getSuggestedDifficulty(64)).toBe(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should increase difficulty for rapid submissions', async () => {
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
jest.setSystemTime(new Date(Date.parse('2026-05-06T12:00:00Z') + (i * 1000)));
|
||||||
|
await statistics.addShares(client, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(statistics.getSuggestedDifficulty(64)).toBe(2048);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should decrease difficulty for slow submissions', async () => {
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
jest.setSystemTime(new Date(Date.parse('2026-05-06T12:00:00Z') + (i * 150000)));
|
||||||
|
await statistics.addShares(client, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(statistics.getSuggestedDifficulty(128)).toBe(16);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not suggest a difficulty below the configured minimum', () => {
|
||||||
|
statistics = new StratumV1ClientStatistics(1);
|
||||||
|
jest.setSystemTime(new Date('2026-05-06T12:06:00Z'));
|
||||||
|
|
||||||
|
expect(statistics.getSuggestedDifficulty(1)).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,67 +1,45 @@
|
|||||||
import { ClientStatisticsService } from '../ORM/client-statistics/client-statistics.service';
|
|
||||||
import { ClientEntity } from '../ORM/client/client.entity';
|
import { ClientEntity } from '../ORM/client/client.entity';
|
||||||
|
|
||||||
const CACHE_SIZE = 30;
|
const CACHE_SIZE = 30;
|
||||||
const TARGET_SUBMISSION_PER_SECOND = 10;
|
const DEFAULT_MIN_DIFF = 0.001;
|
||||||
const MIN_DIFF = 0.00001;
|
|
||||||
export class StratumV1ClientStatistics {
|
export class StratumV1ClientStatistics {
|
||||||
|
|
||||||
private shareBacklog: number = 0;
|
public targetSubmitShareEveryNSeconds: number = 30;
|
||||||
|
public hashRate = 0;
|
||||||
|
|
||||||
private submissionCacheStart: Date;
|
private submissionCacheStart: Date;
|
||||||
private submissionCache = [];
|
private submissionCache: { time: Date, difficulty: number }[] = [];
|
||||||
|
private submissionCacheDifficultySum = 0;
|
||||||
|
|
||||||
constructor(
|
constructor(private readonly minDifficulty = DEFAULT_MIN_DIFF) {
|
||||||
private readonly clientStatisticsService: ClientStatisticsService
|
|
||||||
) {
|
|
||||||
this.submissionCacheStart = new Date();
|
this.submissionCacheStart = new Date();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async addShares(_client: ClientEntity, targetDifficulty: number) {
|
||||||
public async saveShares(client: ClientEntity) {
|
|
||||||
|
|
||||||
if (client == null || client.address == null || client.clientName == null || client.sessionId == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 10 min
|
|
||||||
var coeff = 1000 * 60 * 10;
|
|
||||||
var date = new Date();
|
var date = new Date();
|
||||||
var rounded = new Date(Math.floor(date.getTime() / coeff) * coeff);
|
|
||||||
|
|
||||||
await this.clientStatisticsService.save({
|
|
||||||
time: rounded.getTime(),
|
|
||||||
shares: this.shareBacklog,
|
|
||||||
address: client.address,
|
|
||||||
clientName: client.clientName,
|
|
||||||
sessionId: client.sessionId
|
|
||||||
});
|
|
||||||
|
|
||||||
this.shareBacklog = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We don't want to save them here because it can be DB intensive, stead do it every once in
|
|
||||||
// awhile with saveShares()
|
|
||||||
public async addShares(targetDifficulty: number) {
|
|
||||||
|
|
||||||
if (this.submissionCache.length > CACHE_SIZE) {
|
if (this.submissionCache.length > CACHE_SIZE) {
|
||||||
|
this.submissionCacheDifficultySum -= this.submissionCache[0].difficulty;
|
||||||
this.submissionCache.shift();
|
this.submissionCache.shift();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.submissionCache.push({
|
this.submissionCache.push({
|
||||||
time: new Date(),
|
time: date,
|
||||||
difficulty: targetDifficulty,
|
difficulty: targetDifficulty,
|
||||||
});
|
});
|
||||||
|
this.submissionCacheDifficultySum += targetDifficulty;
|
||||||
|
|
||||||
this.shareBacklog += targetDifficulty;
|
const time = new Date().getTime() - this.submissionCache[0].time.getTime();
|
||||||
|
if(time > 60000 && this.submissionCache.length > 2) {
|
||||||
|
this.hashRate = (this.submissionCacheDifficultySum * 4294967296) / (time / 1000);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public getSuggestedDifficulty(clientDifficulty: number) {
|
public getSuggestedDifficulty(clientDifficulty: number) {
|
||||||
|
|
||||||
// miner hasn't submitted shares in one minute
|
// miner hasn't submitted shares in one minute
|
||||||
if (this.submissionCache.length < 5) {
|
if (this.submissionCache.length < 5) {
|
||||||
if ((new Date().getTime() - this.submissionCacheStart.getTime()) / 1000 > 60) {
|
if ((new Date().getTime() - this.submissionCacheStart.getTime()) / 5000 > 60) {
|
||||||
return this.nearestPowerOfTwo(clientDifficulty / 6);
|
return this.nearestPowerOfTwo(clientDifficulty / 6);
|
||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
@@ -76,7 +54,7 @@ export class StratumV1ClientStatistics {
|
|||||||
|
|
||||||
const difficultyPerSecond = sum / diffSeconds;
|
const difficultyPerSecond = sum / diffSeconds;
|
||||||
|
|
||||||
const targetDifficulty = difficultyPerSecond * TARGET_SUBMISSION_PER_SECOND;
|
const targetDifficulty = difficultyPerSecond * this.targetSubmitShareEveryNSeconds;
|
||||||
|
|
||||||
if ((clientDifficulty * 2) < targetDifficulty || (clientDifficulty / 2) > targetDifficulty) {
|
if ((clientDifficulty * 2) < targetDifficulty || (clientDifficulty / 2) > targetDifficulty) {
|
||||||
return this.nearestPowerOfTwo(targetDifficulty)
|
return this.nearestPowerOfTwo(targetDifficulty)
|
||||||
@@ -89,8 +67,8 @@ export class StratumV1ClientStatistics {
|
|||||||
if (val === 0) {
|
if (val === 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (val < MIN_DIFF) {
|
if (val < this.minDifficulty) {
|
||||||
return MIN_DIFF;
|
return this.minDifficulty;
|
||||||
}
|
}
|
||||||
let x = val | (val >> 1);
|
let x = val | (val >> 1);
|
||||||
x = x | (x >> 2);
|
x = x | (x >> 2);
|
||||||
@@ -99,8 +77,8 @@ export class StratumV1ClientStatistics {
|
|||||||
x = x | (x >> 16);
|
x = x | (x >> 16);
|
||||||
x = x | (x >> 32);
|
x = x | (x >> 32);
|
||||||
const res = x - (x >> 1);
|
const res = x - (x >> 1);
|
||||||
if (res == 0 && val * 100 < MIN_DIFF) {
|
if (res == 0 && val * 100 < this.minDifficulty) {
|
||||||
return MIN_DIFF;
|
return this.minDifficulty;
|
||||||
}
|
}
|
||||||
if (res == 0) {
|
if (res == 0) {
|
||||||
return this.nearestPowerOfTwo(val * 100) / 100;
|
return this.nearestPowerOfTwo(val * 100) / 100;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,5 @@
|
|||||||
|
import type { PayoutMode } from '../../types/payout-mode';
|
||||||
|
|
||||||
export interface IBlockTemplateTx {
|
export interface IBlockTemplateTx {
|
||||||
data: string; //'hex', // (string) transaction data encoded in hexadecimal (byte-for-byte)
|
data: string; //'hex', // (string) transaction data encoded in hexadecimal (byte-for-byte)
|
||||||
txid: string; //'hex', // (string) transaction id encoded in little-endian hexadecimal
|
txid: string; //'hex', // (string) transaction id encoded in little-endian hexadecimal
|
||||||
@@ -7,6 +9,13 @@ export interface IBlockTemplateTx {
|
|||||||
sigops: number, // (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero
|
sigops: number, // (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero
|
||||||
weight: number // (numeric) total transaction weight, as counted for purposes of block limits
|
weight: number // (numeric) total transaction weight, as counted for purposes of block limits
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IBlockTemplatePayoutOutput {
|
||||||
|
address: string;
|
||||||
|
percent?: number;
|
||||||
|
amountSats?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface IBlockTemplate {
|
export interface IBlockTemplate {
|
||||||
// (json object)
|
// (json object)
|
||||||
version: number; // (numeric) The preferred block version
|
version: number; // (numeric) The preferred block version
|
||||||
@@ -35,5 +44,20 @@ export interface IBlockTemplate {
|
|||||||
height: number, // (numeric) The height of the next block
|
height: number, // (numeric) The height of the next block
|
||||||
default_witness_commitment: string // (string, optional) a valid witness commitment for the unmodified block template
|
default_witness_commitment: string // (string, optional) a valid witness commitment for the unmodified block template
|
||||||
capabilities: string[]
|
capabilities: string[]
|
||||||
|
payoutSnapshotId?: string;
|
||||||
|
payoutOutputs?: IBlockTemplatePayoutOutput[];
|
||||||
|
/** Force miners to switch even when the previous block hash is unchanged. */
|
||||||
|
forceCleanJobs?: boolean;
|
||||||
|
/** Distinguishes normal fee-paying templates from the subsidy-only bridge. */
|
||||||
|
jobType?: 'full' | 'empty';
|
||||||
|
/** Limits this template to the payout path whose coinbase data is ready. */
|
||||||
|
payoutMode?: PayoutMode | 'all';
|
||||||
|
/** Correlates master detection, Redis delivery, and socket fan-out traces. */
|
||||||
|
notificationEventId?: string;
|
||||||
|
/** Wall-clock time when the master first observed the source block notification. */
|
||||||
|
sourceNotificationReceivedAtMs?: number;
|
||||||
|
notificationPublishedAtMs?: number;
|
||||||
|
/** Timestamp of the rolling PPLNS snapshot seed used by an empty bridge. */
|
||||||
|
payoutBridgeSeedCreatedAtMs?: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
import {
|
||||||
|
DATUM_INITIAL_HEADER_KEY,
|
||||||
|
DATUM_EXTRANONCE_SIZE,
|
||||||
|
DatumFrameReader,
|
||||||
|
DatumMiningCommand,
|
||||||
|
DatumProtocolCommand,
|
||||||
|
DatumShareResponseStatus,
|
||||||
|
datumHeaderXorFeedback,
|
||||||
|
decodeDatumHeader,
|
||||||
|
deserializeDatumCoinbaserFetch,
|
||||||
|
deserializeDatumJobValidationResponse,
|
||||||
|
deserializeDatumMiningCommand,
|
||||||
|
deserializeDatumPowSubmit,
|
||||||
|
encodeDatumFrame,
|
||||||
|
encodeDatumHeader,
|
||||||
|
serializeDatumJobValidationFullTransactionBlobRequest,
|
||||||
|
serializeDatumJobValidationFullTransactionsRequest,
|
||||||
|
serializeDatumJobValidationShortTxIdsRequest,
|
||||||
|
serializeDatumCoinbaserFetchResponse,
|
||||||
|
serializeDatumMiningCommand,
|
||||||
|
serializeDatumShareResponse,
|
||||||
|
} from './datum-codec';
|
||||||
|
|
||||||
|
describe('datum-codec', () => {
|
||||||
|
it('round-trips DATUM packed headers with XOR key', () => {
|
||||||
|
const encoded = encodeDatumHeader({
|
||||||
|
cmdLen: 1234,
|
||||||
|
reserved: 0,
|
||||||
|
isSigned: true,
|
||||||
|
isEncryptedPubkey: false,
|
||||||
|
isEncryptedChannel: true,
|
||||||
|
protoCmd: DatumProtocolCommand.MINING,
|
||||||
|
}, DATUM_INITIAL_HEADER_KEY);
|
||||||
|
|
||||||
|
expect(decodeDatumHeader(encoded, DATUM_INITIAL_HEADER_KEY)).toEqual({
|
||||||
|
cmdLen: 1234,
|
||||||
|
reserved: 0,
|
||||||
|
isSigned: true,
|
||||||
|
isEncryptedPubkey: false,
|
||||||
|
isEncryptedChannel: true,
|
||||||
|
protoCmd: DatumProtocolCommand.MINING,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('matches the DATUM header feedback function for stable inputs', () => {
|
||||||
|
expect(datumHeaderXorFeedback(0).toString(16)).toBe('74a55cf6');
|
||||||
|
expect(datumHeaderXorFeedback(0xdc871829).toString(16)).toBe('88e1697d');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('splits framed DATUM payloads', () => {
|
||||||
|
const first = encodeDatumFrame({
|
||||||
|
header: {
|
||||||
|
cmdLen: 0,
|
||||||
|
reserved: 0,
|
||||||
|
isSigned: false,
|
||||||
|
isEncryptedPubkey: false,
|
||||||
|
isEncryptedChannel: true,
|
||||||
|
protoCmd: DatumProtocolCommand.MINING,
|
||||||
|
},
|
||||||
|
payload: serializeDatumMiningCommand(DatumMiningCommand.TEMPLATE_REFRESH),
|
||||||
|
});
|
||||||
|
const second = encodeDatumFrame({
|
||||||
|
header: {
|
||||||
|
cmdLen: 0,
|
||||||
|
reserved: 0,
|
||||||
|
isSigned: false,
|
||||||
|
isEncryptedPubkey: false,
|
||||||
|
isEncryptedChannel: true,
|
||||||
|
protoCmd: DatumProtocolCommand.MINING,
|
||||||
|
},
|
||||||
|
payload: serializeDatumMiningCommand(DatumMiningCommand.FETCH_COINBASER, Buffer.alloc(8)),
|
||||||
|
}, datumHeaderXorFeedback(DATUM_INITIAL_HEADER_KEY));
|
||||||
|
|
||||||
|
const frames = new DatumFrameReader().feed(Buffer.concat([first, second]));
|
||||||
|
expect(frames).toHaveLength(2);
|
||||||
|
expect(deserializeDatumMiningCommand(frames[0].payload).command).toBe(DatumMiningCommand.TEMPLATE_REFRESH);
|
||||||
|
expect(deserializeDatumMiningCommand(frames[1].payload).command).toBe(DatumMiningCommand.FETCH_COINBASER);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes coinbaser fetch responses', () => {
|
||||||
|
const response = serializeDatumCoinbaserFetchResponse(50n, [
|
||||||
|
{ value: 50n, scriptPubKey: Buffer.from('6a', 'hex') },
|
||||||
|
], 7);
|
||||||
|
const mining = deserializeDatumMiningCommand(response);
|
||||||
|
expect(mining.command).toBe(DatumMiningCommand.FETCH_COINBASER_RESPONSE);
|
||||||
|
expect(mining.body.readBigUInt64LE(0)).toBe(50n);
|
||||||
|
expect(mining.body.readUInt32LE(8)).toBe(11);
|
||||||
|
expect(mining.body[12]).toBe(7);
|
||||||
|
expect(mining.body.readBigUInt64LE(13)).toBe(50n);
|
||||||
|
expect(mining.body[21]).toBe(1);
|
||||||
|
expect(mining.body.subarray(22).toString('hex')).toBe('6a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deserializes coinbaser fetch requests', () => {
|
||||||
|
const payload = Buffer.alloc(8);
|
||||||
|
payload.writeBigUInt64LE(123n, 0);
|
||||||
|
expect(deserializeDatumCoinbaserFetch(payload)).toEqual({ rewardValue: 123n });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deserializes fixed DATUM POW submissions', () => {
|
||||||
|
const username = Buffer.from('bc1ptest.worker\0', 'utf8');
|
||||||
|
const extranonce = Buffer.from('000102030405060708090a0b', 'hex');
|
||||||
|
const payload = Buffer.alloc(17 + DATUM_EXTRANONCE_SIZE);
|
||||||
|
payload[0] = 7;
|
||||||
|
payload[1] = 1;
|
||||||
|
payload[2] = 0x01;
|
||||||
|
payload[3] = 4;
|
||||||
|
payload.writeUInt32LE(100, 4);
|
||||||
|
payload.writeUInt32LE(200, 8);
|
||||||
|
payload.writeUInt32LE(0x20000000, 12);
|
||||||
|
payload[16] = DATUM_EXTRANONCE_SIZE;
|
||||||
|
extranonce.copy(payload, 17);
|
||||||
|
const parsed = deserializeDatumPowSubmit(Buffer.concat([
|
||||||
|
payload,
|
||||||
|
username,
|
||||||
|
Buffer.alloc(4),
|
||||||
|
Buffer.from([0xfe]),
|
||||||
|
]));
|
||||||
|
|
||||||
|
expect(parsed.jobId).toBe(7);
|
||||||
|
expect(parsed.coinbaseId).toBe(1);
|
||||||
|
expect(parsed.isBlock).toBe(true);
|
||||||
|
expect(parsed.extranonce).toEqual(extranonce);
|
||||||
|
expect(parsed.username).toBe('bc1ptest.worker');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deserializes cached DATUM POW context sections', () => {
|
||||||
|
const username = Buffer.from('bc1ptest.worker\0', 'utf8');
|
||||||
|
const extranonce = Buffer.from('000102030405060708090a0b', 'hex');
|
||||||
|
const base = Buffer.alloc(17 + DATUM_EXTRANONCE_SIZE);
|
||||||
|
base[0] = 3;
|
||||||
|
base[1] = 2;
|
||||||
|
base[2] = 0;
|
||||||
|
base[3] = 0x12;
|
||||||
|
base.writeUInt32LE(100, 4);
|
||||||
|
base.writeUInt32LE(200, 8);
|
||||||
|
base.writeUInt32LE(0x20000000, 12);
|
||||||
|
base[16] = DATUM_EXTRANONCE_SIZE;
|
||||||
|
extranonce.copy(base, 17);
|
||||||
|
|
||||||
|
const templateSection = Buffer.concat([
|
||||||
|
Buffer.from([0x01]),
|
||||||
|
Buffer.alloc(32, 0xaa),
|
||||||
|
Buffer.from([0x09, 0x00]),
|
||||||
|
Buffer.from('ffff7f20', 'hex'),
|
||||||
|
Buffer.from([7]),
|
||||||
|
Buffer.from('64000000', 'hex'),
|
||||||
|
Buffer.from('0100000000000000', 'hex'),
|
||||||
|
Buffer.from('02000000', 'hex'),
|
||||||
|
Buffer.from('03000000', 'hex'),
|
||||||
|
Buffer.from('04000000', 'hex'),
|
||||||
|
Buffer.from('05000000', 'hex'),
|
||||||
|
Buffer.from([1]),
|
||||||
|
Buffer.alloc(32, 0xbb),
|
||||||
|
]);
|
||||||
|
const coinbaseSection = Buffer.concat([
|
||||||
|
Buffer.from([0x02, 2]),
|
||||||
|
Buffer.from([0x02, 0x00]),
|
||||||
|
Buffer.from([0x03, 0x00]),
|
||||||
|
Buffer.from('abcd', 'hex'),
|
||||||
|
Buffer.from('010203', 'hex'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const parsed = deserializeDatumPowSubmit(Buffer.concat([
|
||||||
|
base,
|
||||||
|
username,
|
||||||
|
Buffer.alloc(4),
|
||||||
|
templateSection,
|
||||||
|
coinbaseSection,
|
||||||
|
Buffer.from([0xfe]),
|
||||||
|
]));
|
||||||
|
|
||||||
|
expect(parsed.jobId).toBe(3);
|
||||||
|
expect(parsed.coinbaseId).toBe(2);
|
||||||
|
expect(parsed.targetByte).toBe(0x12);
|
||||||
|
expect(parsed.prevBlockHash?.equals(Buffer.alloc(32, 0xaa))).toBe(true);
|
||||||
|
expect(parsed.targetByteIndex).toBe(9);
|
||||||
|
expect(parsed.nBits?.toString('hex')).toBe('ffff7f20');
|
||||||
|
expect(parsed.height).toBe(100);
|
||||||
|
expect(parsed.merkleBranches?.[0].equals(Buffer.alloc(32, 0xbb))).toBe(true);
|
||||||
|
expect(parsed.coinbasePairs.get(2)?.coinb1.toString('hex')).toBe('abcd');
|
||||||
|
expect(parsed.coinbasePairs.get(2)?.coinb2.toString('hex')).toBe('010203');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('classifies DATUM coinbase sections by section type, not the top-level coinbase id', () => {
|
||||||
|
const username = Buffer.from('bc1ptest.worker\0', 'utf8');
|
||||||
|
const extranonce = Buffer.from('000102030405060708090a0b', 'hex');
|
||||||
|
const base = Buffer.alloc(17 + DATUM_EXTRANONCE_SIZE);
|
||||||
|
base[0] = 3;
|
||||||
|
base[1] = 0xff;
|
||||||
|
base[2] = 0x02;
|
||||||
|
base[3] = 0x12;
|
||||||
|
base.writeUInt32LE(100, 4);
|
||||||
|
base.writeUInt32LE(200, 8);
|
||||||
|
base.writeUInt32LE(0x20000000, 12);
|
||||||
|
base[16] = DATUM_EXTRANONCE_SIZE;
|
||||||
|
extranonce.copy(base, 17);
|
||||||
|
|
||||||
|
const coinbaseSection = Buffer.concat([
|
||||||
|
Buffer.from([0x02, 2]),
|
||||||
|
Buffer.from([0x02, 0x00]),
|
||||||
|
Buffer.from([0x03, 0x00]),
|
||||||
|
Buffer.from('abcd', 'hex'),
|
||||||
|
Buffer.from('010203', 'hex'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const parsed = deserializeDatumPowSubmit(Buffer.concat([
|
||||||
|
base,
|
||||||
|
username,
|
||||||
|
Buffer.alloc(4),
|
||||||
|
coinbaseSection,
|
||||||
|
Buffer.from([0xfe]),
|
||||||
|
]));
|
||||||
|
|
||||||
|
expect(parsed.subsidyOnly).toBe(true);
|
||||||
|
expect(parsed.subsidyOnlyCoinbase).toBeUndefined();
|
||||||
|
expect(parsed.coinbasePairs.get(2)?.coinb1.toString('hex')).toBe('abcd');
|
||||||
|
expect(parsed.coinbasePairs.get(2)?.coinb2.toString('hex')).toBe('010203');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects DATUM POW submissions with non-standard extranonce sizes', () => {
|
||||||
|
const payload = Buffer.alloc(18);
|
||||||
|
payload[16] = 1;
|
||||||
|
payload[17] = 0xaa;
|
||||||
|
|
||||||
|
expect(() => deserializeDatumPowSubmit(payload)).toThrow('Unsupported DATUM extranonce size 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes share responses', () => {
|
||||||
|
const response = serializeDatumShareResponse({
|
||||||
|
status: DatumShareResponseStatus.ACCEPTED,
|
||||||
|
reasonCode: 0,
|
||||||
|
nonce: 123,
|
||||||
|
targetByte: 4,
|
||||||
|
jobId: 7,
|
||||||
|
});
|
||||||
|
expect(response.toString('hex')).toBe('8f5000007b0000000407');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes DATUM job validation requests', () => {
|
||||||
|
expect(serializeDatumJobValidationShortTxIdsRequest(7).toString('hex')).toBe('501007');
|
||||||
|
expect(serializeDatumJobValidationFullTransactionBlobRequest(7).toString('hex')).toBe('501207');
|
||||||
|
expect(serializeDatumJobValidationFullTransactionsRequest(7, [1, 258]).toString('hex')).toBe('501107020001000201');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deserializes DATUM short transaction ID validation responses', () => {
|
||||||
|
const payload = Buffer.concat([
|
||||||
|
Buffer.from([0x90, 7, 0x01]),
|
||||||
|
Buffer.from('0200', 'hex'),
|
||||||
|
Buffer.from('010203040506', 'hex'),
|
||||||
|
Buffer.from('111213141516', 'hex'),
|
||||||
|
Buffer.alloc(32, 0xaa),
|
||||||
|
Buffer.from([0xfe, 0x00, 0x00]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const parsed = deserializeDatumJobValidationResponse(payload);
|
||||||
|
expect(parsed.kind).toBe('short-txids');
|
||||||
|
expect(parsed.jobId).toBe(7);
|
||||||
|
expect(parsed.status).toBe(1);
|
||||||
|
expect(parsed.transactionCount).toBe(2);
|
||||||
|
if (parsed.kind !== 'short-txids') {
|
||||||
|
throw new Error(`Unexpected DATUM validation response kind ${parsed.kind}`);
|
||||||
|
}
|
||||||
|
expect(parsed.shortTxIds.map(id => id.toString('hex'))).toEqual(['010203040506', '111213141516']);
|
||||||
|
expect(parsed.crosscheck?.equals(Buffer.alloc(32, 0xaa))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deserializes DATUM full transaction blob validation responses', () => {
|
||||||
|
const tx = Buffer.from(
|
||||||
|
'0100000001'
|
||||||
|
+ '0000000000000000000000000000000000000000000000000000000000000000'
|
||||||
|
+ 'ffffffff00ffffffff'
|
||||||
|
+ '01000000000000000000'
|
||||||
|
+ '00000000',
|
||||||
|
'hex',
|
||||||
|
);
|
||||||
|
const txSize = Buffer.alloc(3);
|
||||||
|
txSize.writeUIntLE(tx.length, 0, 3);
|
||||||
|
const payload = Buffer.concat([
|
||||||
|
Buffer.from([0x92, 9, 0x01]),
|
||||||
|
Buffer.from('0100', 'hex'),
|
||||||
|
txSize,
|
||||||
|
tx,
|
||||||
|
Buffer.from([0xfe]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const parsed = deserializeDatumJobValidationResponse(payload);
|
||||||
|
expect(parsed.kind).toBe('full-transaction-blob');
|
||||||
|
expect(parsed.jobId).toBe(9);
|
||||||
|
expect(parsed.status).toBe(1);
|
||||||
|
expect(parsed.transactionCount).toBe(1);
|
||||||
|
if (parsed.kind !== 'full-transaction-blob') {
|
||||||
|
throw new Error(`Unexpected DATUM validation response kind ${parsed.kind}`);
|
||||||
|
}
|
||||||
|
expect(parsed.transactions[0]).toEqual(tx);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,506 @@
|
|||||||
|
import { BufferReader, BufferWriter } from '../sv2/sv2-binary-codec';
|
||||||
|
|
||||||
|
export const DATUM_PROTOCOL_VERSION = 'v0.4.1-beta';
|
||||||
|
export const DATUM_INITIAL_HEADER_KEY = 0xdc871829;
|
||||||
|
export const DATUM_MAX_PAYLOAD_SIZE = 4194304;
|
||||||
|
export const DATUM_MAX_JOBS = 8;
|
||||||
|
export const DATUM_EXTRANONCE_SIZE = 12;
|
||||||
|
|
||||||
|
export enum DatumProtocolCommand {
|
||||||
|
PING = 0x01,
|
||||||
|
HANDSHAKE_INIT = 0x01,
|
||||||
|
HANDSHAKE_RESPONSE = 0x02,
|
||||||
|
MINING = 0x05,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum DatumMiningCommand {
|
||||||
|
FETCH_COINBASER = 0x10,
|
||||||
|
FETCH_COINBASER_RESPONSE = 0x11,
|
||||||
|
SUBMIT_POW = 0x27,
|
||||||
|
JOB_VALIDATION = 0x50,
|
||||||
|
SHARE_RESPONSE = 0x8f,
|
||||||
|
CLIENT_CONFIGURE = 0x99,
|
||||||
|
TEMPLATE_REFRESH = 0xf9,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum DatumJobValidationCommand {
|
||||||
|
REQUEST_SHORT_TX_IDS = 0x10,
|
||||||
|
REQUEST_FULL_TRANSACTIONS = 0x11,
|
||||||
|
REQUEST_FULL_TRANSACTION_BLOB = 0x12,
|
||||||
|
SHORT_TX_IDS_RESPONSE = 0x90,
|
||||||
|
FULL_TRANSACTIONS_RESPONSE = 0x91,
|
||||||
|
FULL_TRANSACTION_BLOB_RESPONSE = 0x92,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum DatumJobValidationStatus {
|
||||||
|
SUCCESS = 0x01,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum DatumShareResponseStatus {
|
||||||
|
ACCEPTED = 0x50,
|
||||||
|
ACCEPTED_TENTATIVE = 0x55,
|
||||||
|
REJECTED = 0x66,
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum DatumRejectReason {
|
||||||
|
BAD_JOB_ID = 10,
|
||||||
|
BAD_COINBASE_ID = 11,
|
||||||
|
BAD_EXTRANONCE_SIZE = 12,
|
||||||
|
BAD_TARGET = 13,
|
||||||
|
BAD_USERNAME = 14,
|
||||||
|
BAD_COINBASER_ID = 15,
|
||||||
|
BAD_MERKLE_COUNT = 16,
|
||||||
|
BAD_COINBASE_TOO_LARGE = 17,
|
||||||
|
COINBASE_MISSING = 18,
|
||||||
|
TARGET_MISMATCH = 19,
|
||||||
|
HIGH_HASH = 21,
|
||||||
|
BAD_NTIME = 23,
|
||||||
|
BAD_VERSION = 24,
|
||||||
|
STALE_BLOCK = 25,
|
||||||
|
DUPLICATE_WORK = 29,
|
||||||
|
OTHER = 30,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumHeader {
|
||||||
|
cmdLen: number;
|
||||||
|
reserved: number;
|
||||||
|
isSigned: boolean;
|
||||||
|
isEncryptedPubkey: boolean;
|
||||||
|
isEncryptedChannel: boolean;
|
||||||
|
protoCmd: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumFrame {
|
||||||
|
header: DatumHeader;
|
||||||
|
payload: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumCoinbaserFetch {
|
||||||
|
rewardValue: bigint;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumPayoutOutput {
|
||||||
|
value: bigint;
|
||||||
|
scriptPubKey: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumPowSubmit {
|
||||||
|
jobId: number;
|
||||||
|
coinbaseId: number;
|
||||||
|
isBlock: boolean;
|
||||||
|
subsidyOnly: boolean;
|
||||||
|
quickDiff: boolean;
|
||||||
|
targetByte: number;
|
||||||
|
ntime: number;
|
||||||
|
nonce: number;
|
||||||
|
version: number;
|
||||||
|
extranonce: Buffer;
|
||||||
|
username: string;
|
||||||
|
reserved: Buffer;
|
||||||
|
prevBlockHash?: Buffer;
|
||||||
|
targetByteIndex?: number;
|
||||||
|
nBits?: Buffer;
|
||||||
|
coinbaserId?: number;
|
||||||
|
height?: number;
|
||||||
|
coinbaseValue?: bigint;
|
||||||
|
transactionCount?: number;
|
||||||
|
totalWeight?: number;
|
||||||
|
totalSize?: number;
|
||||||
|
totalSigops?: number;
|
||||||
|
merkleBranches?: Buffer[];
|
||||||
|
coinbasePairs: Map<number, { coinb1: Buffer; coinb2: Buffer }>;
|
||||||
|
subsidyOnlyCoinbase?: { coinb1: Buffer; coinb2: Buffer };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumShortTxIdsResponse {
|
||||||
|
kind: 'short-txids';
|
||||||
|
jobId: number;
|
||||||
|
status: number;
|
||||||
|
transactionCount: number;
|
||||||
|
shortTxIds: Buffer[];
|
||||||
|
crosscheck: Buffer | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumFullTransactionsResponse {
|
||||||
|
kind: 'full-transactions';
|
||||||
|
jobId: number;
|
||||||
|
status: number;
|
||||||
|
transactionCount: number;
|
||||||
|
transactions: Buffer[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatumFullTransactionBlobResponse {
|
||||||
|
kind: 'full-transaction-blob';
|
||||||
|
jobId: number;
|
||||||
|
status: number;
|
||||||
|
transactionCount: number;
|
||||||
|
transactions: Buffer[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DatumJobValidationResponse =
|
||||||
|
| DatumShortTxIdsResponse
|
||||||
|
| DatumFullTransactionsResponse
|
||||||
|
| DatumFullTransactionBlobResponse;
|
||||||
|
|
||||||
|
export function encodeDatumHeader(header: DatumHeader, xorKey = 0): Buffer {
|
||||||
|
if (header.cmdLen < 0 || header.cmdLen > DATUM_MAX_PAYLOAD_SIZE - 1) {
|
||||||
|
throw new RangeError(`DATUM payload length ${header.cmdLen} exceeds protocol limit`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let raw = header.cmdLen & 0x3fffff;
|
||||||
|
raw |= (header.reserved & 0x03) << 22;
|
||||||
|
raw |= (header.isSigned ? 1 : 0) << 24;
|
||||||
|
raw |= (header.isEncryptedPubkey ? 1 : 0) << 25;
|
||||||
|
raw |= (header.isEncryptedChannel ? 1 : 0) << 26;
|
||||||
|
raw |= (header.protoCmd & 0x1f) << 27;
|
||||||
|
|
||||||
|
const out = Buffer.alloc(4);
|
||||||
|
out.writeUInt32LE((raw ^ xorKey) >>> 0, 0);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeDatumHeader(input: Buffer, xorKey = 0): DatumHeader {
|
||||||
|
if (input.length < 4) {
|
||||||
|
throw new RangeError('DATUM header requires 4 bytes');
|
||||||
|
}
|
||||||
|
const raw = (input.readUInt32LE(0) ^ xorKey) >>> 0;
|
||||||
|
return {
|
||||||
|
cmdLen: raw & 0x3fffff,
|
||||||
|
reserved: (raw >>> 22) & 0x03,
|
||||||
|
isSigned: ((raw >>> 24) & 0x01) !== 0,
|
||||||
|
isEncryptedPubkey: ((raw >>> 25) & 0x01) !== 0,
|
||||||
|
isEncryptedChannel: ((raw >>> 26) & 0x01) !== 0,
|
||||||
|
protoCmd: (raw >>> 27) & 0x1f,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function datumHeaderXorFeedback(input: number): number {
|
||||||
|
let h = 0xb10cfeed >>> 0;
|
||||||
|
let k = input >>> 0;
|
||||||
|
k = Math.imul(k, 0xcc9e2d51) >>> 0;
|
||||||
|
k = (((k << 15) >>> 0) | (k >>> 17)) >>> 0;
|
||||||
|
k = Math.imul(k, 0x1b873593) >>> 0;
|
||||||
|
h = (h ^ k) >>> 0;
|
||||||
|
h = (((h << 13) >>> 0) | (h >>> 19)) >>> 0;
|
||||||
|
h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;
|
||||||
|
h = (h ^ 4) >>> 0;
|
||||||
|
h = (h ^ (h >>> 16)) >>> 0;
|
||||||
|
h = Math.imul(h, 0x85ebca6b) >>> 0;
|
||||||
|
h = (h ^ (h >>> 13)) >>> 0;
|
||||||
|
h = Math.imul(h, 0xc2b2ae35) >>> 0;
|
||||||
|
h = (h ^ (h >>> 16)) >>> 0;
|
||||||
|
return h >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DatumFrameReader {
|
||||||
|
private buffer = Buffer.alloc(0);
|
||||||
|
|
||||||
|
constructor(private headerXorKey = DATUM_INITIAL_HEADER_KEY) {}
|
||||||
|
|
||||||
|
public setHeaderXorKey(headerXorKey: number): void {
|
||||||
|
this.headerXorKey = headerXorKey >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public feed(data: Buffer): DatumFrame[] {
|
||||||
|
this.buffer = Buffer.concat([this.buffer, data]);
|
||||||
|
const frames: DatumFrame[] = [];
|
||||||
|
|
||||||
|
while (this.buffer.length >= 4) {
|
||||||
|
const header = decodeDatumHeader(this.buffer.subarray(0, 4), this.headerXorKey);
|
||||||
|
if (header.cmdLen > DATUM_MAX_PAYLOAD_SIZE) {
|
||||||
|
throw new RangeError(`DATUM payload length ${header.cmdLen} exceeds protocol limit`);
|
||||||
|
}
|
||||||
|
if (this.buffer.length < 4 + header.cmdLen) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
frames.push({
|
||||||
|
header,
|
||||||
|
payload: Buffer.from(this.buffer.subarray(4, 4 + header.cmdLen)),
|
||||||
|
});
|
||||||
|
this.buffer = this.buffer.subarray(4 + header.cmdLen);
|
||||||
|
if (header.isEncryptedChannel) {
|
||||||
|
this.headerXorKey = datumHeaderXorFeedback(this.headerXorKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeDatumFrame(frame: DatumFrame, xorKey = DATUM_INITIAL_HEADER_KEY): Buffer {
|
||||||
|
return Buffer.concat([
|
||||||
|
encodeDatumHeader({ ...frame.header, cmdLen: frame.payload.length }, xorKey),
|
||||||
|
frame.payload,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deserializeDatumMiningCommand(payload: Buffer): { command: DatumMiningCommand; body: Buffer } {
|
||||||
|
if (payload.length < 1) {
|
||||||
|
throw new RangeError('DATUM mining command requires a sub-command byte');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
command: payload[0],
|
||||||
|
body: Buffer.from(payload.subarray(1)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumMiningCommand(command: DatumMiningCommand, body = Buffer.alloc(0)): Buffer {
|
||||||
|
return Buffer.concat([Buffer.from([command]), body]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumJobValidationShortTxIdsRequest(jobId: number): Buffer {
|
||||||
|
return serializeDatumMiningCommand(DatumMiningCommand.JOB_VALIDATION, Buffer.from([
|
||||||
|
DatumJobValidationCommand.REQUEST_SHORT_TX_IDS,
|
||||||
|
jobId & 0xff,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumJobValidationFullTransactionBlobRequest(jobId: number): Buffer {
|
||||||
|
return serializeDatumMiningCommand(DatumMiningCommand.JOB_VALIDATION, Buffer.from([
|
||||||
|
DatumJobValidationCommand.REQUEST_FULL_TRANSACTION_BLOB,
|
||||||
|
jobId & 0xff,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumJobValidationFullTransactionsRequest(jobId: number, transactionIndexes: number[]): Buffer {
|
||||||
|
if (transactionIndexes.length > 0xffff) {
|
||||||
|
throw new RangeError('DATUM requested transaction index count must fit in u16');
|
||||||
|
}
|
||||||
|
const w = new BufferWriter();
|
||||||
|
w.writeU8(DatumJobValidationCommand.REQUEST_FULL_TRANSACTIONS);
|
||||||
|
w.writeU8(jobId);
|
||||||
|
w.writeU16(transactionIndexes.length);
|
||||||
|
for (const index of transactionIndexes) {
|
||||||
|
if (!Number.isInteger(index) || index < 0 || index > 0xffff) {
|
||||||
|
throw new RangeError(`Invalid DATUM transaction index ${index}`);
|
||||||
|
}
|
||||||
|
w.writeU16(index);
|
||||||
|
}
|
||||||
|
return serializeDatumMiningCommand(DatumMiningCommand.JOB_VALIDATION, Buffer.from(w.toBuffer()));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deserializeDatumJobValidationResponse(payload: Buffer): DatumJobValidationResponse {
|
||||||
|
const reader = new BufferReader(payload);
|
||||||
|
const responseCommand = reader.readU8();
|
||||||
|
const jobId = reader.readU8();
|
||||||
|
const status = reader.readU8();
|
||||||
|
|
||||||
|
if (responseCommand === DatumJobValidationCommand.SHORT_TX_IDS_RESPONSE) {
|
||||||
|
if (status !== DatumJobValidationStatus.SUCCESS) {
|
||||||
|
return {
|
||||||
|
kind: 'short-txids',
|
||||||
|
jobId,
|
||||||
|
status,
|
||||||
|
transactionCount: 0,
|
||||||
|
shortTxIds: [],
|
||||||
|
crosscheck: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const transactionCount = reader.readU16();
|
||||||
|
const shortTxIds: Buffer[] = [];
|
||||||
|
for (let i = 0; i < transactionCount; i++) {
|
||||||
|
shortTxIds.push(reader.readBytes(6));
|
||||||
|
}
|
||||||
|
const crosscheck = reader.remaining >= 32 ? reader.readBytes(32) : null;
|
||||||
|
consumeDatumTerminatorAndPadding(reader);
|
||||||
|
return {
|
||||||
|
kind: 'short-txids',
|
||||||
|
jobId,
|
||||||
|
status,
|
||||||
|
transactionCount,
|
||||||
|
shortTxIds,
|
||||||
|
crosscheck,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseCommand === DatumJobValidationCommand.FULL_TRANSACTIONS_RESPONSE) {
|
||||||
|
return deserializeDatumTransactionListResponse('full-transactions', reader, jobId, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseCommand === DatumJobValidationCommand.FULL_TRANSACTION_BLOB_RESPONSE) {
|
||||||
|
return deserializeDatumTransactionListResponse('full-transaction-blob', reader, jobId, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new RangeError(`Unsupported DATUM job validation response 0x${responseCommand.toString(16)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deserializeDatumCoinbaserFetch(payload: Buffer): DatumCoinbaserFetch {
|
||||||
|
if (payload.length < 8) {
|
||||||
|
throw new RangeError('DATUM coinbaser fetch requires reward value');
|
||||||
|
}
|
||||||
|
return { rewardValue: payload.readBigUInt64LE(0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumCoinbaserFetchResponse(rewardValue: bigint, outputs: DatumPayoutOutput[], coinbaserId = 1): Buffer {
|
||||||
|
const w = new BufferWriter();
|
||||||
|
w.writeU64(rewardValue);
|
||||||
|
const outputsBuffer = serializeDatumPayoutOutputs(outputs, coinbaserId);
|
||||||
|
w.writeU32(outputsBuffer.length);
|
||||||
|
w.writeBytes(outputsBuffer);
|
||||||
|
return serializeDatumMiningCommand(DatumMiningCommand.FETCH_COINBASER_RESPONSE, Buffer.from(w.toBuffer()));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumPayoutOutputs(outputs: DatumPayoutOutput[], coinbaserId = 1): Buffer {
|
||||||
|
if (!Number.isInteger(coinbaserId) || coinbaserId < 0 || coinbaserId > 255) {
|
||||||
|
throw new RangeError('DATUM coinbaser id must fit in one byte');
|
||||||
|
}
|
||||||
|
const w = new BufferWriter();
|
||||||
|
w.writeU8(coinbaserId);
|
||||||
|
for (const output of outputs) {
|
||||||
|
if (output.scriptPubKey.length > 255) {
|
||||||
|
throw new RangeError('DATUM scriptPubKey length must fit in one byte');
|
||||||
|
}
|
||||||
|
w.writeU64(output.value);
|
||||||
|
w.writeU8(output.scriptPubKey.length);
|
||||||
|
w.writeBytes(output.scriptPubKey);
|
||||||
|
}
|
||||||
|
return w.toBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deserializeDatumPowSubmit(payload: Buffer): DatumPowSubmit {
|
||||||
|
const reader = new BufferReader(payload);
|
||||||
|
const jobId = reader.readU8();
|
||||||
|
const coinbaseId = reader.readU8();
|
||||||
|
const flags = reader.readU8();
|
||||||
|
const targetByte = reader.readU8();
|
||||||
|
const ntime = reader.readU32();
|
||||||
|
const nonce = reader.readU32();
|
||||||
|
const version = reader.readU32();
|
||||||
|
const extranonceSize = reader.readU8();
|
||||||
|
if (extranonceSize !== DATUM_EXTRANONCE_SIZE) {
|
||||||
|
throw new RangeError(`Unsupported DATUM extranonce size ${extranonceSize}`);
|
||||||
|
}
|
||||||
|
const extranonce = reader.readBytes(extranonceSize);
|
||||||
|
const username = readNullTerminatedString(reader);
|
||||||
|
const reserved = reader.readBytes(Math.min(4, reader.remaining));
|
||||||
|
const coinbasePairs = new Map<number, { coinb1: Buffer; coinb2: Buffer }>();
|
||||||
|
const result: DatumPowSubmit = {
|
||||||
|
jobId,
|
||||||
|
coinbaseId,
|
||||||
|
isBlock: (flags & 0x01) !== 0,
|
||||||
|
subsidyOnly: (flags & 0x02) !== 0,
|
||||||
|
quickDiff: (flags & 0x04) !== 0,
|
||||||
|
targetByte,
|
||||||
|
ntime,
|
||||||
|
nonce,
|
||||||
|
version,
|
||||||
|
extranonce,
|
||||||
|
username,
|
||||||
|
reserved,
|
||||||
|
coinbasePairs,
|
||||||
|
};
|
||||||
|
|
||||||
|
while (reader.remaining > 0) {
|
||||||
|
const section = reader.readU8();
|
||||||
|
if (section === 0xfe) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (section === 0x01) {
|
||||||
|
result.prevBlockHash = reader.readBytes(32);
|
||||||
|
result.targetByteIndex = reader.readU16();
|
||||||
|
result.nBits = reader.readBytes(4);
|
||||||
|
result.coinbaserId = reader.readU8();
|
||||||
|
result.height = reader.readU32();
|
||||||
|
result.coinbaseValue = reader.readU64();
|
||||||
|
result.transactionCount = reader.readU32();
|
||||||
|
result.totalWeight = reader.readU32();
|
||||||
|
result.totalSize = reader.readU32();
|
||||||
|
result.totalSigops = reader.readU32();
|
||||||
|
const merkleBranchCount = reader.readU8();
|
||||||
|
result.merkleBranches = [];
|
||||||
|
for (let i = 0; i < merkleBranchCount; i++) {
|
||||||
|
result.merkleBranches.push(reader.readBytes(32));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (section === 0x02) {
|
||||||
|
const coinbaseType = reader.readU8();
|
||||||
|
const coinb1Len = reader.readU16();
|
||||||
|
const coinb2Len = reader.readU16();
|
||||||
|
const coinbase = {
|
||||||
|
coinb1: reader.readBytes(coinb1Len),
|
||||||
|
coinb2: reader.readBytes(coinb2Len),
|
||||||
|
};
|
||||||
|
if (coinbaseType === 255) {
|
||||||
|
result.subsidyOnlyCoinbase = coinbase;
|
||||||
|
} else {
|
||||||
|
coinbasePairs.set(coinbaseType, coinbase);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw new RangeError(`Unsupported DATUM POW section 0x${section.toString(16)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeDatumShareResponse(input: {
|
||||||
|
status: DatumShareResponseStatus;
|
||||||
|
reasonCode: number;
|
||||||
|
nonce: number;
|
||||||
|
targetByte: number;
|
||||||
|
jobId: number;
|
||||||
|
}): Buffer {
|
||||||
|
const w = new BufferWriter();
|
||||||
|
w.writeU8(input.status);
|
||||||
|
w.writeU16(input.reasonCode);
|
||||||
|
w.writeU32(input.nonce);
|
||||||
|
w.writeU8(input.targetByte);
|
||||||
|
w.writeU8(input.jobId);
|
||||||
|
return serializeDatumMiningCommand(DatumMiningCommand.SHARE_RESPONSE, Buffer.from(w.toBuffer()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function deserializeDatumTransactionListResponse(
|
||||||
|
kind: 'full-transactions' | 'full-transaction-blob',
|
||||||
|
reader: BufferReader,
|
||||||
|
jobId: number,
|
||||||
|
status: number,
|
||||||
|
): DatumFullTransactionsResponse | DatumFullTransactionBlobResponse {
|
||||||
|
if (status !== DatumJobValidationStatus.SUCCESS) {
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
jobId,
|
||||||
|
status,
|
||||||
|
transactionCount: 0,
|
||||||
|
transactions: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const transactionCount = reader.readU16();
|
||||||
|
const transactions: Buffer[] = [];
|
||||||
|
for (let i = 0; i < transactionCount; i++) {
|
||||||
|
const transactionSize = reader.readU24();
|
||||||
|
transactions.push(reader.readBytes(transactionSize));
|
||||||
|
}
|
||||||
|
consumeDatumTerminatorAndPadding(reader);
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
jobId,
|
||||||
|
status,
|
||||||
|
transactionCount,
|
||||||
|
transactions,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function consumeDatumTerminatorAndPadding(reader: BufferReader): void {
|
||||||
|
if (reader.remaining <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const terminator = reader.readU8();
|
||||||
|
if (terminator !== 0xfe) {
|
||||||
|
throw new RangeError(`DATUM job validation response missing terminator; got 0x${terminator.toString(16)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readNullTerminatedString(reader: BufferReader): string {
|
||||||
|
const bytes: number[] = [];
|
||||||
|
while (reader.remaining > 0) {
|
||||||
|
const byte = reader.readU8();
|
||||||
|
if (byte === 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
bytes.push(byte);
|
||||||
|
}
|
||||||
|
return Buffer.from(bytes).toString('utf8');
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import * as sodium from 'libsodium-wrappers-sumo';
|
||||||
|
import {
|
||||||
|
DATUM_INITIAL_HEADER_KEY,
|
||||||
|
DatumProtocolCommand,
|
||||||
|
datumHeaderXorFeedback,
|
||||||
|
decodeDatumHeader,
|
||||||
|
encodeDatumFrame,
|
||||||
|
} from './datum-codec';
|
||||||
|
import { DatumCryptoSession } from './datum-crypto';
|
||||||
|
|
||||||
|
describe('DatumCryptoSession', () => {
|
||||||
|
it('derives stable DATUM public keys from a configured seed', async () => {
|
||||||
|
await sodium.ready;
|
||||||
|
const seed = Buffer.from('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex');
|
||||||
|
|
||||||
|
const first = DatumCryptoSession.generateKeyPairFromSeed(seed);
|
||||||
|
const second = DatumCryptoSession.generateKeyPairFromSeed(seed);
|
||||||
|
|
||||||
|
expect(Buffer.concat([first.edPublicKey, first.xPublicKey]).toString('hex'))
|
||||||
|
.toBe(Buffer.concat([second.edPublicKey, second.xPublicKey]).toString('hex'));
|
||||||
|
expect(first.edSecretKey).toEqual(second.edSecretKey);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens signed sealed handshakes and builds encrypted responses', async () => {
|
||||||
|
await sodium.ready;
|
||||||
|
const serverIdentity = DatumCryptoSession.generateKeyPair();
|
||||||
|
const serverSessionKeys = DatumCryptoSession.generateKeyPair();
|
||||||
|
const clientIdentity = DatumCryptoSession.generateKeyPair();
|
||||||
|
const clientSessionKeys = DatumCryptoSession.generateKeyPair();
|
||||||
|
const server = await DatumCryptoSession.create(serverIdentity, serverSessionKeys);
|
||||||
|
const nextHeaderKey = 0x12345678;
|
||||||
|
|
||||||
|
const signedBody = Buffer.concat([
|
||||||
|
clientIdentity.edPublicKey,
|
||||||
|
clientIdentity.xPublicKey,
|
||||||
|
clientSessionKeys.edPublicKey,
|
||||||
|
clientSessionKeys.xPublicKey,
|
||||||
|
Buffer.from('datum-test/0\0', 'utf8'),
|
||||||
|
Buffer.from([0xfe]),
|
||||||
|
uint32(nextHeaderKey),
|
||||||
|
Buffer.from([1, 2, 3]),
|
||||||
|
]);
|
||||||
|
const signature = Buffer.from(sodium.crypto_sign_detached(signedBody, clientIdentity.edSecretKey));
|
||||||
|
const encrypted = Buffer.from(sodium.crypto_box_seal(
|
||||||
|
Buffer.concat([signedBody, signature]),
|
||||||
|
serverIdentity.xPublicKey,
|
||||||
|
));
|
||||||
|
const frame = encodeDatumFrame({
|
||||||
|
header: {
|
||||||
|
cmdLen: encrypted.length,
|
||||||
|
reserved: 0,
|
||||||
|
isSigned: true,
|
||||||
|
isEncryptedPubkey: true,
|
||||||
|
isEncryptedChannel: false,
|
||||||
|
protoCmd: DatumProtocolCommand.HANDSHAKE_INIT,
|
||||||
|
},
|
||||||
|
payload: encrypted,
|
||||||
|
}, DATUM_INITIAL_HEADER_KEY);
|
||||||
|
const header = decodeDatumHeader(frame.subarray(0, 4), DATUM_INITIAL_HEADER_KEY);
|
||||||
|
|
||||||
|
const hello = server.openHandshake(frame.subarray(4, 4 + header.cmdLen));
|
||||||
|
expect(hello.userAgent).toBe('datum-test/0');
|
||||||
|
expect(hello.nextHeaderKey).toBe(nextHeaderKey);
|
||||||
|
expect(hello.sessionXPublicKey).toEqual(clientSessionKeys.xPublicKey);
|
||||||
|
|
||||||
|
const response = server.buildHandshakeResponse(hello, 'motd');
|
||||||
|
const responseHeader = decodeDatumHeader(response.subarray(0, 4), datumHeaderXorFeedback((~nextHeaderKey) >>> 0));
|
||||||
|
expect(responseHeader.protoCmd).toBe(DatumProtocolCommand.HANDSHAKE_RESPONSE);
|
||||||
|
expect(responseHeader.isSigned).toBe(true);
|
||||||
|
expect(responseHeader.isEncryptedPubkey).toBe(true);
|
||||||
|
const opened = Buffer.from(sodium.crypto_box_seal_open(
|
||||||
|
response.subarray(4),
|
||||||
|
clientSessionKeys.xPublicKey,
|
||||||
|
clientSessionKeys.xSecretKey,
|
||||||
|
));
|
||||||
|
expect(opened.subarray(0, 32)).toEqual(clientIdentity.edPublicKey);
|
||||||
|
expect(opened.subarray(128, 160)).toEqual(serverSessionKeys.edPublicKey);
|
||||||
|
|
||||||
|
const ping = server.encryptChannelFrame(DatumProtocolCommand.PING, Buffer.alloc(0));
|
||||||
|
const pingHeader = decodeDatumHeader(
|
||||||
|
ping.subarray(0, 4),
|
||||||
|
datumHeaderXorFeedback(datumHeaderXorFeedback((~nextHeaderKey) >>> 0)),
|
||||||
|
);
|
||||||
|
expect(pingHeader.protoCmd).toBe(DatumProtocolCommand.PING);
|
||||||
|
expect(pingHeader.isEncryptedChannel).toBe(true);
|
||||||
|
expect(pingHeader.cmdLen).toBe(sodium.crypto_box_MACBYTES);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function uint32(value: number): Buffer {
|
||||||
|
const result = Buffer.alloc(4);
|
||||||
|
result.writeUInt32LE(value >>> 0, 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user