Compare commits

6 Commits
61 changed files with 4200 additions and 1404 deletions
+10
View File
@@ -26,7 +26,10 @@ DOCKER_LOG_MAX_SIZE=100m
DOCKER_LOG_MAX_FILES=5 DOCKER_LOG_MAX_FILES=5
# Plain TCP Stratum ports accept both SV1 JSON-RPC and SV2 Noise/binary traffic. # 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 STRATUM_PORTS=3333,3332,3331,3330
# Optional PPLNS-mode SV1/SV2 autodetect ports.
#PPLNS_STRATUM_PORTS=
STRATUM_WORKERS=2 STRATUM_WORKERS=2
STRATUM_WORKER_MAX_MEMORY_RESTART=4096M STRATUM_WORKER_MAX_MEMORY_RESTART=4096M
STRATUM_MIN_DIFFICULTY=1 STRATUM_MIN_DIFFICULTY=1
@@ -35,20 +38,24 @@ STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS=60000
# Optional additional SV2-only mining ports. Usually unnecessary when STRATUM_PORTS are exposed. # Optional additional SV2-only mining ports. Usually unnecessary when STRATUM_PORTS are exposed.
#STRATUM_V2_PORTS= #STRATUM_V2_PORTS=
#PPLNS_STRATUM_V2_PORTS=
#SV2_START_DIFFICULTY=100000 #SV2_START_DIFFICULTY=100000
#SV2_TARGET_SHARES_PER_MINUTE=2 #SV2_TARGET_SHARES_PER_MINUTE=2
#SV2_DIFFICULTY_CHECK_INTERVAL_MS=60000 #SV2_DIFFICULTY_CHECK_INTERVAL_MS=60000
#STRATUM_V2_SOCKET_TIMEOUT_MS=3600000 #STRATUM_V2_SOCKET_TIMEOUT_MS=3600000
#SV2_AUTHORITY_PRIVKEY= #SV2_AUTHORITY_PRIVKEY=
#SV2_JDP_PORTS= #SV2_JDP_PORTS=
#PPLNS_SV2_JDP_PORTS=
#SV2_JDP_POOL_PAYOUT_ADDRESS= #SV2_JDP_POOL_PAYOUT_ADDRESS=
#SV2_JDP_TOKEN_TTL_MS=600000 #SV2_JDP_TOKEN_TTL_MS=600000
#SV2_TDP_PORTS= #SV2_TDP_PORTS=
#PPLNS_SV2_TDP_PORTS=
#SV2_TDP_POOL_PAYOUT_ADDRESS= #SV2_TDP_POOL_PAYOUT_ADDRESS=
# Optional DATUM Prime-compatible listener. DATUM_POOL_PAYOUT_ADDRESS is the # Optional DATUM Prime-compatible listener. DATUM_POOL_PAYOUT_ADDRESS is the
# required pool coinbase output DATUM gateways must include in custom templates. # required pool coinbase output DATUM gateways must include in custom templates.
#DATUM_PORTS= #DATUM_PORTS=
#PPLNS_DATUM_PORTS=
#DATUM_POOL_PAYOUT_ADDRESS= #DATUM_POOL_PAYOUT_ADDRESS=
#DATUM_SHARE_DIFFICULTY=1 #DATUM_SHARE_DIFFICULTY=1
# 32-byte hex seed for the DATUM server identity key. DATUM clients must be # 32-byte hex seed for the DATUM server identity key. DATUM clients must be
@@ -57,6 +64,7 @@ STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS=60000
STRATUM_SECURE=true STRATUM_SECURE=true
SECURE_STRATUM_PORTS=4333,4332,4331,4330 SECURE_STRATUM_PORTS=4333,4332,4331,4330
#PPLNS_SECURE_STRATUM_PORTS=
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000 STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000 STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
@@ -91,6 +99,7 @@ SHARE_ACCOUNTING_FLUSH_INTERVAL_MS=25
SHARE_ACCOUNTING_MAX_QUEUE_SIZE=50000 SHARE_ACCOUNTING_MAX_QUEUE_SIZE=50000
SHARE_ACCOUNTING_SUMMARY_CACHE_MS=2500 SHARE_ACCOUNTING_SUMMARY_CACHE_MS=2500
SHARE_ACCOUNTING_SUMMARY_CACHE_MAX=10000 SHARE_ACCOUNTING_SUMMARY_CACHE_MAX=10000
CLIENT_HASHRATE_PERSIST_INTERVAL_MS=60000
SHARE_ROLLUP_ENABLED=true SHARE_ROLLUP_ENABLED=true
SHARE_ROLLUP_INTERVAL_MS=60000 SHARE_ROLLUP_INTERVAL_MS=60000
SHARE_ROLLUP_SAFETY_LAG_SECONDS=30 SHARE_ROLLUP_SAFETY_LAG_SECONDS=30
@@ -100,6 +109,7 @@ SHARE_ROLLUP_MAX_SHARES_PER_BATCH=5000000
PAYOUT_SNAPSHOT_ENABLED=true PAYOUT_SNAPSHOT_ENABLED=true
PAYOUT_METHOD=pplns PAYOUT_METHOD=pplns
PAYOUT_WINDOW_FACTOR=4 PAYOUT_WINDOW_FACTOR=4
PAYOUT_BOOTSTRAP_WINDOW=true
# solo preserves current one-address coinbase payouts. Set to snapshot to pay # solo preserves current one-address coinbase payouts. Set to snapshot to pay
# the latest payout snapshot directly in coinbase outputs. # the latest payout snapshot directly in coinbase outputs.
PAYOUT_COINBASE_MODE=solo PAYOUT_COINBASE_MODE=solo
+1
View File
@@ -21,6 +21,7 @@ lerna-debug.log*
/.baseline-*.json /.baseline-*.json
/.test-artifacts /.test-artifacts
/.profiles /.profiles
/.local-runtime
# IDEs and editors # IDEs and editors
/.idea /.idea
+195 -634
View File
@@ -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 same work.
The Corresponding Source for a work in source code form is that 2. Basic Permissions.
same work. 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.
2. Basic Permissions. 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.
All rights granted under this License are granted for the term of Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
permission to run the unmodified Program. The output from running a 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.
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your 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.
rights of fair use or other equivalent, as provided by copyright law.
4. Conveying Verbatim Copies.
You may make, run and propagate covered works that you do not 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.
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose 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.
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with 5. Conveying Modified Source Versions.
the terms of this License in conveying all material for which you do 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:
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you. 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".
Conveying under any other circumstances is permitted solely under 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.
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary. 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.
3. Protecting Users' Legal Rights From Anti-Circumvention Law. 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.
No covered work shall be deemed part of an effective technological 6. Conveying Non-Source Forms.
measure under any applicable law fulfilling obligations under article 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:
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such 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.
measures.
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.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention 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.
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or 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.
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of 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.
technological measures.
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.
4. Conveying Verbatim Copies.
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.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and "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.
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any 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).
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 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.
recipients a copy of this License along with the Program.
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.
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. 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.
5. Conveying Modified Source Versions.
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.
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 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:
terms of section 4, provided that you also meet all of these conditions:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date. 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
b) The work must carry prominent notices stating that it is 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
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
"keep intact all notices".
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This 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.
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts, 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.
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not 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.
invalidate such permission if you have separately received it.
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.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive 8. Termination.
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so. 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).
A compilation of a covered work with other separate and independent 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.
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, 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.
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not 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.
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work 9. Acceptance Not Required for Having Copies.
in an aggregate does not cause this License to apply to the other
parts of the aggregate. 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.
6. Conveying Non-Source Forms. 10. Automatic Licensing of Downstream Recipients.
You may convey a covered work in object code form under the terms 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.
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License, 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.
in one of these ways:
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.
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the 11. Patents.
Corresponding Source fixed on a durable physical medium
customarily used for software interchange. 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".
b) Convey the object code in, or embodied in, a physical product 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.
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as 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.
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a 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.
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical 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
medium customarily used for software interchange, for a price no 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.
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the 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.
Corresponding Source from a network server at no charge.
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.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This 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.
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord 12. No Surrender of Others' Freedom.
with subsection 6b.
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
d) Convey the object code by offering access from a designated 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.
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no 13. Remote Network Interaction; Use with the GNU General Public License.
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to 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.
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party) 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.
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the 14. Revised Versions of this License.
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is 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.
available for as long as needed to satisfy these requirements.
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.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding 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.
Source of the work are being offered to the general public at no
charge under subsection 6d. 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.
A separable portion of the object code, whose source code is excluded 15. Disclaimer of Warranty.
from the Corresponding Source as a System Library, need not be
included in conveying the object code work. 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.
A "User Product" is either (1) a "consumer product", which means any 16. Limitation of Liability.
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation 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.
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular 17. Interpretation of Sections 15 and 16.
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status 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.
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 END OF TERMS AND CONDITIONS
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,
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
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
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.
"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.
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.
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:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
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
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
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
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.
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.
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.
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.
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).
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.
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.
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.
9. Acceptance Not Required for Having Copies.
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.
10. Automatic Licensing of Downstream Recipients.
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.
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.
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.
11. Patents.
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".
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.
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.
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.
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
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
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
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
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.
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
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.
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 Affero 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 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.
The Free Software Foundation may publish revised and/or new versions of
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
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
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
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.
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.
16. Limitation of Liability.
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.
17. Interpretation of Sections 15 and 16.
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.
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>.
+25 -1
View File
@@ -41,6 +41,21 @@ services:
- "0.0.0.0:4332:4332/tcp" - "0.0.0.0:4332:4332/tcp"
- "0.0.0.0:4331:4331/tcp" - "0.0.0.0:4331:4331/tcp"
- "0.0.0.0:4330:4330/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" - "${API_BIND_HOST:-127.0.0.1}:${API_PUBLIC_PORT:-3334}:3334/tcp"
volumes: volumes:
- "./.env:/public-pool/.env:ro" - "./.env:/public-pool/.env:ro"
@@ -62,15 +77,24 @@ services:
PM2_ENABLED: ${PM2_ENABLED:-true} PM2_ENABLED: ${PM2_ENABLED:-true}
STRATUM_WORKERS: ${STRATUM_WORKERS:-2} STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330} STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330}
PPLNS_STRATUM_PORTS: ${PPLNS_STRATUM_PORTS:-}
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1} STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000} STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000} STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
STRATUM_SECURE: ${STRATUM_SECURE:-true} STRATUM_SECURE: ${STRATUM_SECURE:-true}
SECURE_STRATUM_PORTS: ${SECURE_STRATUM_PORTS:-4333,4332,4331,4330} 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_MAX_CONNECTIONS_PER_LISTENER: ${STRATUM_MAX_CONNECTIONS_PER_LISTENER:-10000}
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000} STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000}
STRATUM_BACKPRESSURE_ENABLED: "${STRATUM_BACKPRESSURE_ENABLED:-false}" STRATUM_BACKPRESSURE_ENABLED: "${STRATUM_BACKPRESSURE_ENABLED:-false}"
STRATUM_V2_PORTS: ${STRATUM_V2_PORTS:-} 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_BATCH_SIZE: ${SHARE_ACCOUNTING_BATCH_SIZE:-500}
SHARE_ACCOUNTING_FLUSH_INTERVAL_MS: ${SHARE_ACCOUNTING_FLUSH_INTERVAL_MS:-25} SHARE_ACCOUNTING_FLUSH_INTERVAL_MS: ${SHARE_ACCOUNTING_FLUSH_INTERVAL_MS:-25}
SHARE_ACCOUNTING_MAX_QUEUE_SIZE: ${SHARE_ACCOUNTING_MAX_QUEUE_SIZE:-50000} SHARE_ACCOUNTING_MAX_QUEUE_SIZE: ${SHARE_ACCOUNTING_MAX_QUEUE_SIZE:-50000}
@@ -83,7 +107,7 @@ services:
PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true} PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true}
PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns} PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns}
PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4} PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4}
PAYOUT_COINBASE_MODE: ${PAYOUT_COINBASE_MODE:-solo} PAYOUT_BOOTSTRAP_WINDOW: ${PAYOUT_BOOTSTRAP_WINDOW:-true}
PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-10} PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-10}
PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546} PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546}
PAYOUT_FEE_ADDRESS: ${PAYOUT_FEE_ADDRESS:-} PAYOUT_FEE_ADDRESS: ${PAYOUT_FEE_ADDRESS:-}
+24
View File
@@ -74,6 +74,21 @@ services:
- "0.0.0.0:4332:4332/tcp" - "0.0.0.0:4332:4332/tcp"
- "0.0.0.0:4331:4331/tcp" - "0.0.0.0:4331:4331/tcp"
- "0.0.0.0:4330:4330/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" - "${API_BIND_HOST:-127.0.0.1}:${API_PUBLIC_PORT:-3334}:3334/tcp"
volumes: volumes:
- "./.env:/public-pool/.env:ro" - "./.env:/public-pool/.env:ro"
@@ -92,14 +107,23 @@ services:
PM2_ENABLED: ${PM2_ENABLED:-true} PM2_ENABLED: ${PM2_ENABLED:-true}
STRATUM_WORKERS: ${STRATUM_WORKERS:-2} STRATUM_WORKERS: ${STRATUM_WORKERS:-2}
STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330} STRATUM_PORTS: ${STRATUM_PORTS:-3333,3332,3331,3330}
PPLNS_STRATUM_PORTS: ${PPLNS_STRATUM_PORTS:-}
STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1} STRATUM_MIN_DIFFICULTY: ${STRATUM_MIN_DIFFICULTY:-1}
STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000} STRATUM_SOCKET_TIMEOUT_MS: ${STRATUM_SOCKET_TIMEOUT_MS:-3600000}
STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000} STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS: ${STRATUM_TCP_KEEPALIVE_INITIAL_DELAY_MS:-60000}
STRATUM_SECURE: ${STRATUM_SECURE:-true} STRATUM_SECURE: ${STRATUM_SECURE:-true}
SECURE_STRATUM_PORTS: ${SECURE_STRATUM_PORTS:-4333,4332,4331,4330} 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_MAX_CONNECTIONS_PER_LISTENER: ${STRATUM_MAX_CONNECTIONS_PER_LISTENER:-10000}
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000} STRATUM_TLS_HANDSHAKE_TIMEOUT_MS: ${STRATUM_TLS_HANDSHAKE_TIMEOUT_MS:-10000}
STRATUM_V2_PORTS: ${STRATUM_V2_PORTS:-} 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: 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);});\""] 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 interval: 30s
+1
View File
@@ -120,6 +120,7 @@ services:
PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true} PAYOUT_SNAPSHOT_ENABLED: ${PAYOUT_SNAPSHOT_ENABLED:-true}
PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns} PAYOUT_METHOD: ${PAYOUT_METHOD:-pplns}
PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4} PAYOUT_WINDOW_FACTOR: ${PAYOUT_WINDOW_FACTOR:-4}
PAYOUT_BOOTSTRAP_WINDOW: ${PAYOUT_BOOTSTRAP_WINDOW:-true}
PAYOUT_COINBASE_MODE: ${PAYOUT_COINBASE_MODE:-solo} PAYOUT_COINBASE_MODE: ${PAYOUT_COINBASE_MODE:-solo}
PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-10} PAYOUT_MAX_COINBASE_OUTPUTS: ${PAYOUT_MAX_COINBASE_OUTPUTS:-10}
PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546} PAYOUT_MIN_OUTPUT_SATS: ${PAYOUT_MIN_OUTPUT_SATS:-546}
+10
View File
@@ -8,8 +8,18 @@ BITCOIN_ZMQ_HOST=tcp://bitcoin:3000
API_PORT=3334 API_PORT=3334
STRATUM_PORTS=3333,3332,3331,3330 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 STRATUM_SECURE=true
SECURE_STRATUM_PORTS=4333,4332,4331,4330 SECURE_STRATUM_PORTS=4333,4332,4331,4330
PPLNS_SECURE_STRATUM_PORTS=
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000 STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000 STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
+10
View File
@@ -8,8 +8,18 @@ BITCOIN_ZMQ_HOST=tcp://bitcoin-testnet:3000
API_PORT=13334 API_PORT=13334
STRATUM_PORTS=13333,13332,13331,13330 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 STRATUM_SECURE=false
SECURE_STRATUM_PORTS= SECURE_STRATUM_PORTS=
PPLNS_SECURE_STRATUM_PORTS=
STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000 STRATUM_MAX_CONNECTIONS_PER_LISTENER=10000
STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000 STRATUM_TLS_HANDSHAKE_TIMEOUT_MS=10000
+1 -1
View File
@@ -8,7 +8,7 @@
"name": "public-pool", "name": "public-pool",
"version": "0.0.1", "version": "0.0.1",
"hasInstallScript": true, "hasInstallScript": true,
"license": "UNLICENSED", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
"@nestjs/axios": "^4.0.1", "@nestjs/axios": "^4.0.1",
"@nestjs/cache-manager": "^3.1.2", "@nestjs/cache-manager": "^3.1.2",
+1 -1
View File
@@ -4,7 +4,7 @@
"description": "", "description": "",
"author": "", "author": "",
"private": true, "private": true,
"license": "UNLICENSED", "license": "AGPL-3.0-only",
"engines": { "engines": {
"node": ">=22.12.0" "node": ">=22.12.0"
}, },
@@ -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,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,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,125 @@
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();
});
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(),
groupBy: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
getRawMany: jest.fn().mockResolvedValue(rows),
};
return {
createQueryBuilder: jest.fn().mockReturnValue(queryBuilder),
};
}
@@ -29,10 +29,17 @@ export class UserAgentReportService {
return null; return null;
}); });
if (cachedReport != null) { if (cachedReport != null) {
return cachedReport; if (cachedReport.length > 0) {
return cachedReport;
}
} }
if (process.env.API_ONLY == 'true') { 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.userAgentReport.find();
} }
@@ -53,49 +60,28 @@ export class UserAgentReportService {
} }
private async buildLiveReport() { private async buildLiveReport() {
const presences = await this.redisMessagingService.getAllClientPresence(); const rows = await this.clientRepository
const rows = new Map<string, { .createQueryBuilder('client')
userAgent: string; .select('COALESCE(NULLIF(client.userAgent, \'\'), \'Other\')', 'userAgent')
count: number; .addSelect('COUNT(*)', 'count')
bestDifficulty: number; .addSelect('MAX(client.bestDifficulty)', 'bestDifficulty')
totalHashRate: number; .addSelect('COALESCE(SUM(client.hashRate), 0)', 'totalHashRate')
}>(); .where('client.deletedAt IS NULL')
.groupBy('COALESCE(NULLIF(client.userAgent, \'\'), \'Other\')')
.orderBy('"totalHashRate"', 'DESC')
.getRawMany<UserAgentReportView>();
presences.forEach(presence => { if (rows.length === 0) {
const userAgent = presence.userAgent == null || presence.userAgent.length === 0 return await this.userAgentReport.find();
? 'Other' }
: presence.userAgent;
const row = rows.get(userAgent) ?? {
userAgent,
count: 0,
bestDifficulty: 0,
totalHashRate: 0,
};
row.count++;
row.bestDifficulty = Math.max(
row.bestDifficulty,
Number(presence.bestDifficulty ?? 0),
);
row.totalHashRate += Number(presence.hashRate ?? 0);
rows.set(userAgent, row);
});
const report = [...rows.values()]
.sort((left, right) => right.totalHashRate - left.totalHashRate)
.map(row => ({
userAgent: row.userAgent,
count: row.count.toString(),
bestDifficulty: row.bestDifficulty,
totalHashRate: row.totalHashRate.toString(),
}));
await this.redisMessagingService await this.redisMessagingService
.setJsonCache(this.liveReportCacheKey, report, 60 * 1000) .setJsonCache(this.liveReportCacheKey, rows, 60 * 1000)
.catch(error => { .catch(error => {
console.error(`Live user-agent report cache write failed: ${error.message}`); console.error(`Live user-agent report cache write failed: ${error.message}`);
}); });
return report; return rows;
} }
public async refreshReport() { public async refreshReport() {
@@ -1,10 +1,10 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm'; import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
@Entity() @Entity()
@Index('IDX_accepted_share_accounting_lookup', ['address', 'clientName', 'acceptedAt']) @Index('IDX_accepted_share_mode_order', ['payoutMode', 'shareIndex'])
@Index('IDX_accepted_share_client_lookup', ['clientId', 'acceptedAt']) @Index('IDX_accepted_share_unique_submission', ['acceptedAt', 'payoutMode', 'protocol', 'sessionId', 'jobId', 'nonce', 'ntime', 'version', 'extraNonce2'], { unique: true })
@Index('IDX_accepted_share_order', ['shareIndex'])
@Index('IDX_accepted_share_unique_submission', ['acceptedAt', 'protocol', 'sessionId', 'jobId', 'nonce', 'ntime', 'version', 'extraNonce2'], { unique: true })
export class AcceptedShareEntity { export class AcceptedShareEntity {
@PrimaryGeneratedColumn('uuid') @PrimaryGeneratedColumn('uuid')
id: string; id: string;
@@ -18,6 +18,9 @@ export class AcceptedShareEntity {
@Column({ length: 16, type: 'varchar' }) @Column({ length: 16, type: 'varchar' })
protocol: 'sv1' | 'sv1_tls' | 'sv2' | 'sv2_jdp' | 'datum'; 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' }) @Column({ length: 16, type: 'varchar', default: 'pool_template' })
workSource: 'pool_template' | 'miner_template'; workSource: 'pool_template' | 'miner_template';
+5 -1
View File
@@ -1,5 +1,6 @@
import { Column, Entity } from 'typeorm'; import { Column, Entity } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
import { PrimaryGeneratedBigIntColumn } from '../utils/PrimaryGeneratedBigIntColumn'; import { PrimaryGeneratedBigIntColumn } from '../utils/PrimaryGeneratedBigIntColumn';
import { TrackedEntity } from '../utils/TrackedEntity.entity'; import { TrackedEntity } from '../utils/TrackedEntity.entity';
@@ -18,6 +19,9 @@ 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;
@@ -31,6 +35,6 @@ export class BlocksEntity extends TrackedEntity {
blockSubmissionResult?: string; blockSubmissionResult?: string;
@Column({ type: 'bigint', nullable: true }) @Column({ type: 'bigint', nullable: true })
payoutSnapshotId?: string; payoutSnapshotId?: string | null;
} }
+129
View File
@@ -30,6 +30,9 @@ describe('BlocksService', () => {
id: 9, id: 9,
blockSubmissionResult: 'SUCCESS!', blockSubmissionResult: 'SUCCESS!',
payoutSnapshotId: '7', payoutSnapshotId: '7',
minerAddress: 'tb1qminer',
worker: 'worker',
sessionId: 'abcd1234',
}); });
const service = new BlocksService({} as any, repository as any); const service = new BlocksService({} as any, repository as any);
@@ -43,6 +46,88 @@ describe('BlocksService', () => {
expect(repository.save).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 () => { it('returns one public found-block row per block hash or legacy height', async () => {
const repository = createRepository(); const repository = createRepository();
repository.find.mockResolvedValue([ repository.find.mockResolvedValue([
@@ -57,6 +142,50 @@ describe('BlocksService', () => {
{ height: 124, minerAddress: 'addr2', worker: 'b', sessionId: '2222', blockHash: 'hash-b' }, { height: 124, minerAddress: 'addr2', worker: 'b', sessionId: '2222', blockHash: 'hash-b' },
{ height: 123, minerAddress: 'addr1', worker: 'a', sessionId: '1111', blockHash: null }, { 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() { function createRepository() {
+52 -12
View File
@@ -1,14 +1,17 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import * as bitcoinjs from 'bitcoinjs-lib'; import * as bitcoinjs from 'bitcoinjs-lib';
import { DataSource, IsNull, Repository } from 'typeorm'; 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,
@@ -24,15 +27,35 @@ export class BlocksService {
const existing = blockHash == null const existing = blockHash == null
? null ? null
: await this.blocksRepository.findOne({ : await this.blocksRepository.findOne({
select: { id: true, blockSubmissionResult: true, payoutSnapshotId: true }, select: {
id: true,
blockSubmissionResult: true,
payoutSnapshotId: true,
minerAddress: true,
worker: true,
sessionId: true,
payoutMode: true,
},
where: { blockHash }, where: { blockHash },
}); });
if (existing != null) { if (existing != null) {
const update: Partial<BlocksEntity> = {};
if (this.isSuccessfulBlockSubmission(block.blockSubmissionResult)) { if (this.isSuccessfulBlockSubmission(block.blockSubmissionResult)) {
await this.blocksRepository.update(existing.id, { update.blockSubmissionResult = 'SUCCESS!';
blockSubmissionResult: 'SUCCESS!', update.payoutSnapshotId = Object.prototype.hasOwnProperty.call(block, 'payoutSnapshotId')
payoutSnapshotId: block.payoutSnapshotId ?? existing.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; return;
} }
@@ -43,20 +66,21 @@ export class BlocksService {
}); });
} }
public async getFoundBlocks() { public async getFoundBlocks(payoutMode?: PayoutMode) {
const rows = await this.blocksRepository.find({ const rows = await this.blocksRepository.find({
select: { select: {
height: true, height: true,
minerAddress: true, minerAddress: true,
worker: true, worker: true,
sessionId: true, sessionId: true,
payoutMode: true,
blockHash: true, blockHash: true,
blockSubmissionResult: true, blockSubmissionResult: true,
createdAt: true, createdAt: true,
}, },
where: [ where: [
{ blockSubmissionResult: 'SUCCESS!' }, { ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: In(BlocksService.PUBLIC_FOUND_BLOCK_RESULTS) },
{ blockSubmissionResult: IsNull() }, { ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: IsNull() },
], ],
order: { order: {
height: 'DESC', height: 'DESC',
@@ -66,20 +90,21 @@ export class BlocksService {
return this.uniqueFoundBlocks(rows); return this.uniqueFoundBlocks(rows);
} }
public async getFoundBlocksByAddress(address: string) { public async getFoundBlocksByAddress(address: string, payoutMode?: PayoutMode) {
const rows = await this.blocksRepository.find({ const rows = await this.blocksRepository.find({
select: { select: {
height: true, height: true,
minerAddress: true, minerAddress: true,
worker: true, worker: true,
sessionId: true, sessionId: true,
payoutMode: true,
blockHash: true, blockHash: true,
blockSubmissionResult: true, blockSubmissionResult: true,
createdAt: true, createdAt: true,
}, },
where: [ where: [
{ minerAddress: address, blockSubmissionResult: 'SUCCESS!' }, { minerAddress: address, ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: In(BlocksService.PUBLIC_FOUND_BLOCK_RESULTS) },
{ minerAddress: address, blockSubmissionResult: IsNull() }, { minerAddress: address, ...(payoutMode == null ? {} : { payoutMode }), blockSubmissionResult: IsNull() },
], ],
order: { order: {
height: 'DESC', height: 'DESC',
@@ -122,4 +147,19 @@ export class BlocksService {
private isSuccessfulBlockSubmission(result?: string | null): boolean { private isSuccessfulBlockSubmission(result?: string | null): boolean {
return result == null || result === 'SUCCESS!'; 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';
}
} }
@@ -2,11 +2,20 @@ import { Injectable } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm'; import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
const HASHES_PER_DIFFICULTY = 4294967296; const HASHES_PER_DIFFICULTY = 4294967296;
const CHART_BUCKET_SECONDS = 600; const CHART_BUCKET_SECONDS = 600;
const CHART_WINDOW = '24 hours'; const CHART_WINDOW = '24 hours';
const SITE_CHART_WINDOW = '7 days'; const SITE_CHART_WINDOW = '7 days';
interface AcceptedShareChartFilter {
address?: string;
clientName?: string;
clientId?: string;
payoutMode?: PayoutMode;
}
@Injectable() @Injectable()
export class ClientStatisticsService { export class ClientStatisticsService {
@@ -21,6 +30,10 @@ export class ClientStatisticsService {
return this.getAcceptedShareChartData('', [], limit, SITE_CHART_WINDOW); return this.getAcceptedShareChartData('', [], limit, SITE_CHART_WINDOW);
} }
public async getChartDataForSiteByPayoutMode(payoutMode?: PayoutMode, limit: number = 144 * 7) {
return this.getAcceptedShareChartDataByPayoutMode({ payoutMode }, limit, SITE_CHART_WINDOW);
}
public async getChartDataForAddress(address: string) { public async getChartDataForAddress(address: string) {
return this.getAcceptedShareChartData( return this.getAcceptedShareChartData(
'AND "address" = $1', 'AND "address" = $1',
@@ -30,14 +43,33 @@ export class ClientStatisticsService {
); );
} }
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(` const result = await this.dataSource.query(`
WITH bounds AS (
SELECT time_bucket(INTERVAL '10 minutes', NOW()) AS current_bucket
),
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
COALESCE((SUM("creditedDifficulty") * ${HASHES_PER_DIFFICULTY}) / ${CHART_BUCKET_SECONDS}, 0) AS "hashRate" COALESCE(((completed."creditedDifficulty" + live."creditedDifficulty") * ${HASHES_PER_DIFFICULTY}) / ${CHART_BUCKET_SECONDS}, 0) AS "hashRate"
FROM "accepted_share_entity" FROM completed, live
WHERE "address" = $1
AND "clientName" = $2
AND "acceptedAt" > NOW() - INTERVAL '1 hour'
`, [address, clientName]); `, [address, clientName]);
return parseFloat(result[0]?.hashRate ?? '0'); return parseFloat(result[0]?.hashRate ?? '0');
@@ -52,6 +84,10 @@ export class ClientStatisticsService {
); );
} }
public async getChartDataForGroupByPayoutMode(address: string, clientName: string, payoutMode?: PayoutMode) {
return this.getAcceptedShareChartDataByPayoutMode({ address, clientName, payoutMode }, 144, CHART_WINDOW);
}
public async getChartDataForSession(clientId: string) { public async getChartDataForSession(clientId: string) {
return this.getAcceptedShareChartData( return this.getAcceptedShareChartData(
'AND "clientId" = $1', 'AND "clientId" = $1',
@@ -61,6 +97,10 @@ export class ClientStatisticsService {
); );
} }
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) { private async getAcceptedShareChartData(filterSql: string, params: unknown[], limit: number, windowSql: string) {
const query = ` const query = `
WITH bounds AS ( WITH bounds AS (
@@ -101,4 +141,80 @@ export class ClientStatisticsService {
}; };
}); });
} }
private async getAcceptedShareChartDataByPayoutMode(
filter: AcceptedShareChartFilter,
limit: number,
windowSql: string,
) {
const { whereSql, params } = this.buildModeChartWhere(filter);
const query = `
WITH bounds AS (
SELECT
NOW() - INTERVAL '${windowSql}' AS since,
time_bucket(INTERVAL '10 minutes', NOW()) AS current_bucket
)
SELECT
"label",
"payoutMode",
"data",
"shares",
"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.dataSource.query(query, params);
return result.map(res => {
return {
label: new Date(res.label).toISOString(),
payoutMode: res.payoutMode,
data: res.data,
shares: Number(res.shares ?? 0),
acceptedCount: Number(res.acceptedCount ?? 0),
};
});
}
private buildModeChartWhere(filter: AcceptedShareChartFilter): { 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(normalizePayoutMode(filter.payoutMode));
where.push(`"payoutMode" = $${params.length}`);
}
return {
whereSql: where.length > 0 ? `AND ${where.join(' AND ')}` : '',
params,
};
}
} }
+4
View File
@@ -1,5 +1,6 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
import { TrackedEntity } from '../utils/TrackedEntity.entity'; import { TrackedEntity } from '../utils/TrackedEntity.entity';
@@ -24,6 +25,9 @@ export class ClientEntity extends TrackedEntity {
@Column({ 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;
+26 -2
View File
@@ -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 { In, Repository } from 'typeorm';
import { ClientEntity } from './client.entity'; import { ClientEntity } from './client.entity';
@@ -58,15 +58,39 @@ export class ClientService {
.execute(); .execute();
} }
public async updateHashRate(id: string, hashRate: number, updatedAt = new Date()) {
return await this.clientRepository.update({ id }, { hashRate, updatedAt });
}
public async connectedClientCount(): Promise<number> { public async connectedClientCount(): Promise<number> {
return await this.clientRepository.count(); return await this.clientRepository.count();
} }
public async getActiveIds(ids: string[]): Promise<Set<string>> {
if (ids.length === 0) {
return new Set();
}
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[]> { public async getByAddress(address: string): Promise<ClientEntity[]> {
return await this.clientRepository.find({ return await this.clientRepository.find({
where: { where: {
address address
} },
order: {
updatedAt: 'DESC',
},
}) })
} }
@@ -23,15 +23,14 @@ describe('buildPayoutDistribution', () => {
payoutSats: entry.payoutSats, payoutSats: entry.payoutSats,
balanceAfterSats: entry.balanceAfterSats, balanceAfterSats: entry.balanceAfterSats,
}))).toEqual([ }))).toEqual([
{ address: ADDRESS_A, payoutSats: 1000, balanceAfterSats: -334 }, { address: ADDRESS_A, payoutSats: 667, balanceAfterSats: 0 },
{ address: ADDRESS_B, payoutSats: 333, balanceAfterSats: 0 },
]); ]);
expect(result.entries.find(entry => entry.address === ADDRESS_B))
.toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 333 }));
expect(result.distributedSats).toBe(1000); expect(result.distributedSats).toBe(1000);
expect(result.unallocatedRemainderSats).toBe(0); expect(result.unallocatedRemainderSats).toBe(0);
}); });
it('should carry sub-dust work forward as signed credit', () => { it('should include small active miner payouts instead of reallocating their work', () => {
const result = buildPayoutDistribution({ const result = buildPayoutDistribution({
addressWork: [ addressWork: [
{ address: ADDRESS_A, creditedDifficulty: 999, acceptedShareCount: 999 }, { address: ADDRESS_A, creditedDifficulty: 999, acceptedShareCount: 999 },
@@ -48,17 +47,18 @@ describe('buildPayoutDistribution', () => {
const paid = result.entries.find(entry => entry.address === ADDRESS_A); const paid = result.entries.find(entry => entry.address === ADDRESS_A);
expect(pending).toEqual(expect.objectContaining({ expect(pending).toEqual(expect.objectContaining({
includedInCoinbase: false, includedInCoinbase: true,
grossPayoutSats: 1, grossPayoutSats: 1,
payoutSats: 0, payoutSats: 1,
balanceAfterSats: 1, balanceAfterSats: 0,
})); }));
expect(paid).toEqual(expect.objectContaining({ expect(paid).toEqual(expect.objectContaining({
includedInCoinbase: true, includedInCoinbase: true,
payoutSats: 1000, payoutSats: 999,
balanceAfterSats: -1, balanceAfterSats: 0,
})); }));
expect(result.distributedSats).toBe(1000); expect(result.distributedSats).toBe(1000);
expect(result.unallocatedRemainderSats).toBe(0);
}); });
it('should trim outputs that do not fit the coinbase weight budget', () => { it('should trim outputs that do not fit the coinbase weight budget', () => {
@@ -77,10 +77,16 @@ describe('buildPayoutDistribution', () => {
expect(result.payoutOutputs).toHaveLength(1); expect(result.payoutOutputs).toHaveLength(1);
expect(result.payoutOutputs[0].address).toBe(ADDRESS_A); 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)) expect(result.entries.find(entry => entry.address === ADDRESS_B))
.toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 1000 })); .toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 1000 }));
expect(result.entries.find(entry => entry.address === ADDRESS_C)) expect(result.entries.find(entry => entry.address === ADDRESS_C))
.toEqual(expect.objectContaining({ includedInCoinbase: false, balanceAfterSats: 888 })); .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', () => { it('should apply positive and negative carried balances to the next distribution', () => {
+154 -28
View File
@@ -73,6 +73,11 @@ interface ComputedAddress {
includedInCoinbase: boolean; includedInCoinbase: boolean;
} }
interface AllocationTarget<T> {
item: T;
weight: number;
}
export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutDistributionResult { export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutDistributionResult {
const coinbaseValueSats = Math.max(0, Math.floor(input.coinbaseValueSats)); const coinbaseValueSats = Math.max(0, Math.floor(input.coinbaseValueSats));
const minOutputSats = Math.max(DUST_LIMIT_SATS, Math.floor(input.minOutputSats)); const minOutputSats = Math.max(DUST_LIMIT_SATS, Math.floor(input.minOutputSats));
@@ -120,6 +125,15 @@ export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutD
}; };
} }
const fairShareSats = allocateIntegerSats(
[...workByAddress.entries()].map(([address, work]) => ({
item: address,
weight: work.creditedDifficulty,
})),
minerRewardSats,
totalCreditedDifficulty,
);
const computations = new Map<string, ComputedAddress>(); const computations = new Map<string, ComputedAddress>();
const considered = new Set<string>([...workByAddress.keys(), ...balanceByAddress.keys()]); const considered = new Set<string>([...workByAddress.keys(), ...balanceByAddress.keys()]);
@@ -128,7 +142,7 @@ export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutD
const creditedDifficulty = work?.creditedDifficulty ?? 0; const creditedDifficulty = work?.creditedDifficulty ?? 0;
const acceptedShareCount = work?.acceptedShareCount ?? 0; const acceptedShareCount = work?.acceptedShareCount ?? 0;
const payoutWeight = creditedDifficulty > 0 ? creditedDifficulty / totalCreditedDifficulty : 0; const payoutWeight = creditedDifficulty > 0 ? creditedDifficulty / totalCreditedDifficulty : 0;
const rawFairSats = Math.floor(payoutWeight * minerRewardSats); const rawFairSats = fairShareSats.get(address) ?? 0;
const balanceBeforeSats = balanceByAddress.get(address) ?? 0; const balanceBeforeSats = balanceByAddress.get(address) ?? 0;
const targetSats = rawFairSats + balanceBeforeSats; const targetSats = rawFairSats + balanceBeforeSats;
computations.set(address, { computations.set(address, {
@@ -148,47 +162,31 @@ export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutD
const feeWeight = feeSats > 0 ? outputWeightForAddress(feeAddress) : 0; const feeWeight = feeSats > 0 ? outputWeightForAddress(feeAddress) : 0;
let usedWeight = COINBASE_BASE_WEIGHT + COINBASE_WITNESS_COMMITMENT_WEIGHT + feeWeight; let usedWeight = COINBASE_BASE_WEIGHT + COINBASE_WITNESS_COMMITMENT_WEIGHT + feeWeight;
const effectiveBudget = coinbaseWeightBudget - BUDGET_SAFETY_MARGIN_WEIGHT; const effectiveBudget = coinbaseWeightBudget - BUDGET_SAFETY_MARGIN_WEIGHT;
allocatePayoutTargets(computations, minerRewardSats, totalCreditedDifficulty);
const eligible = [...computations.values()] const eligible = [...computations.values()]
.filter(row => row.targetSats >= minOutputSats) .filter(row => row.payoutSats > 0 && (row.creditedDifficulty > 0 || row.payoutSats >= minOutputSats))
.sort((a, b) => b.targetSats - a.targetSats || a.address.localeCompare(b.address)); .sort((a, b) => b.payoutSats - a.payoutSats || b.targetSats - a.targetSats || a.address.localeCompare(b.address));
for (const row of eligible) { for (const row of eligible) {
const outputWeight = outputWeightForAddress(row.address); const outputWeight = outputWeightForAddress(row.address);
if (usedWeight + outputWeight > effectiveBudget) { if (usedWeight + outputWeight > effectiveBudget) {
row.balanceAfterSats = row.targetSats;
continue; continue;
} }
row.includedInCoinbase = true; row.includedInCoinbase = true;
row.payoutSats = row.targetSats; row.balanceAfterSats = row.targetSats - row.payoutSats;
row.balanceAfterSats = 0;
usedWeight += outputWeight; usedWeight += outputWeight;
} }
let distributedToMiners = 0;
for (const row of computations.values()) { for (const row of computations.values()) {
distributedToMiners += row.payoutSats; if (!row.includedInCoinbase && row.payoutSats > 0) {
} row.payoutSats = 0;
row.balanceAfterSats = row.targetSats;
const remainder = minerRewardSats - distributedToMiners;
if (remainder > 0) {
const keptActive = [...computations.values()]
.filter(row => row.includedInCoinbase && row.creditedDifficulty > 0)
.sort((a, b) => b.creditedDifficulty - a.creditedDifficulty || a.address.localeCompare(b.address));
if (keptActive.length > 0) {
let assigned = 0;
for (const row of keptActive) {
const bonus = Math.floor((remainder * row.creditedDifficulty) / totalCreditedDifficulty);
row.payoutSats += bonus;
row.balanceAfterSats -= bonus;
assigned += bonus;
}
const residual = remainder - assigned;
if (residual > 0) {
keptActive[0].payoutSats += residual;
keptActive[0].balanceAfterSats -= residual;
}
} }
} }
redistributeUnfitMinerPayouts(computations, minerRewardSats);
const feeEntry = feeSats > 0 const feeEntry = feeSats > 0
? { ? {
address: feeAddress, address: feeAddress,
@@ -243,6 +241,134 @@ export function buildPayoutDistribution(input: PayoutDistributionInput): PayoutD
}; };
} }
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( function mergeFeeEntry(
feeEntry: PayoutDistributionEntry, feeEntry: PayoutDistributionEntry,
minerEntries: Omit<PayoutDistributionEntry, 'rank'>[], minerEntries: Omit<PayoutDistributionEntry, 'rank'>[],
@@ -1,12 +1,14 @@
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
const bigintTransformer = { const bigintTransformer = {
from: (value: string | number | null): number => Number(value ?? 0), from: (value: string | number | null): number => Number(value ?? 0),
to: (value: number): number => Math.trunc(value ?? 0), to: (value: number): number => Math.trunc(value ?? 0),
}; };
@Entity({ name: 'payout_history' }) @Entity({ name: 'payout_history' })
@Index('UQ_payout_history_block_address', ['blockHeight', 'address'], { unique: true }) @Index('UQ_payout_history_block_address', ['payoutMode', 'blockHeight', 'address'], { unique: true })
@Index('IDX_payout_history_address_created', ['address', 'createdAt']) @Index('IDX_payout_history_address_created', ['address', 'createdAt'])
export class PayoutHistoryEntity { export class PayoutHistoryEntity {
@PrimaryGeneratedColumn({ type: 'bigint' }) @PrimaryGeneratedColumn({ type: 'bigint' })
@@ -18,6 +20,9 @@ export class PayoutHistoryEntity {
@Column({ type: 'bigint' }) @Column({ type: 'bigint' })
payoutSnapshotId: string; payoutSnapshotId: string;
@Column({ length: 16, type: 'varchar', default: 'pplns' })
payoutMode: PayoutMode;
@Column({ length: 62, type: 'varchar' }) @Column({ length: 62, type: 'varchar' })
address: string; address: string;
@@ -1,5 +1,6 @@
import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
import { PayoutSnapshotEntity } from './payout-snapshot.entity'; import { PayoutSnapshotEntity } from './payout-snapshot.entity';
@Entity({ name: 'payout_snapshot_entry' }) @Entity({ name: 'payout_snapshot_entry' })
@@ -12,6 +13,9 @@ export class PayoutSnapshotEntryEntity {
@Column({ type: 'bigint' }) @Column({ type: 'bigint' })
snapshotId: string; snapshotId: string;
@Column({ length: 16, type: 'varchar', default: 'pplns' })
payoutMode: PayoutMode;
@ManyToOne(() => PayoutSnapshotEntity, snapshot => snapshot.entries, { onDelete: 'CASCADE' }) @ManyToOne(() => PayoutSnapshotEntity, snapshot => snapshot.entries, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'snapshotId' }) @JoinColumn({ name: 'snapshotId' })
snapshot: PayoutSnapshotEntity; snapshot: PayoutSnapshotEntity;
@@ -1,9 +1,10 @@
import { Column, Entity, Index, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; import { Column, Entity, Index, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { PayoutMode } from '../../types/payout-mode';
import { PayoutSnapshotEntryEntity } from './payout-snapshot-entry.entity'; import { PayoutSnapshotEntryEntity } from './payout-snapshot-entry.entity';
@Entity({ name: 'payout_snapshot' }) @Entity({ name: 'payout_snapshot' })
@Index('IDX_payout_snapshot_latest', ['status', 'createdAt']) @Index('IDX_payout_snapshot_latest', ['payoutMode', 'status', 'createdAt'])
@Index('IDX_payout_snapshot_window', ['windowEndShareIndex']) @Index('IDX_payout_snapshot_window', ['windowEndShareIndex'])
export class PayoutSnapshotEntity { export class PayoutSnapshotEntity {
@PrimaryGeneratedColumn({ type: 'bigint' }) @PrimaryGeneratedColumn({ type: 'bigint' })
@@ -12,6 +13,9 @@ export class PayoutSnapshotEntity {
@Column({ length: 32, type: 'varchar' }) @Column({ length: 32, type: 'varchar' })
method: string; method: string;
@Column({ length: 16, type: 'varchar', default: 'pplns' })
payoutMode: PayoutMode;
@Column({ length: 16, type: 'varchar', default: 'finalized' }) @Column({ length: 16, type: 'varchar', default: 'finalized' })
status: 'finalized'; status: 'finalized';
@@ -16,6 +16,7 @@ describe('PayoutSnapshotService', () => {
process.env.PAYOUT_SNAPSHOT_ENABLED = 'true'; process.env.PAYOUT_SNAPSHOT_ENABLED = 'true';
process.env.PAYOUT_METHOD = 'pplns'; process.env.PAYOUT_METHOD = 'pplns';
process.env.PAYOUT_WINDOW_FACTOR = '4'; process.env.PAYOUT_WINDOW_FACTOR = '4';
process.env.PAYOUT_BOOTSTRAP_WINDOW = 'false';
process.env.PAYOUT_MAX_COINBASE_OUTPUTS = '10'; process.env.PAYOUT_MAX_COINBASE_OUTPUTS = '10';
process.env.PAYOUT_MIN_OUTPUT_SATS = '546'; process.env.PAYOUT_MIN_OUTPUT_SATS = '546';
process.env.PAYOUT_FEE_PERCENT = '0'; process.env.PAYOUT_FEE_PERCENT = '0';
@@ -62,12 +63,13 @@ describe('PayoutSnapshotService', () => {
totalCreditedDifficulty: 100, totalCreditedDifficulty: 100,
totalAcceptedShareCount: '5', totalAcceptedShareCount: '5',
eligibleAddressCount: 2, eligibleAddressCount: 2,
includedOutputCount: 1, includedOutputCount: 2,
distributedSats: '1000', distributedSats: '1000',
unallocatedRemainderSats: '0', unallocatedRemainderSats: '0',
}]) }])
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ address: ADDRESS_A, payoutSats: '1000' }, { address: ADDRESS_A, payoutSats: '600' },
{ address: ADDRESS_B, payoutSats: '400' },
]); ]);
const snapshot = await service.createSnapshotForTemplate({ const snapshot = await service.createSnapshotForTemplate({
@@ -86,10 +88,67 @@ describe('PayoutSnapshotService', () => {
unallocatedRemainderSats: '0', unallocatedRemainderSats: '0',
})); }));
expect(snapshot.payoutOutputs).toEqual([ expect(snapshot.payoutOutputs).toEqual([
{ address: ADDRESS_A, amountSats: 1000, percent: 100 }, { address: ADDRESS_A, amountSats: 600, percent: 60 },
{ address: ADDRESS_B, amountSats: 400, percent: 40 },
]); ]);
expect(manager.query).toHaveBeenCalledTimes(9); expect(manager.query).toHaveBeenCalledTimes(9);
expect(manager.query.mock.calls[0][1]).toEqual([100]); expect(manager.query.mock.calls[0][1]).toEqual([100, 'pplns']);
});
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([])
.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 () => { it('should not create a snapshot when there is no finalized rollup work', async () => {
@@ -131,12 +190,13 @@ describe('PayoutSnapshotService', () => {
totalCreditedDifficulty: 100, totalCreditedDifficulty: 100,
totalAcceptedShareCount: '5', totalAcceptedShareCount: '5',
eligibleAddressCount: 2, eligibleAddressCount: 2,
includedOutputCount: 1, includedOutputCount: 2,
distributedSats: '1000', distributedSats: '1000',
unallocatedRemainderSats: '0', unallocatedRemainderSats: '0',
}]) }])
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ address: ADDRESS_A, payoutSats: '1000' }, { address: ADDRESS_A, payoutSats: '600' },
{ address: ADDRESS_B, payoutSats: '400' },
]); ]);
const snapshot = await service.createSnapshotForTemplate({ const snapshot = await service.createSnapshotForTemplate({
@@ -147,7 +207,8 @@ describe('PayoutSnapshotService', () => {
expect(snapshot.id).toBe('55'); expect(snapshot.id).toBe('55');
expect(snapshot.payoutOutputs).toEqual([ expect(snapshot.payoutOutputs).toEqual([
{ address: ADDRESS_A, amountSats: 1000, percent: 100 }, { address: ADDRESS_A, amountSats: 600, percent: 60 },
{ address: ADDRESS_B, amountSats: 400, percent: 40 },
]); ]);
expect(manager.query).toHaveBeenCalledTimes(4); expect(manager.query).toHaveBeenCalledTimes(4);
}); });
@@ -159,21 +220,21 @@ describe('PayoutSnapshotService', () => {
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ {
address: ADDRESS_A, address: ADDRESS_A,
payoutSats: '1000', payoutSats: '600',
balanceBeforeSats: '0', balanceBeforeSats: '0',
balanceAfterSats: '-400', balanceAfterSats: '0',
creditedDifficulty: 60, creditedDifficulty: 60,
includedInCoinbase: true, includedInCoinbase: true,
rowType: 'coinbase', rowType: 'coinbase',
}, },
{ {
address: ADDRESS_B, address: ADDRESS_B,
payoutSats: '0', payoutSats: '400',
balanceBeforeSats: '0', balanceBeforeSats: '0',
balanceAfterSats: '400', balanceAfterSats: '0',
creditedDifficulty: 40, creditedDifficulty: 40,
includedInCoinbase: false, includedInCoinbase: true,
rowType: 'pending', rowType: 'coinbase',
}, },
]) ])
.mockResolvedValueOnce([]) .mockResolvedValueOnce([])
@@ -210,4 +271,45 @@ describe('PayoutSnapshotService', () => {
}); });
expect(manager.query).toHaveBeenCalledTimes(2); 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();
});
}); });
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import { DataSource, EntityManager } from 'typeorm'; import { DataSource, EntityManager } from 'typeorm';
import type { AddressObject } from '../../models/MiningJob'; import type { AddressObject } from '../../models/MiningJob';
import { PayoutMode } from '../../types/payout-mode';
import { import {
buildPayoutDistribution, buildPayoutDistribution,
PayoutAddressWork, PayoutAddressWork,
@@ -23,6 +24,7 @@ export interface PayoutSnapshotForTemplate {
distributedSats: string; distributedSats: string;
unallocatedRemainderSats: string; unallocatedRemainderSats: string;
payoutOutputs: AddressObject[]; payoutOutputs: AddressObject[];
payoutMode: PayoutMode;
} }
export interface PayoutFinalizationResult { export interface PayoutFinalizationResult {
@@ -33,17 +35,36 @@ export interface PayoutFinalizationResult {
balanceRows?: 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 = 10; const DEFAULT_MAX_COINBASE_OUTPUTS = 10;
const DEFAULT_MIN_OUTPUT_SATS = 546; const DEFAULT_MIN_OUTPUT_SATS = 546;
const DEFAULT_PAYOUT_METHOD = 'pplns'; const DEFAULT_PAYOUT_METHOD = 'pplns';
const DEFAULT_PAYOUT_WINDOW_FACTOR = 4; const DEFAULT_PAYOUT_WINDOW_FACTOR = 4;
const DEFAULT_COINBASE_WEIGHT_BUDGET = 50_000; const DEFAULT_COINBASE_WEIGHT_BUDGET = 50_000;
const DEFAULT_PAYOUT_BOOTSTRAP_WINDOW = true;
const PPLNS_PAYOUT_MODE: PayoutMode = 'pplns';
@Injectable() @Injectable()
export class PayoutSnapshotService { export class PayoutSnapshotService {
private readonly snapshotsEnabled = this.readBoolean('PAYOUT_SNAPSHOT_ENABLED', true); private readonly snapshotsEnabled = this.readBoolean('PAYOUT_SNAPSHOT_ENABLED', true);
private readonly method = process.env.PAYOUT_METHOD ?? DEFAULT_PAYOUT_METHOD; private readonly method = process.env.PAYOUT_METHOD ?? DEFAULT_PAYOUT_METHOD;
private readonly windowFactor = this.readPositiveNumber('PAYOUT_WINDOW_FACTOR', DEFAULT_PAYOUT_WINDOW_FACTOR); 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 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 minOutputSats = this.readNonNegativeInt('PAYOUT_MIN_OUTPUT_SATS', DEFAULT_MIN_OUTPUT_SATS);
private readonly feeAddress = process.env.PAYOUT_FEE_ADDRESS?.trim() ?? ''; private readonly feeAddress = process.env.PAYOUT_FEE_ADDRESS?.trim() ?? '';
@@ -64,7 +85,8 @@ export class PayoutSnapshotService {
} }
return this.dataSource.transaction(async manager => { return this.dataSource.transaction(async manager => {
const windowTargetDifficulty = input.networkDifficulty * this.windowFactor; const effectiveWindowFactor = await this.getEffectiveWindowFactor(manager);
const windowTargetDifficulty = input.networkDifficulty * effectiveWindowFactor;
const window = await this.getPplnsWindow(manager, windowTargetDifficulty); const window = await this.getPplnsWindow(manager, windowTargetDifficulty);
if (window == null || this.toNumber(window.totalCreditedDifficulty) <= 0) { if (window == null || this.toNumber(window.totalCreditedDifficulty) <= 0) {
return null; return null;
@@ -107,6 +129,7 @@ export class PayoutSnapshotService {
const [snapshotRow] = await manager.query(` const [snapshotRow] = await manager.query(`
INSERT INTO "payout_snapshot" ( INSERT INTO "payout_snapshot" (
"method", "method",
"payoutMode",
"status", "status",
"blockHeight", "blockHeight",
"coinbaseValueSats", "coinbaseValueSats",
@@ -129,35 +152,37 @@ export class PayoutSnapshotService {
"unallocatedRemainderSats" "unallocatedRemainderSats"
) VALUES ( ) VALUES (
$1, $1,
$2,
'finalized', 'finalized',
$2::bigint,
$3::bigint, $3::bigint,
$4::numeric, $4::bigint,
$5::numeric, $5::numeric,
$6::numeric, $6::numeric,
NULLIF($7, ''), $7::numeric,
$8::bigint, NULLIF($8, ''),
$9::int, $9::bigint,
$10::int, $10::int,
$11::bigint, $11::int,
$12::bigint, $12::bigint,
$13::bigint, $13::bigint,
$14::bigint, $14::bigint,
$15::numeric, $15::bigint,
$16::bigint, $16::numeric,
$17::int, $17::bigint,
$18::int, $18::int,
$19::bigint, $19::int,
$20::bigint $20::bigint,
$21::bigint
) )
RETURNING "id"::text AS "id" RETURNING "id"::text AS "id"
`, [ `, [
this.method, this.method,
PPLNS_PAYOUT_MODE,
input.blockHeight, input.blockHeight,
input.coinbaseValueSats.toString(), input.coinbaseValueSats.toString(),
input.networkDifficulty, input.networkDifficulty,
windowTargetDifficulty, windowTargetDifficulty,
this.windowFactor, effectiveWindowFactor,
this.feeAddress, this.feeAddress,
distribution.feeSats.toString(), distribution.feeSats.toString(),
this.minOutputSats, this.minOutputSats,
@@ -182,14 +207,36 @@ export class PayoutSnapshotService {
}); });
} }
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: { public async finalizeSnapshotForBlock(input: {
payoutSnapshotId?: string | null; payoutSnapshotId?: string | null;
blockHeight: number; blockHeight: number;
blockSubmissionResult?: string | null; blockSubmissionResult?: string | null;
payoutMode?: PayoutMode;
}): Promise<PayoutFinalizationResult> { }): Promise<PayoutFinalizationResult> {
if (!this.snapshotsEnabled) { if (!this.snapshotsEnabled) {
return { finalized: false, reason: 'disabled' }; 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)) { if (!this.isSuccessfulBlockSubmission(input.blockSubmissionResult)) {
return { finalized: false, reason: 'missing-snapshot' }; return { finalized: false, reason: 'missing-snapshot' };
} }
@@ -202,8 +249,9 @@ export class PayoutSnapshotService {
SELECT "id"::text AS "id", "coinbaseValueSats"::text AS "coinbaseValueSats" SELECT "id"::text AS "id", "coinbaseValueSats"::text AS "coinbaseValueSats"
FROM "payout_snapshot" FROM "payout_snapshot"
WHERE "id" = $1::bigint WHERE "id" = $1::bigint
AND "payoutMode" = $2
LIMIT 1 LIMIT 1
`, [input.payoutSnapshotId]); `, [input.payoutSnapshotId, PPLNS_PAYOUT_MODE]);
if (snapshot == null) { if (snapshot == null) {
return { finalized: false, reason: 'missing-snapshot' }; return { finalized: false, reason: 'missing-snapshot' };
} }
@@ -212,8 +260,9 @@ export class PayoutSnapshotService {
SELECT "id"::text AS "id" SELECT "id"::text AS "id"
FROM "payout_history" FROM "payout_history"
WHERE "blockHeight" = $1::bigint WHERE "blockHeight" = $1::bigint
AND "payoutMode" = $2
LIMIT 1 LIMIT 1
`, [input.blockHeight]); `, [input.blockHeight, PPLNS_PAYOUT_MODE]);
if (existing != null) { if (existing != null) {
return { return {
finalized: false, finalized: false,
@@ -233,8 +282,9 @@ export class PayoutSnapshotService {
"rowType" "rowType"
FROM "payout_snapshot_entry" FROM "payout_snapshot_entry"
WHERE "snapshotId" = $1::bigint WHERE "snapshotId" = $1::bigint
AND "payoutMode" = $2
ORDER BY "rank" ORDER BY "rank"
`, [input.payoutSnapshotId]); `, [input.payoutSnapshotId, PPLNS_PAYOUT_MODE]);
if (entries.length === 0) { if (entries.length === 0) {
return { finalized: false, reason: 'missing-snapshot' }; return { finalized: false, reason: 'missing-snapshot' };
} }
@@ -283,6 +333,7 @@ export class PayoutSnapshotService {
INSERT INTO "payout_history" ( INSERT INTO "payout_history" (
"blockHeight", "blockHeight",
"payoutSnapshotId", "payoutSnapshotId",
"payoutMode",
"address", "address",
"paidSats", "paidSats",
"percent", "percent",
@@ -293,16 +344,18 @@ export class PayoutSnapshotService {
$1::bigint, $1::bigint,
$2::bigint, $2::bigint,
$3, $3,
$4::bigint, $4,
$5::numeric, $5::bigint,
$6::bigint, $6::numeric,
$7::bigint, $7::bigint,
$8 $8::bigint,
$9
) )
ON CONFLICT ("blockHeight", "address") DO NOTHING ON CONFLICT ("payoutMode", "blockHeight", "address") DO NOTHING
`, [ `, [
input.blockHeight, input.blockHeight,
input.payoutSnapshotId, input.payoutSnapshotId,
PPLNS_PAYOUT_MODE,
entry.address, entry.address,
payoutSats.toString(), payoutSats.toString(),
coinbaseValue > 0 && isCoinbase ? (payoutSats / coinbaseValue) * 100 : 0, coinbaseValue > 0 && isCoinbase ? (payoutSats / coinbaseValue) * 100 : 0,
@@ -336,15 +389,79 @@ export class PayoutSnapshotService {
SELECT "id"::text AS "id" SELECT "id"::text AS "id"
FROM "payout_snapshot" FROM "payout_snapshot"
WHERE "status" = 'finalized' WHERE "status" = 'finalized'
AND "payoutMode" = $1
ORDER BY "createdAt" DESC, "id" DESC ORDER BY "createdAt" DESC, "id" DESC
LIMIT 1 LIMIT 1
`); `, [PPLNS_PAYOUT_MODE]);
if (snapshot?.id == null) { if (snapshot?.id == null) {
return null; return null;
} }
return this.dataSource.transaction(manager => this.getSnapshotById(manager, snapshot.id)); 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<{ private async getPplnsWindow(manager: EntityManager, windowTargetDifficulty: number): Promise<{
startBatchId: string; startBatchId: string;
endBatchId: string; endBatchId: string;
@@ -370,6 +487,7 @@ export class PayoutSnapshotService {
) AS "difficultyAfter" ) AS "difficultyAfter"
FROM "share_rollup_batch" FROM "share_rollup_batch"
WHERE "status" = 'finalized' WHERE "status" = 'finalized'
AND "payoutMode" = $2
), ),
selected AS MATERIALIZED ( selected AS MATERIALIZED (
SELECT * SELECT *
@@ -384,7 +502,7 @@ export class PayoutSnapshotService {
COALESCE(SUM("creditedDifficulty"), 0)::numeric AS "totalCreditedDifficulty", COALESCE(SUM("creditedDifficulty"), 0)::numeric AS "totalCreditedDifficulty",
COALESCE(SUM("acceptedShareCount"), 0)::bigint AS "totalAcceptedShareCount" COALESCE(SUM("acceptedShareCount"), 0)::bigint AS "totalAcceptedShareCount"
FROM selected FROM selected
`, [windowTargetDifficulty]); `, [windowTargetDifficulty, PPLNS_PAYOUT_MODE]);
if (window?.startBatchId == null || window?.windowEndShareIndex == null) { if (window?.startBatchId == null || window?.windowEndShareIndex == null) {
return null; return null;
@@ -404,6 +522,8 @@ export class PayoutSnapshotService {
FROM "share_rollup_batch_summary" s FROM "share_rollup_batch_summary" s
JOIN "share_rollup_batch" b ON b."id" = s."batchId" JOIN "share_rollup_batch" b ON b."id" = s."batchId"
WHERE b."status" = 'finalized' WHERE b."status" = 'finalized'
AND b."payoutMode" = $3
AND s."payoutMode" = $3
AND b."endShareIndex" >= $1::bigint AND b."endShareIndex" >= $1::bigint
AND b."endShareIndex" <= $2::bigint AND b."endShareIndex" <= $2::bigint
GROUP BY s."address" GROUP BY s."address"
@@ -411,6 +531,7 @@ export class PayoutSnapshotService {
`, [ `, [
window.windowStartShareIndex, window.windowStartShareIndex,
window.windowEndShareIndex, window.windowEndShareIndex,
PPLNS_PAYOUT_MODE,
]); ]);
return rows.map(row => ({ return rows.map(row => ({
address: row.address, address: row.address,
@@ -439,6 +560,7 @@ export class PayoutSnapshotService {
SELECT "id"::text AS "id" SELECT "id"::text AS "id"
FROM "payout_snapshot" FROM "payout_snapshot"
WHERE "method" = $1 WHERE "method" = $1
AND "payoutMode" = $5
AND "status" = 'finalized' AND "status" = 'finalized'
AND "blockHeight" = $2::bigint AND "blockHeight" = $2::bigint
AND "coinbaseValueSats" = $3::bigint AND "coinbaseValueSats" = $3::bigint
@@ -450,6 +572,7 @@ export class PayoutSnapshotService {
input.blockHeight, input.blockHeight,
input.coinbaseValueSats.toString(), input.coinbaseValueSats.toString(),
input.windowEndShareIndex, input.windowEndShareIndex,
PPLNS_PAYOUT_MODE,
]); ]);
if (snapshot?.id == null) { if (snapshot?.id == null) {
@@ -463,6 +586,7 @@ export class PayoutSnapshotService {
SELECT SELECT
"id"::text AS "id", "id"::text AS "id",
"method", "method",
"payoutMode",
"blockHeight"::int AS "blockHeight", "blockHeight"::int AS "blockHeight",
"coinbaseValueSats"::text AS "coinbaseValueSats", "coinbaseValueSats"::text AS "coinbaseValueSats",
"windowStartShareIndex"::text AS "windowStartShareIndex", "windowStartShareIndex"::text AS "windowStartShareIndex",
@@ -475,7 +599,8 @@ export class PayoutSnapshotService {
"unallocatedRemainderSats"::text AS "unallocatedRemainderSats" "unallocatedRemainderSats"::text AS "unallocatedRemainderSats"
FROM "payout_snapshot" FROM "payout_snapshot"
WHERE "id" = $1::bigint WHERE "id" = $1::bigint
`, [id]); AND "payoutMode" = $2
`, [id, PPLNS_PAYOUT_MODE]);
if (snapshot == null) { if (snapshot == null) {
return null; return null;
} }
@@ -486,14 +611,16 @@ export class PayoutSnapshotService {
"payoutSats"::text AS "payoutSats" "payoutSats"::text AS "payoutSats"
FROM "payout_snapshot_entry" FROM "payout_snapshot_entry"
WHERE "snapshotId" = $1::bigint WHERE "snapshotId" = $1::bigint
AND "payoutMode" = $2
AND "includedInCoinbase" = true AND "includedInCoinbase" = true
ORDER BY "rank" ORDER BY "rank"
`, [id]); `, [id, PPLNS_PAYOUT_MODE]);
const coinbaseValue = Number(snapshot.coinbaseValueSats); const coinbaseValue = Number(snapshot.coinbaseValueSats);
return { return {
id: snapshot.id, id: snapshot.id,
method: snapshot.method, method: snapshot.method,
payoutMode: snapshot.payoutMode,
blockHeight: this.toNumber(snapshot.blockHeight), blockHeight: this.toNumber(snapshot.blockHeight),
coinbaseValueSats: snapshot.coinbaseValueSats, coinbaseValueSats: snapshot.coinbaseValueSats,
windowStartShareIndex: snapshot.windowStartShareIndex, windowStartShareIndex: snapshot.windowStartShareIndex,
@@ -518,6 +645,7 @@ export class PayoutSnapshotService {
await manager.query(` await manager.query(`
INSERT INTO "payout_snapshot_entry" ( INSERT INTO "payout_snapshot_entry" (
"snapshotId", "snapshotId",
"payoutMode",
"address", "address",
"creditedDifficulty", "creditedDifficulty",
"acceptedShareCount", "acceptedShareCount",
@@ -532,19 +660,21 @@ export class PayoutSnapshotService {
) VALUES ( ) VALUES (
$1::bigint, $1::bigint,
$2, $2,
$3::numeric, $3,
$4::bigint, $4::numeric,
$5::numeric, $5::bigint,
$6::bigint, $6::numeric,
$7::bigint, $7::bigint,
$8::bigint, $8::bigint,
$9::bigint, $9::bigint,
$10::boolean, $10::bigint,
$11, $11::boolean,
$12::int $12,
$13::int
) )
`, [ `, [
snapshotId, snapshotId,
PPLNS_PAYOUT_MODE,
entry.address, entry.address,
entry.creditedDifficulty, entry.creditedDifficulty,
entry.acceptedShareCount, entry.acceptedShareCount,
@@ -561,7 +691,8 @@ export class PayoutSnapshotService {
private limitCoinbaseOutputs(entries: PayoutDistributionEntry[]): PayoutDistributionEntry[] { private limitCoinbaseOutputs(entries: PayoutDistributionEntry[]): PayoutDistributionEntry[] {
let included = 0; let included = 0;
return entries.map(entry => { let removedPayoutSats = 0;
const limitedEntries = entries.map(entry => {
if (!entry.includedInCoinbase) { if (!entry.includedInCoinbase) {
return entry; return entry;
} }
@@ -569,6 +700,7 @@ export class PayoutSnapshotService {
if (included <= this.maxCoinbaseOutputs) { if (included <= this.maxCoinbaseOutputs) {
return entry; return entry;
} }
removedPayoutSats += entry.payoutSats;
return { return {
...entry, ...entry,
payoutSats: 0, payoutSats: 0,
@@ -576,6 +708,43 @@ export class PayoutSnapshotService {
includedInCoinbase: false, 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 { private isSuccessfulBlockSubmission(result?: string | null): boolean {
@@ -3,11 +3,12 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity'; import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity';
import { ShareAccountingService } from './share-accounting.service'; import { ShareAccountingService } from './share-accounting.service';
import { ShareHighScoreService } from './share-high-score.service';
@Global() @Global()
@Module({ @Module({
imports: [TypeOrmModule.forFeature([AcceptedShareEntity])], imports: [TypeOrmModule.forFeature([AcceptedShareEntity])],
providers: [ShareAccountingService], providers: [ShareAccountingService, ShareHighScoreService],
exports: [TypeOrmModule, ShareAccountingService], exports: [TypeOrmModule, ShareAccountingService, ShareHighScoreService],
}) })
export class ShareAccountingModule { } export class ShareAccountingModule { }
@@ -48,6 +48,7 @@ describe('ShareAccountingService', () => {
expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({
acceptedAt, acceptedAt,
payoutMode: 'solo',
nonce: '123', nonce: '123',
ntime: '456', ntime: '456',
version: '536870912', version: '536870912',
@@ -55,10 +56,54 @@ describe('ShareAccountingService', () => {
})); }));
expect(repository.insert).toHaveBeenCalledWith([expect.objectContaining({ expect(repository.insert).toHaveBeenCalledWith([expect.objectContaining({
protocol: 'sv1', protocol: 'sv1',
payoutMode: 'solo',
creditedDifficulty: 1024, 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 () => { it('should accept TLS SV1 protocol labels for accounting', async () => {
const repository = { const repository = {
create: jest.fn(value => value), create: jest.fn(value => value),
@@ -295,7 +340,8 @@ describe('ShareAccountingService', () => {
currentRoundAcceptedShares: '11', currentRoundAcceptedShares: '11',
workSinceLastBlock: '352', workSinceLastBlock: '352',
currentRoundNetworkDifficulty: '1000', currentRoundNetworkDifficulty: '1000',
}]), }])
.mockResolvedValueOnce([]),
}; };
const service = new ShareAccountingService(repository as any, redis as any); const service = new ShareAccountingService(repository as any, redis as any);
@@ -314,12 +360,55 @@ describe('ShareAccountingService', () => {
expect(repository.query).toHaveBeenNthCalledWith( expect(repository.query).toHaveBeenNthCalledWith(
2, 2,
expect.stringContaining('FROM "accepted_share_block_10m"'), 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(repository.query).not.toHaveBeenCalledWith(
expect.stringContaining('FROM "accepted_share_entity"'), 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 () => { it('should cache accounting summaries briefly to protect hot dashboard endpoints', async () => {
process.env.SHARE_ACCOUNTING_SUMMARY_CACHE_MS = '1000'; process.env.SHARE_ACCOUNTING_SUMMARY_CACHE_MS = '1000';
const repository = { const repository = {
@@ -370,6 +459,7 @@ describe('ShareAccountingService', () => {
await expect(service.processPendingShareRollupBatch()).resolves.toEqual({ await expect(service.processPendingShareRollupBatch()).resolves.toEqual({
processed: true, processed: true,
payoutMode: 'pplns',
batchId: '7', batchId: '7',
startShareIndex: '11', startShareIndex: '11',
endShareIndex: '20', endShareIndex: '20',
@@ -386,7 +476,7 @@ describe('ShareAccountingService', () => {
expect(manager.query).toHaveBeenNthCalledWith( expect(manager.query).toHaveBeenNthCalledWith(
6, 6,
expect.stringContaining('INSERT INTO "share_rollup_batch_summary"'), expect.stringContaining('INSERT INTO "share_rollup_batch_summary"'),
['7', '11', '20'], ['7', '11', '20', 'pplns'],
); );
}); });
@@ -4,9 +4,11 @@ import { Repository } from 'typeorm';
import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity'; import { AcceptedShareEntity } from '../accepted-share/accepted-share.entity';
import { RedisMessagingService } from '../../services/redis-messaging.service'; import { RedisMessagingService } from '../../services/redis-messaging.service';
import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
export interface AcceptedShareRecord { export interface AcceptedShareRecord {
protocol: 'sv1' | 'sv1_tls' | 'sv2' | 'sv2_jdp' | 'datum'; protocol: 'sv1' | 'sv1_tls' | 'sv2' | 'sv2_jdp' | 'datum';
payoutMode?: PayoutMode;
workSource?: 'pool_template' | 'miner_template'; workSource?: 'pool_template' | 'miner_template';
workProtocol?: 'pool' | 'sv2_jdp' | 'datum'; workProtocol?: 'pool' | 'sv2_jdp' | 'datum';
acceptedAt?: Date; acceptedAt?: Date;
@@ -64,6 +66,7 @@ export interface SessionShareSummary {
export interface ShareRollupBatchResult { export interface ShareRollupBatchResult {
processed: boolean; processed: boolean;
reason?: 'disabled' | 'locked' | 'no-shares'; reason?: 'disabled' | 'locked' | 'no-shares';
payoutMode?: PayoutMode;
batchId?: string; batchId?: string;
startShareIndex?: string; startShareIndex?: string;
endShareIndex?: string; endShareIndex?: string;
@@ -75,6 +78,7 @@ interface AccountingFilter {
address?: string; address?: string;
clientName?: string; clientName?: string;
clientId?: string; clientId?: string;
payoutMode?: PayoutMode;
} }
const HASHES_PER_DIFFICULTY = 4294967296; const HASHES_PER_DIFFICULTY = 4294967296;
@@ -123,6 +127,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
public async recordAcceptedShare(record: AcceptedShareRecord): Promise<AcceptedShareEntity> { public async recordAcceptedShare(record: AcceptedShareRecord): Promise<AcceptedShareEntity> {
const acceptedShare = this.acceptedShareRepository.create({ const acceptedShare = this.acceptedShareRepository.create({
...record, ...record,
payoutMode: normalizePayoutMode(record.payoutMode),
workSource: record.workSource ?? 'pool_template', workSource: record.workSource ?? 'pool_template',
workProtocol: record.workProtocol ?? 'pool', workProtocol: record.workProtocol ?? 'pool',
acceptedAt: record.acceptedAt ?? new Date(), acceptedAt: record.acceptedAt ?? new Date(),
@@ -186,11 +191,13 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
return { processed: false, reason: 'locked' }; return { processed: false, reason: 'locked' };
} }
const payoutMode: PayoutMode = 'pplns';
const [lastRow] = await manager.query(` const [lastRow] = await manager.query(`
SELECT COALESCE(MAX("endShareIndex"), 0)::text AS "lastProcessedShareIndex" SELECT COALESCE(MAX("endShareIndex"), 0)::text AS "lastProcessedShareIndex"
FROM "share_rollup_batch" FROM "share_rollup_batch"
WHERE "status" = 'finalized' WHERE "status" = 'finalized'
`); AND "payoutMode" = $1
`, [payoutMode]);
const lastProcessedShareIndex = lastRow?.lastProcessedShareIndex ?? '0'; const lastProcessedShareIndex = lastRow?.lastProcessedShareIndex ?? '0';
const [rangeRow] = await manager.query(` const [rangeRow] = await manager.query(`
@@ -201,6 +208,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
SELECT MIN("shareIndex") AS "firstUnstableShareIndex" SELECT MIN("shareIndex") AS "firstUnstableShareIndex"
FROM "accepted_share_entity", last_state FROM "accepted_share_entity", last_state
WHERE "shareIndex" > last_state."lastProcessedShareIndex" WHERE "shareIndex" > last_state."lastProcessedShareIndex"
AND "payoutMode" = $4
AND "acceptedAt" > NOW() - ($2::int * INTERVAL '1 second') AND "acceptedAt" > NOW() - ($2::int * INTERVAL '1 second')
), ),
stable_bound AS MATERIALIZED ( stable_bound AS MATERIALIZED (
@@ -210,6 +218,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
SELECT MAX("shareIndex") SELECT MAX("shareIndex")
FROM "accepted_share_entity", last_state FROM "accepted_share_entity", last_state
WHERE "shareIndex" > last_state."lastProcessedShareIndex" WHERE "shareIndex" > last_state."lastProcessedShareIndex"
AND "payoutMode" = $4
) )
ELSE (SELECT "firstUnstableShareIndex" FROM first_unstable) - 1 ELSE (SELECT "firstUnstableShareIndex" FROM first_unstable) - 1
END AS "maxStableShareIndex" END AS "maxStableShareIndex"
@@ -219,6 +228,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
FROM "accepted_share_entity", last_state, stable_bound FROM "accepted_share_entity", last_state, stable_bound
WHERE "shareIndex" > last_state."lastProcessedShareIndex" WHERE "shareIndex" > last_state."lastProcessedShareIndex"
AND "shareIndex" <= stable_bound."maxStableShareIndex" AND "shareIndex" <= stable_bound."maxStableShareIndex"
AND "payoutMode" = $4
ORDER BY "shareIndex" ASC ORDER BY "shareIndex" ASC
LIMIT $3::int LIMIT $3::int
) )
@@ -231,6 +241,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
lastProcessedShareIndex, lastProcessedShareIndex,
this.shareRollupSafetyLagSeconds, this.shareRollupSafetyLagSeconds,
this.shareRollupMaxSharesPerBatch, this.shareRollupMaxSharesPerBatch,
payoutMode,
]); ]);
if (rangeRow?.startShareIndex == null || rangeRow?.endShareIndex == null || this.toNumber(rangeRow.acceptedShareCount) === 0) { if (rangeRow?.startShareIndex == null || rangeRow?.endShareIndex == null || this.toNumber(rangeRow.acceptedShareCount) === 0) {
@@ -246,7 +257,8 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
FROM "accepted_share_entity" FROM "accepted_share_entity"
WHERE "shareIndex" >= $1::bigint WHERE "shareIndex" >= $1::bigint
AND "shareIndex" <= $2::bigint AND "shareIndex" <= $2::bigint
`, [rangeRow.startShareIndex, rangeRow.endShareIndex]); AND "payoutMode" = $3
`, [rangeRow.startShareIndex, rangeRow.endShareIndex, payoutMode]);
if (statsRow?.startAcceptedAt == null || this.toNumber(statsRow.acceptedShareCount) === 0) { if (statsRow?.startAcceptedAt == null || this.toNumber(statsRow.acceptedShareCount) === 0) {
return { processed: false, reason: 'no-shares' }; return { processed: false, reason: 'no-shares' };
@@ -256,6 +268,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
INSERT INTO "share_rollup_batch" ( INSERT INTO "share_rollup_batch" (
"startShareIndex", "startShareIndex",
"endShareIndex", "endShareIndex",
"payoutMode",
"startAcceptedAt", "startAcceptedAt",
"endAcceptedAt", "endAcceptedAt",
"acceptedShareCount", "acceptedShareCount",
@@ -265,10 +278,11 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
) VALUES ( ) VALUES (
$1::bigint, $1::bigint,
$2::bigint, $2::bigint,
$3::timestamptz, $3,
$4::timestamptz, $4::timestamptz,
$5::bigint, $5::timestamptz,
$6::numeric, $6::bigint,
$7::numeric,
'finalized', 'finalized',
NOW() NOW()
) )
@@ -276,6 +290,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
`, [ `, [
rangeRow.startShareIndex, rangeRow.startShareIndex,
rangeRow.endShareIndex, rangeRow.endShareIndex,
payoutMode,
statsRow.startAcceptedAt, statsRow.startAcceptedAt,
statsRow.endAcceptedAt, statsRow.endAcceptedAt,
statsRow.acceptedShareCount, statsRow.acceptedShareCount,
@@ -285,6 +300,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
await manager.query(` await manager.query(`
INSERT INTO "share_rollup_batch_summary" ( INSERT INTO "share_rollup_batch_summary" (
"batchId", "batchId",
"payoutMode",
"address", "address",
"clientName", "clientName",
"protocol", "protocol",
@@ -297,6 +313,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
) )
SELECT SELECT
$1::bigint AS "batchId", $1::bigint AS "batchId",
"payoutMode",
"address", "address",
"clientName", "clientName",
"protocol", "protocol",
@@ -309,15 +326,18 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
FROM "accepted_share_entity" FROM "accepted_share_entity"
WHERE "shareIndex" >= $2::bigint WHERE "shareIndex" >= $2::bigint
AND "shareIndex" <= $3::bigint AND "shareIndex" <= $3::bigint
GROUP BY "address", "clientName", "protocol", "blockHeight" AND "payoutMode" = $4
GROUP BY "payoutMode", "address", "clientName", "protocol", "blockHeight"
`, [ `, [
batchRow.batchId, batchRow.batchId,
rangeRow.startShareIndex, rangeRow.startShareIndex,
rangeRow.endShareIndex, rangeRow.endShareIndex,
payoutMode,
]); ]);
return { return {
processed: true, processed: true,
payoutMode,
batchId: batchRow.batchId, batchId: batchRow.batchId,
startShareIndex: rangeRow.startShareIndex, startShareIndex: rangeRow.startShareIndex,
endShareIndex: rangeRow.endShareIndex, endShareIndex: rangeRow.endShareIndex,
@@ -327,9 +347,11 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
}); });
} }
public async getPoolSummary(): Promise<ShareAccountingSummary> { 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 const cached = await this.redisMessagingService
?.getJsonCache<ShareAccountingSummary>(this.poolSummaryCacheKey) ?.getJsonCache<ShareAccountingSummary>(poolSummaryCacheKey)
.catch(error => { .catch(error => {
console.error(`Pool accounting summary cache read failed: ${error.message}`); console.error(`Pool accounting summary cache read failed: ${error.message}`);
return null; return null;
@@ -342,20 +364,22 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
return this.emptySummary(); return this.emptySummary();
} }
return this.getSummary({}); return this.getSummary({ payoutMode: mode });
} }
public async refreshPoolSummary(): Promise<ShareAccountingSummary> { public async refreshPoolSummary(payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
const summary = await this.withPoolRollupOverlay(await this.getSummary({})); 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 await this.redisMessagingService
?.setJsonCache(this.poolSummaryCacheKey, summary, 10 * 60 * 1000) ?.setJsonCache(poolSummaryCacheKey, summary, 10 * 60 * 1000)
.catch(error => { .catch(error => {
console.error(`Pool accounting summary cache write failed: ${error.message}`); console.error(`Pool accounting summary cache write failed: ${error.message}`);
}); });
return summary; return summary;
} }
private async withPoolRollupOverlay(summary: ShareAccountingSummary): Promise<ShareAccountingSummary> { private async withPoolRollupOverlay(summary: ShareAccountingSummary, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
if (process.env.API_ONLY === 'true') { if (process.env.API_ONLY === 'true') {
return summary; return summary;
} }
@@ -364,11 +388,13 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
WITH latest_found_block AS ( WITH latest_found_block AS (
SELECT COALESCE(MAX("height"), 0) AS "height" SELECT COALESCE(MAX("height"), 0) AS "height"
FROM "blocks_entity" FROM "blocks_entity"
${payoutMode == null ? '' : 'WHERE "payoutMode" = $1'}
), ),
filtered_rows AS ( filtered_rows AS (
SELECT "accepted_share_block_10m".* SELECT "accepted_share_block_10m".*
FROM "accepted_share_block_10m", latest_found_block FROM "accepted_share_block_10m", latest_found_block
WHERE "blockHeight" > latest_found_block."height" WHERE "blockHeight" > latest_found_block."height"
${payoutMode == null ? '' : 'AND "payoutMode" = $1'}
), ),
best_share AS ( best_share AS (
SELECT SELECT
@@ -384,17 +410,26 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
COALESCE(MAX("networkDifficulty"), 0)::float AS "currentRoundNetworkDifficulty", COALESCE(MAX("networkDifficulty"), 0)::float AS "currentRoundNetworkDifficulty",
COALESCE((SELECT "bestSubmissionDifficulty" FROM best_share), 0)::float AS "bestSubmissionDifficulty", COALESCE((SELECT "bestSubmissionDifficulty" FROM best_share), 0)::float AS "bestSubmissionDifficulty",
(SELECT "bucket" FROM best_share) AS "bestSubmissionDifficultyAt" (SELECT "bucket" FROM best_share) AS "bestSubmissionDifficultyAt"
FROM filtered_rows FROM filtered_rows
`); `, payoutMode == null ? [] : [payoutMode]);
const currentRoundNetworkDifficulty = this.toNumber(currentRoundRow?.currentRoundNetworkDifficulty); const currentRoundNetworkDifficulty = this.toNumber(currentRoundRow?.currentRoundNetworkDifficulty);
const workSinceLastBlock = this.toNumber(currentRoundRow?.workSinceLastBlock); 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 { return {
...summary, ...summary,
bestSubmissionDifficulty: this.toNumber(currentRoundRow?.bestSubmissionDifficulty), bestSubmissionDifficulty: useRetainedBest
bestSubmissionDifficultyAt: currentRoundRow?.bestSubmissionDifficultyAt == null ? retainedBestSubmissionDifficulty
? null : liveBestSubmissionDifficulty,
: new Date(currentRoundRow.bestSubmissionDifficultyAt).toISOString(), bestSubmissionDifficultyAt: useRetainedBest
? retainedBest?.bestSubmissionDifficultyAt ?? null
: liveBestSubmissionDifficultyAt,
workSinceLastBlock, workSinceLastBlock,
currentRoundAcceptedShares: this.toNumber(currentRoundRow?.currentRoundAcceptedShares), currentRoundAcceptedShares: this.toNumber(currentRoundRow?.currentRoundAcceptedShares),
currentRoundNetworkDifficulty, currentRoundNetworkDifficulty,
@@ -404,6 +439,40 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
}; };
} }
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 { public emptySummary(): ShareAccountingSummary {
return { return {
totalAcceptedShares: 0, totalAcceptedShares: 0,
@@ -428,16 +497,16 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
}; };
} }
public async getAddressSummary(address: string): Promise<ShareAccountingSummary> { public async getAddressSummary(address: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
return this.getSummary({ address }); return this.getSummary({ address, payoutMode });
} }
public async getWorkerGroupSummary(address: string, clientName: string): Promise<ShareAccountingSummary> { public async getWorkerGroupSummary(address: string, clientName: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
return this.getSummary({ address, clientName }); return this.getSummary({ address, clientName, payoutMode });
} }
public async getSessionSummary(clientId: string): Promise<ShareAccountingSummary> { public async getSessionSummary(clientId: string, payoutMode?: PayoutMode): Promise<ShareAccountingSummary> {
return this.getSummary({ clientId }); return this.getSummary({ clientId, payoutMode });
} }
public async getSessionSummaries(clientIds: string[]): Promise<Map<string, SessionShareSummary>> { public async getSessionSummaries(clientIds: string[]): Promise<Map<string, SessionShareSummary>> {
@@ -705,6 +774,10 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
params.push(filter.clientId); params.push(filter.clientId);
where.push(`"clientId" = $${params.length}`); where.push(`"clientId" = $${params.length}`);
} }
if (filter.payoutMode != null) {
params.push(filter.payoutMode);
where.push(`"payoutMode" = $${params.length}`);
}
return { return {
whereSql: where.length > 0 ? `WHERE ${where.join(' AND ')}` : '', whereSql: where.length > 0 ? `WHERE ${where.join(' AND ')}` : '',
@@ -726,6 +799,7 @@ export class ShareAccountingService implements OnModuleInit, OnModuleDestroy {
address: filter.address ?? null, address: filter.address ?? null,
clientName: filter.clientName ?? null, clientName: filter.clientName ?? null,
clientId: filter.clientId ?? null, clientId: filter.clientId ?? null,
payoutMode: filter.payoutMode ?? null,
}); });
} }
@@ -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;
}
}
+130
View File
@@ -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',
},
]);
});
});
+84 -33
View File
@@ -1,5 +1,5 @@
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';
@@ -13,12 +13,14 @@ import { UserAgentReportView } from './ORM/_views/user-agent-report/user-agent-r
import { StratumV2Service } from './services/stratum-v2.service'; import { StratumV2Service } from './services/stratum-v2.service';
import { ShareAccountingService } from './ORM/share-accounting/share-accounting.service'; import { ShareAccountingService } from './ORM/share-accounting/share-accounting.service';
import { RedisMessagingService } from './services/redis-messaging.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 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,
@@ -37,16 +39,16 @@ export class AppController {
public async info() { public async info() {
const CACHE_KEY = 'SITE_INFO'; const CACHE_KEY = 'SITE_INFO';
const STALE_CACHE_KEY = 'SITE_INFO_STALE'; const STALE_CACHE_KEY = 'SITE_INFO_STALE';
const cachedResult = await this.getCached(CACHE_KEY, 5 * 60 * 1000); const cachedResult = await this.getCached<SiteInfoResponse>(CACHE_KEY, 5 * 60 * 1000);
if (cachedResult != null) { if (cachedResult != null) {
return cachedResult; return await this.withFreshFoundBlocks(cachedResult);
} }
const staleResult = await this.getCached<SiteInfoResponse>(STALE_CACHE_KEY, 60 * 60 * 1000); const staleResult = await this.getCached<SiteInfoResponse>(STALE_CACHE_KEY, 60 * 60 * 1000);
if (staleResult != null) { if (staleResult != null) {
void this.refreshSiteInfo(staleResult); void this.refreshSiteInfo(staleResult);
return staleResult; return await this.withFreshFoundBlocks(staleResult);
} }
return await this.refreshSiteInfo(null); return await this.refreshSiteInfo(null);
@@ -83,32 +85,7 @@ export class AppController {
withInfoTimeout<UserAgentReportView[]>('user agent report', this.userAgentReportService.getReport(), staleInfo?.userAgents ?? []), withInfoTimeout<UserAgentReportView[]>('user agent report', this.userAgentReportService.getReport(), staleInfo?.userAgents ?? []),
]); ]);
const other: { const userAgents = this.groupSmallUserAgents(userAgentReport);
count: number,
bestDifficulty: number,
totalHashRate: number;
} = {
count: 0,
bestDifficulty: 0,
totalHashRate: 0
};
const userAgents: UserAgentReportView[] = userAgentReport.reduce((pre, cur, idx, arr) => {
// 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() })
}
const data: SiteInfoResponse = { const data: SiteInfoResponse = {
blockData, blockData,
@@ -129,16 +106,71 @@ export class AppController {
return data; 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') @Get('info/accounting')
public async infoAccounting() { public async infoAccounting(@Query('payoutMode') payoutMode?: string) {
const CACHE_KEY = 'SITE_ACCOUNTING'; const mode = normalizePayoutMode(payoutMode ?? 'pplns');
const CACHE_KEY = `SITE_ACCOUNTING:${mode}`;
const cachedResult = await this.getCached(CACHE_KEY, 15 * 1000); 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(); const data = await this.shareAccountingService.getPoolSummary(mode);
//15 sec //15 sec
await this.setCached(CACHE_KEY, data, 15 * 1000); await this.setCached(CACHE_KEY, data, 15 * 1000);
@@ -200,6 +232,25 @@ export class AppController {
} }
@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> { private async getCached<T>(key: string, localTtlMs: number): Promise<T | null> {
const local = await this.cacheManager.get<T>(key); const local = await this.cacheManager.get<T>(key);
if (local != null) { if (local != null) {
@@ -3,12 +3,13 @@ import { Test, TestingModule } from '@nestjs/testing';
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 { ShareAccountingService } from '../../ORM/share-accounting/share-accounting.service';
import { RedisMessagingService } from '../../services/redis-messaging.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 addressSettingsService: { getSettings: jest.Mock };
let shareAccountingService: { let shareAccountingService: {
getAddressSummary: jest.Mock; getAddressSummary: jest.Mock;
@@ -16,7 +17,7 @@ describe('ClientController', () => {
getSessionSummary: jest.Mock; getSessionSummary: jest.Mock;
getSessionSummaries: jest.Mock; getSessionSummaries: jest.Mock;
}; };
let redisMessagingService: { getClientPresenceByAddress: jest.Mock }; let payoutSnapshotService: { getLatestExpectedPayoutForAddress: jest.Mock };
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
@@ -25,7 +26,7 @@ describe('ClientController', () => {
{ {
provide: ClientService, provide: ClientService,
useValue: { useValue: {
getByAddress: jest.fn(), getByAddress: jest.fn().mockResolvedValue([]),
getByName: jest.fn(), getByName: jest.fn(),
getBySessionId: jest.fn(), getBySessionId: jest.fn(),
}, },
@@ -54,9 +55,9 @@ describe('ClientController', () => {
}, },
}, },
{ {
provide: RedisMessagingService, provide: PayoutSnapshotService,
useValue: { useValue: {
getClientPresenceByAddress: jest.fn().mockResolvedValue([]), getLatestExpectedPayoutForAddress: jest.fn().mockResolvedValue(null),
}, },
}, },
], ],
@@ -64,9 +65,10 @@ describe('ClientController', () => {
}).compile(); }).compile();
controller = module.get<ClientController>(ClientController); controller = module.get<ClientController>(ClientController);
clientService = module.get(ClientService);
addressSettingsService = module.get(AddressSettingsService); addressSettingsService = module.get(AddressSettingsService);
shareAccountingService = module.get(ShareAccountingService); shareAccountingService = module.get(ShareAccountingService);
redisMessagingService = module.get(RedisMessagingService); payoutSnapshotService = module.get(PayoutSnapshotService);
}); });
it('should be defined', () => { it('should be defined', () => {
@@ -74,15 +76,17 @@ describe('ClientController', () => {
}); });
it('should expose the existing address best difficulty in accounting when rollup best is empty', async () => { it('should expose the existing address best difficulty in accounting when rollup best is empty', async () => {
redisMessagingService.getClientPresenceByAddress.mockResolvedValue([ clientService.getByAddress.mockResolvedValue([
{ {
clientId: '92f5302f-5e32-487e-af67-f56fd78b13c7', id: '92f5302f-5e32-487e-af67-f56fd78b13c7',
sessionId: 'abcd1234', sessionId: 'abcd1234',
clientName: 'worker', clientName: 'worker',
bestDifficulty: 64, bestDifficulty: 64,
hashRate: 1024, hashRate: 1024,
startTime: '2026-06-08T12:00:00.000Z', startTime: '2026-06-08T12:00:00.000Z',
lastSeen: '2026-06-08T12:10:00.000Z', lastSeen: '2026-06-08T12:10:00.000Z',
address: 'bc1qtest',
payoutMode: 'pplns',
}, },
]); ]);
addressSettingsService.getSettings.mockResolvedValue({ bestDifficulty: 4096 }); addressSettingsService.getSettings.mockResolvedValue({ bestDifficulty: 4096 });
@@ -100,4 +104,89 @@ describe('ClientController', () => {
}), }),
})); }));
}); });
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 () => {
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: '2026-06-08T12:10:00.000Z',
},
{
id: 'solo-client',
address: 'bc1qtest',
sessionId: 'solo1',
clientName: 'solo-worker',
payoutMode: 'solo',
bestDifficulty: 128,
hashRate: 2048,
startTime: '2026-06-08T12:00:00.000Z',
updatedAt: '2026-06-08T12:10:00.000Z',
},
]);
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,
},
],
});
});
}); });
+67 -18
View File
@@ -1,10 +1,11 @@
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 { ShareAccountingService } from '../../ORM/share-accounting/share-accounting.service';
import { RedisMessagingService } from '../../services/redis-messaging.service'; import { normalizePayoutMode, PayoutMode } from '../../types/payout-mode';
@Controller('client') @Controller('client')
@@ -15,13 +16,14 @@ export class ClientController {
private readonly clientStatisticsService: ClientStatisticsService, private readonly clientStatisticsService: ClientStatisticsService,
private readonly addressSettingsService: AddressSettingsService, private readonly addressSettingsService: AddressSettingsService,
private readonly shareAccountingService: ShareAccountingService, private readonly shareAccountingService: ShareAccountingService,
private readonly redisMessagingService: RedisMessagingService 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 workers = await this.redisMessagingService.getClientPresenceByAddress(address); const mode = this.getRequestedPayoutMode(payoutMode);
const workers = await this.getActiveAddressWorkers(address, mode);
const sessionSummaries = await this.shareAccountingService.getSessionSummaries(workers.map(worker => worker.clientId)); const sessionSummaries = await this.shareAccountingService.getSessionSummaries(workers.map(worker => worker.clientId));
const addressSettings = process.env.API_ONLY === 'true' const addressSettings = process.env.API_ONLY === 'true'
@@ -30,15 +32,19 @@ export class ClientController {
const bestDifficulty = addressSettings?.bestDifficulty ?? workers.reduce((best, worker) => { const bestDifficulty = addressSettings?.bestDifficulty ?? workers.reduce((best, worker) => {
return Math.max(best, Number(worker.bestDifficulty ?? 0)); return Math.max(best, Number(worker.bestDifficulty ?? 0));
}, 0); }, 0);
const accounting = this.withBestSubmissionDifficulty( const accountingSummary = mode == null
await this.shareAccountingService.getAddressSummary(address), ? await this.shareAccountingService.getAddressSummary(address)
bestDifficulty, : await this.shareAccountingService.getAddressSummary(address, mode);
); const accounting = this.withBestSubmissionDifficulty(accountingSummary, bestDifficulty);
const expectedPayout = mode === 'solo'
? null
: await this.payoutSnapshotService.getLatestExpectedPayoutForAddress(address);
const response = { const response = {
bestDifficulty, bestDifficulty,
workersCount: workers.length, workersCount: workers.length,
accounting, 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 sessionSummary = sessionSummaries.get(worker.clientId);
@@ -49,6 +55,7 @@ export class ClientController {
return { return {
sessionId: worker.sessionId, sessionId: worker.sessionId,
name: worker.clientName, name: worker.clientName,
payoutMode: worker.payoutMode,
bestDifficulty: bestDifficulty.toFixed(2), bestDifficulty: bestDifficulty.toFixed(2),
hashRate: sessionSummary?.hashRateLast10Minutes ?? worker.hashRate, hashRate: sessionSummary?.hashRateLast10Minutes ?? worker.hashRate,
startTime: worker.startTime, startTime: worker.startTime,
@@ -65,9 +72,16 @@ export class ClientController {
return await this.clientStatisticsService.getChartDataForAddress(address); return await this.clientStatisticsService.getChartDataForAddress(address);
} }
@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 addressWorkers = await this.redisMessagingService.getClientPresenceByAddress(address); const mode = this.getRequestedPayoutMode(payoutMode);
const addressWorkers = await this.getActiveAddressWorkers(address, mode);
const workers = addressWorkers const workers = addressWorkers
.filter(worker => worker.clientName === workerName); .filter(worker => worker.clientName === workerName);
@@ -79,24 +93,28 @@ export class ClientController {
}, 0); }, 0);
const chartData = await this.clientStatisticsService.getChartDataForGroup(address, workerName); const chartData = await this.clientStatisticsService.getChartDataForGroup(address, workerName);
const accounting = this.withBestSubmissionDifficulty( const chartDataByPayoutMode = await this.clientStatisticsService.getChartDataForGroupByPayoutMode(address, workerName, mode);
await this.shareAccountingService.getWorkerGroupSummary(address, workerName), const accountingSummary = mode == null
bestDifficulty, ? await this.shareAccountingService.getWorkerGroupSummary(address, workerName)
); : await this.shareAccountingService.getWorkerGroupSummary(address, workerName, mode);
const accounting = this.withBestSubmissionDifficulty(accountingSummary, bestDifficulty);
const response = { const response = {
name: workerName, name: workerName,
bestDifficulty: Math.floor(bestDifficulty), bestDifficulty: Math.floor(bestDifficulty),
payoutModes: [...new Set(workers.map(worker => worker.payoutMode))],
accounting, accounting,
chartData: chartData, chartData: chartData,
chartDataByPayoutMode,
} }
return response; 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 addressWorkers = await this.redisMessagingService.getClientPresenceByAddress(address); const mode = this.getRequestedPayoutMode(payoutMode);
const addressWorkers = await this.getActiveAddressWorkers(address, mode);
const presenceWorker = addressWorkers const presenceWorker = addressWorkers
.find(worker => worker.clientName === workerName && worker.sessionId === sessionId); .find(worker => worker.clientName === workerName && worker.sessionId === sessionId);
const worker = presenceWorker == null const worker = presenceWorker == null
@@ -106,14 +124,18 @@ export class ClientController {
sessionId: presenceWorker.sessionId, sessionId: presenceWorker.sessionId,
clientName: presenceWorker.clientName, clientName: presenceWorker.clientName,
bestDifficulty: presenceWorker.bestDifficulty, bestDifficulty: presenceWorker.bestDifficulty,
payoutMode: presenceWorker.payoutMode,
startTime: presenceWorker.startTime, startTime: presenceWorker.startTime,
}; };
if (worker == null) { if (worker == null) {
return new NotFoundException(); return new NotFoundException();
} }
const chartData = await this.clientStatisticsService.getChartDataForSession(worker.id); const chartData = await this.clientStatisticsService.getChartDataForSession(worker.id);
const chartDataByPayoutMode = await this.clientStatisticsService.getChartDataForSessionByPayoutMode(worker.id, mode);
const accounting = this.withBestSubmissionDifficulty( const accounting = this.withBestSubmissionDifficulty(
await this.shareAccountingService.getSessionSummary(worker.id), mode == null
? await this.shareAccountingService.getSessionSummary(worker.id)
: await this.shareAccountingService.getSessionSummary(worker.id, mode),
worker.bestDifficulty, worker.bestDifficulty,
); );
@@ -121,8 +143,10 @@ export class ClientController {
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, accounting,
chartData: chartData, chartData: chartData,
chartDataByPayoutMode,
startTime: worker.startTime startTime: worker.startTime
} }
return response; return response;
@@ -144,4 +168,29 @@ export class ClientController {
bestSubmissionDifficulty: fallback, 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);
return workers
.filter(worker => payoutMode == null || worker.payoutMode === payoutMode)
.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),
}));
}
} }
+6
View File
@@ -14,6 +14,9 @@ import { AcceptedShareRetentionCompression1780966200000 } from './ORM/_migration
import { PayoutSnapshots1780969800000 } from './ORM/_migrations/PayoutSnapshots1780969800000'; import { PayoutSnapshots1780969800000 } from './ORM/_migrations/PayoutSnapshots1780969800000';
import { AcceptedShareProtocolMetadata1781130600000 } from './ORM/_migrations/AcceptedShareProtocolMetadata1781130600000'; import { AcceptedShareProtocolMetadata1781130600000 } from './ORM/_migrations/AcceptedShareProtocolMetadata1781130600000';
import { BlocksSubmissionMetadata1781220000000 } from './ORM/_migrations/BlocksSubmissionMetadata1781220000000'; 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 { UserAgentReportView } from './ORM/_views/user-agent-report/user-agent-report.view'; import { UserAgentReportView } from './ORM/_views/user-agent-report/user-agent-report.view';
import { AcceptedShareEntity } from './ORM/accepted-share/accepted-share.entity'; import { AcceptedShareEntity } from './ORM/accepted-share/accepted-share.entity';
import { AddressSettingsEntity } from './ORM/address-settings/address-settings.entity'; import { AddressSettingsEntity } from './ORM/address-settings/address-settings.entity';
@@ -54,6 +57,9 @@ export const databaseMigrations = [
PayoutSnapshots1780969800000, PayoutSnapshots1780969800000,
AcceptedShareProtocolMetadata1781130600000, AcceptedShareProtocolMetadata1781130600000,
BlocksSubmissionMetadata1781220000000, BlocksSubmissionMetadata1781220000000,
PayoutModes1781300000000,
ShareRollupStoragePolicy1781305000000,
AcceptedShareHighScores1781309000000,
]; ];
export function createDatabaseOptions(env: NodeJS.ProcessEnv): TypeOrmModuleOptions & DataSourceOptions { export function createDatabaseOptions(env: NodeJS.ProcessEnv): TypeOrmModuleOptions & DataSourceOptions {
+10 -20
View File
@@ -41,7 +41,7 @@ describe('StratumV1Client', () => {
let configService: ConfigService; let configService: ConfigService;
let addressSettings: AddressSettingsService; let addressSettings: AddressSettingsService;
let shareAccountingService: { recordAcceptedShare: jest.Mock }; let shareAccountingService: { recordAcceptedShare: jest.Mock };
let redisMessagingService: { setClientPresence: jest.Mock; removeClientPresence: jest.Mock }; let redisMessagingService: Record<string, never>;
let client: StratumV1Client; let client: StratumV1Client;
@@ -80,6 +80,7 @@ describe('StratumV1Client', () => {
}), }),
connectedClientCount: jest.fn(async () => clients.size), connectedClientCount: jest.fn(async () => clients.size),
updateBestDifficultyIfHigher: jest.fn().mockResolvedValue({ affected: 1 }), updateBestDifficultyIfHigher: jest.fn().mockResolvedValue({ affected: 1 }),
updateHashRate: jest.fn().mockResolvedValue(undefined),
} as any; } as any;
configService = { configService = {
@@ -132,10 +133,7 @@ describe('StratumV1Client', () => {
shareAccountingService = { shareAccountingService = {
recordAcceptedShare: jest.fn().mockResolvedValue(undefined), recordAcceptedShare: jest.fn().mockResolvedValue(undefined),
}; };
redisMessagingService = { redisMessagingService = {};
setClientPresence: jest.fn().mockResolvedValue(undefined),
removeClientPresence: jest.fn().mockResolvedValue(undefined),
};
client = new StratumV1Client( client = new StratumV1Client(
@@ -185,11 +183,6 @@ describe('StratumV1Client', () => {
await Promise.all([client.destroy(), client.destroy()]); await Promise.all([client.destroy(), client.destroy()]);
expect(redisMessagingService.removeClientPresence).toHaveBeenCalledTimes(1);
expect(redisMessagingService.removeClientPresence).toHaveBeenCalledWith(
'00000000-0000-4000-8000-000000000001',
'tb1qcleanup',
);
expect(clientService.delete).toHaveBeenCalledTimes(1); expect(clientService.delete).toHaveBeenCalledTimes(1);
expect(clientService.delete).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000001'); expect(clientService.delete).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000001');
expect(unsubscribe).toHaveBeenCalledTimes(1); expect(unsubscribe).toHaveBeenCalledTimes(1);
@@ -415,13 +408,6 @@ describe('StratumV1Client', () => {
creditedDifficulty: 0, creditedDifficulty: 0,
isBlockCandidate: false, isBlockCandidate: false,
})); }));
expect(redisMessagingService.setClientPresence).toHaveBeenCalledWith(expect.objectContaining({
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
clientName: 'bitaxe3',
sessionId: MockRecording1.EXTRA_NONCE,
}));
}); });
it('should use the header-only fast path for non-block submissions', async () => { it('should use the header-only fast path for non-block submissions', async () => {
@@ -547,8 +533,9 @@ describe('StratumV1Client', () => {
await new Promise((r) => setTimeout(r, 100)); await new Promise((r) => setTimeout(r, 100));
expect((client as any).write).lastCalledWith(`{"id":5,"result":null,"error":[21,"Job not found",""]}\n`); expect((client as any).write).lastCalledWith(`{"id":5,"result":null,"error":[21,"Job not found",""]}\n`);
expect(await clientService.connectedClientCount()).toBe(0); expect(await clientService.connectedClientCount()).toBe(1);
expect(hashSpy).not.toHaveBeenCalled(); expect(hashSpy).not.toHaveBeenCalled();
expect(shareAccountingService.recordAcceptedShare).not.toHaveBeenCalled();
}); });
it('should reject submissions when the job template has expired', async () => { it('should reject submissions when the job template has expired', async () => {
@@ -578,7 +565,8 @@ describe('StratumV1Client', () => {
await new Promise((r) => setTimeout(r, 100)); await new Promise((r) => setTimeout(r, 100));
expect((client as any).write).lastCalledWith(`{"id":5,"result":null,"error":[23,"Difficulty too low",""]}\n`); expect((client as any).write).lastCalledWith(`{"id":5,"result":null,"error":[23,"Difficulty too low",""]}\n`);
expect(await clientService.connectedClientCount()).toBe(0); expect(await clientService.connectedClientCount()).toBe(1);
expect(shareAccountingService.recordAcceptedShare).not.toHaveBeenCalled();
}); });
it('should reject submissions with short extranonce2 values', async () => { it('should reject submissions with short extranonce2 values', async () => {
@@ -670,7 +658,9 @@ describe('StratumV1Client', () => {
minerAddress: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', minerAddress: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
worker: 'bitaxe3', worker: 'bitaxe3',
sessionId: MockRecording1.EXTRA_NONCE, sessionId: MockRecording1.EXTRA_NONCE,
blockData: expect.any(String) blockData: expect.any(String),
payoutSnapshotId: null,
payoutMode: 'solo',
})); }));
expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalled(); expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalled();
expect(addressSettings.resetBestDifficultyAndShares).toHaveBeenCalled(); expect(addressSettings.resetBestDifficultyAndShares).toHaveBeenCalled();
+54 -34
View File
@@ -19,6 +19,7 @@ import { RedisMessagingService } from '../services/redis-messaging.service';
import { IJobTemplate, StratumV1JobsService } from '../services/stratum-v1-jobs.service'; import { IJobTemplate, StratumV1JobsService } from '../services/stratum-v1-jobs.service';
import { DifficultyUtils } from '../utils/difficulty.utils'; import { DifficultyUtils } from '../utils/difficulty.utils';
import { hash256 } from '../utils/hash.utils'; import { hash256 } from '../utils/hash.utils';
import { PayoutMode } from '../types/payout-mode';
import { eRequestMethod } from './enums/eRequestMethod'; import { eRequestMethod } from './enums/eRequestMethod';
import { eResponseMethod } from './enums/eResponseMethod'; import { eResponseMethod } from './enums/eResponseMethod';
import { eStratumErrorCode } from './enums/eStratumErrorCode'; import { eStratumErrorCode } from './enums/eStratumErrorCode';
@@ -36,6 +37,7 @@ const TRUE_DIFF_ONE = 2.695953529101131e67;
const BLOCKED_USER_AGENT_LOG_INTERVAL_MS = 60 * 1000; const BLOCKED_USER_AGENT_LOG_INTERVAL_MS = 60 * 1000;
const VALIDATION_ERROR_LOG_INTERVAL_MS = 60 * 1000; const VALIDATION_ERROR_LOG_INTERVAL_MS = 60 * 1000;
const DEFAULT_MIN_DIFFICULTY = 0.001; const DEFAULT_MIN_DIFFICULTY = 0.001;
const DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS = 60 * 1000;
export class StratumV1Client { export class StratumV1Client {
private static blockedUserAgentLogState = new Map<string, { nextLogAt: number, suppressed: number }>(); private static blockedUserAgentLogState = new Map<string, { nextLogAt: number, suppressed: number }>();
@@ -67,6 +69,7 @@ export class StratumV1Client {
private buffer: string = ''; private buffer: string = '';
private connectionClosed = false; private connectionClosed = false;
private lastSentMiningJobTimestamp: number = null; private lastSentMiningJobTimestamp: number = null;
private lastHashRatePersistedAt = 0;
private miningSubmissionHashes = new Set<string>() private miningSubmissionHashes = new Set<string>()
@@ -83,6 +86,7 @@ export class StratumV1Client {
private readonly redisMessagingService?: RedisMessagingService, private readonly redisMessagingService?: RedisMessagingService,
private readonly payoutSnapshotService?: PayoutSnapshotService, private readonly payoutSnapshotService?: PayoutSnapshotService,
private readonly accountingProtocol: 'sv1' | 'sv1_tls' = 'sv1', private readonly accountingProtocol: 'sv1' | 'sv1_tls' = 'sv1',
private readonly payoutMode: PayoutMode = 'solo',
) { ) {
this.socketDataHandler = (data: Buffer) => { this.socketDataHandler = (data: Buffer) => {
@@ -120,8 +124,6 @@ export class StratumV1Client {
if (this.clientEntity?.id) { if (this.clientEntity?.id) {
const clientId = this.clientEntity.id; const clientId = this.clientEntity.id;
const address = this.clientEntity.address;
await this.redisMessagingService?.removeClientPresence(clientId, address);
await this.clientService.delete(clientId); await this.clientService.delete(clientId);
} }
} }
@@ -447,6 +449,7 @@ export class StratumV1Client {
} }
private async sendNewMiningJob(jobTemplate: IJobTemplate) { private async sendNewMiningJob(jobTemplate: IJobTemplate) {
await this.ensureClientEntity();
let payoutInformation = this.getPayoutInformation(jobTemplate, this.clientAuthorization.address); let payoutInformation = this.getPayoutInformation(jobTemplate, this.clientAuthorization.address);
// const devFeeAddress = this.configService.get('DEV_FEE_ADDRESS'); // const devFeeAddress = this.configService.get('DEV_FEE_ADDRESS');
@@ -519,37 +522,15 @@ export class StratumV1Client {
clientName: this.clientAuthorization.worker, clientName: this.clientAuthorization.worker,
userAgent: this.clientSubscription.userAgent, userAgent: this.clientSubscription.userAgent,
startTime: new Date(), startTime: new Date(),
payoutMode: this.payoutMode,
bestDifficulty: 0 bestDifficulty: 0
}); });
await this.updateClientPresence(new Date());
})(); })();
} }
await this.creatingEntity; await this.creatingEntity;
} }
private async updateClientPresence(lastSeen: Date): Promise<void> {
if (this.clientEntity == null) {
return;
}
try {
await this.redisMessagingService?.setClientPresence({
clientId: this.clientEntity.id,
address: this.clientEntity.address,
clientName: this.clientEntity.clientName,
sessionId: this.clientEntity.sessionId,
userAgent: this.clientEntity.userAgent,
startTime: new Date(this.clientEntity.startTime).toISOString(),
lastSeen: lastSeen.toISOString(),
hashRate: this.statistics?.hashRate ?? 0,
bestDifficulty: Number(this.clientEntity.bestDifficulty ?? 0),
});
} catch (error) {
console.error(`Failed to update SV1 client presence: ${error.message}`);
}
}
private async handleMiningSubmission(submission: MiningSubmitMessage) { private async handleMiningSubmission(submission: MiningSubmitMessage) {
const job = this.stratumV1JobsService.getJobById(submission.jobId); const job = this.stratumV1JobsService.getJobById(submission.jobId);
@@ -651,13 +632,19 @@ export class StratumV1Client {
sessionId: this.extraNonceAndSessionId, sessionId: this.extraNonceAndSessionId,
blockData: blockHex, blockData: blockHex,
blockSubmissionResult, blockSubmissionResult,
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId ?? null, payoutSnapshotId: this.payoutMode === 'pplns'
}); ? jobTemplate.blockData.payoutSnapshotId ?? null
await this.payoutSnapshotService?.finalizeSnapshotForBlock({ : null,
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId, payoutMode: this.payoutMode,
blockHeight: jobTemplate.blockData.height,
blockSubmissionResult,
}); });
if (this.payoutMode === 'pplns') {
await this.payoutSnapshotService?.finalizeSnapshotForBlock({
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId,
blockHeight: jobTemplate.blockData.height,
blockSubmissionResult,
payoutMode: this.payoutMode,
});
}
await this.notificationService.notifySubscribersBlockFound(this.clientAuthorization.address, jobTemplate.blockData.height, updatedJobBlock, blockSubmissionResult); await this.notificationService.notifySubscribersBlockFound(this.clientAuthorization.address, jobTemplate.blockData.height, updatedJobBlock, blockSubmissionResult);
//success //success
@@ -669,6 +656,7 @@ export class StratumV1Client {
try { try {
await this.shareAccountingService?.recordAcceptedShare({ await this.shareAccountingService?.recordAcceptedShare({
protocol: this.accountingProtocol, protocol: this.accountingProtocol,
payoutMode: this.payoutMode,
address: this.clientAuthorization.address, address: this.clientAuthorization.address,
clientName: this.clientAuthorization.worker, clientName: this.clientAuthorization.worker,
sessionId: this.extraNonceAndSessionId, sessionId: this.extraNonceAndSessionId,
@@ -692,7 +680,7 @@ export class StratumV1Client {
const now = new Date(); const now = new Date();
this.clientEntity.updatedAt = now; this.clientEntity.updatedAt = now;
this.clientEntity.hashRate = this.statistics.hashRate; this.clientEntity.hashRate = this.statistics.hashRate;
await this.updateClientPresence(now); await this.persistClientHashRate(now);
} catch (e) { } catch (e) {
console.log(e); console.log(e);
@@ -702,7 +690,6 @@ export class StratumV1Client {
await this.clientService.updateBestDifficultyIfHigher(this.clientEntity.id, submissionDifficulty); await this.clientService.updateBestDifficultyIfHigher(this.clientEntity.id, submissionDifficulty);
this.clientEntity.bestDifficulty = submissionDifficulty; this.clientEntity.bestDifficulty = submissionDifficulty;
await this.addressSettingsService.updateBestDifficultyIfHigher(this.clientAuthorization.address, submissionDifficulty, this.clientEntity.userAgent); await this.addressSettingsService.updateBestDifficultyIfHigher(this.clientAuthorization.address, submissionDifficulty, this.clientEntity.userAgent);
await this.updateClientPresence(new Date());
} }
@@ -840,6 +827,39 @@ export class StratumV1Client {
}); });
} }
private async persistClientHashRate(now: Date): Promise<void> {
if (this.clientEntity?.id == null) {
return;
}
const hashRate = Number(this.statistics?.hashRate ?? 0);
if (!Number.isFinite(hashRate) || hashRate <= 0) {
return;
}
const intervalMs = this.getHashRatePersistIntervalMs();
const nowMs = now.getTime();
if (this.lastHashRatePersistedAt > 0 && nowMs - this.lastHashRatePersistedAt < intervalMs) {
return;
}
this.lastHashRatePersistedAt = nowMs;
try {
await this.clientService.updateHashRate(this.clientEntity.id, hashRate, now);
} catch (error) {
console.error(`Failed to persist SV1 client hashrate: ${error.message}`);
}
}
private getHashRatePersistIntervalMs(): number {
const configured = Number(this.configService.get<string>('CLIENT_HASHRATE_PERSIST_INTERVAL_MS'));
if (Number.isFinite(configured) && configured >= 0) {
return configured;
}
return DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS;
}
private getValidationErrorSignature(errors: ValidationError[]): string { private getValidationErrorSignature(errors: ValidationError[]): string {
if (errors.length === 0) { if (errors.length === 0) {
return 'unknown'; return 'unknown';
@@ -886,7 +906,7 @@ export class StratumV1Client {
} }
private getPayoutInformation(jobTemplate: IJobTemplate, fallbackAddress: string): AddressObject[] { private getPayoutInformation(jobTemplate: IJobTemplate, fallbackAddress: string): AddressObject[] {
if (this.configService.get('PAYOUT_COINBASE_MODE') === 'snapshot' && jobTemplate.blockData.payoutOutputs?.length > 0) { if (this.payoutMode === 'pplns' && jobTemplate.blockData.payoutOutputs?.length > 0) {
return jobTemplate.blockData.payoutOutputs; return jobTemplate.blockData.payoutOutputs;
} }
+129 -12
View File
@@ -7,6 +7,7 @@ import { MockRecording1 } from '../../test/models/MockRecording1';
import { ClientEntity } from '../ORM/client/client.entity'; import { ClientEntity } from '../ORM/client/client.entity';
import { CustomWorkService } from '../services/custom-work.service'; import { CustomWorkService } from '../services/custom-work.service';
import { StratumV1JobsService } from '../services/stratum-v1-jobs.service'; import { StratumV1JobsService } from '../services/stratum-v1-jobs.service';
import { hash256 } from '../utils/hash.utils';
import { BufferReader } from './sv2/sv2-binary-codec'; import { BufferReader } from './sv2/sv2-binary-codec';
import { SV2_CHANNEL_MSG_FLAG, Sv2MiningSetupFlags, Sv2MsgType, Sv2Protocol } from './sv2/sv2-constants'; import { SV2_CHANNEL_MSG_FLAG, Sv2MiningSetupFlags, Sv2MsgType, Sv2Protocol } from './sv2/sv2-constants';
import { import {
@@ -115,6 +116,50 @@ describe('StratumV2Client extended channels', () => {
expect(error.errorCode).toBe('invalid-extranonce-size'); expect(error.errorCode).toBe('invalid-extranonce-size');
}); });
it('reconstructs extended-channel block candidates with a matching merkle root', async () => {
const { client, sentFrames } = await createClient();
await (client as any).handleOpenExtendedMiningChannel(serializeOpenExtendedMiningChannel({
requestId: 1,
userIdentity: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4.worker',
nominalHashRate: 0,
maxTarget: Buffer.alloc(32, 0xff),
minExtranonceSize: 8,
}));
const jobFrame = sentFrames
.filter(frame => frame.msgType === Sv2MsgType.NEW_EXTENDED_MINING_JOB)
.at(-1);
const job = deserializeNewExtendedMiningJob(new BufferReader(jobFrame.payload));
const channel = (client as any).channels.get(1);
const extendedJob = channel.extendedJobs.get(job.jobId);
const extranonce = Buffer.alloc(channel.extranonceSize, 0x42);
const coinbaseTxBytes = Buffer.concat([
extendedJob.coinbasePrefix,
channel.extranoncePrefix,
extranonce,
extendedJob.coinbaseSuffix,
]);
let merkleRoot = hash256(coinbaseTxBytes);
for (const sibling of extendedJob.merklePath) {
merkleRoot = hash256(Buffer.concat([merkleRoot, sibling]));
}
const block = (client as any).reconstructExtendedBlock(
extendedJob,
{
jobId: job.jobId,
nonce: 123,
ntime: parseInt(MockRecording1.TIME, 16),
version: job.version,
extranonce,
},
merkleRoot,
channel.extranoncePrefix,
);
expect(block.merkleRoot.equals(bitcoinjs.Block.calculateMerkleRoot(block.transactions, false))).toBe(true);
expect(block.transactions[0].toBuffer()).toEqual(coinbaseTxBytes);
});
it('accepts SV2 work-selection setup and SetCustomMiningJob without sending pool work', async () => { it('accepts SV2 work-selection setup and SetCustomMiningJob without sending pool work', async () => {
const { client, sentFrames } = await createClient(); const { client, sentFrames } = await createClient();
await (client as any).handleSetupConnection(serializeSetupConnection({ await (client as any).handleSetupConnection(serializeSetupConnection({
@@ -151,7 +196,16 @@ describe('StratumV2Client extended channels', () => {
coinbaseTxVersion: 2, coinbaseTxVersion: 2,
coinbasePrefix: Buffer.from('51', 'hex'), coinbasePrefix: Buffer.from('51', 'hex'),
coinbaseTxInputNSequence: 0xffffffff, coinbaseTxInputNSequence: 0xffffffff,
coinbaseTxOutputs: Buffer.from('010000000000000000016a', 'hex'), coinbaseTxOutputs: serializeCoinbaseOutputs([
{
address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2',
amountSats: 0,
},
{
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
amountSats: MockRecording1.BLOCK_TEMPLATE.coinbasevalue,
},
]),
coinbaseTxLocktime: 0, coinbaseTxLocktime: 0,
merklePath: [], merklePath: [],
})); }));
@@ -163,6 +217,55 @@ describe('StratumV2Client extended channels', () => {
expect((client as any).channels.get(1).extendedJobs.get(success.jobId).workProtocol).toBe('sv2_jdp'); expect((client as any).channels.get(1).extendedJobs.get(success.jobId).workProtocol).toBe('sv2_jdp');
}); });
it('rejects SV2 work-selection custom jobs that do not pay the pool coinbase outputs', async () => {
const { client, sentFrames } = await createClient();
await (client as any).handleSetupConnection(serializeSetupConnection({
protocol: Sv2Protocol.MINING,
minVersion: 2,
maxVersion: 2,
flags: Sv2MiningSetupFlags.REQUIRES_WORK_SELECTION | Sv2MiningSetupFlags.REQUIRES_VERSION_ROLLING,
endpoint_host: 'localhost',
endpoint_port: 3333,
vendor: 'jd-client',
hardwareVersion: '',
firmwareVersion: '',
deviceId: '',
}));
await (client as any).handleOpenExtendedMiningChannel(serializeOpenExtendedMiningChannel({
requestId: 1,
userIdentity: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4.worker',
nominalHashRate: 0,
maxTarget: Buffer.alloc(32, 0xff),
minExtranonceSize: 8,
}));
sentFrames.length = 0;
await (client as any).handleSetCustomMiningJob(serializeSetCustomMiningJob({
channelId: 1,
requestId: 100,
token: Buffer.from('aa', 'hex'),
version: MockRecording1.BLOCK_TEMPLATE.version,
prevHash: Buffer.alloc(32, 1),
minNtime: parseInt(MockRecording1.TIME, 16),
nBits: parseInt(MockRecording1.BLOCK_TEMPLATE.bits, 16),
coinbaseTxVersion: 2,
coinbasePrefix: Buffer.from('51', 'hex'),
coinbaseTxInputNSequence: 0xffffffff,
coinbaseTxOutputs: serializeCoinbaseOutputs([{
address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2',
amountSats: MockRecording1.BLOCK_TEMPLATE.coinbasevalue,
}]),
coinbaseTxLocktime: 0,
merklePath: [],
}));
const errorFrame = sentFrames.find(frame => frame.msgType === Sv2MsgType.SET_CUSTOM_MINING_JOB_ERROR);
const error = deserializeSetCustomMiningJobError(new BufferReader(errorFrame.payload));
expect(error.channelId).toBe(1);
expect(error.requestId).toBe(100);
expect(error.errorCode).toBe('invalid-coinbase-payout-outputs');
});
it('rejects SetCustomMiningJob when work selection was not negotiated', async () => { it('rejects SetCustomMiningJob when work selection was not negotiated', async () => {
const { client, sentFrames } = await createClient(); const { client, sentFrames } = await createClient();
await (client as any).handleOpenExtendedMiningChannel(serializeOpenExtendedMiningChannel({ await (client as any).handleOpenExtendedMiningChannel(serializeOpenExtendedMiningChannel({
@@ -198,8 +301,8 @@ describe('StratumV2Client extended channels', () => {
expect((client as any).channels.get(1).extendedJobs.has(100)).toBe(false); expect((client as any).channels.get(1).extendedJobs.has(100)).toBe(false);
}); });
it('records accepted SV2 shares before presence updates', async () => { it('records accepted SV2 shares and persists DB hashrate', async () => {
const { client, shareAccountingService, redisMessagingService, jobTemplate } = await createClient(); const { client, clientService, shareAccountingService, jobTemplate } = await createClient();
(client as any).address = 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4'; (client as any).address = 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4';
(client as any).workerName = 'worker'; (client as any).workerName = 'worker';
(client as any).sessionId = 'sv2-session'; (client as any).sessionId = 'sv2-session';
@@ -230,10 +333,6 @@ describe('StratumV2Client extended channels', () => {
nonce: 123, nonce: 123,
extraNonce2: 'c708000000000000', extraNonce2: 'c708000000000000',
})); }));
const accountingCallOrder = shareAccountingService.recordAcceptedShare.mock.invocationCallOrder[0];
const postAccountingPresenceUpdates = redisMessagingService.setClientPresence.mock.invocationCallOrder
.filter(callOrder => callOrder > accountingCallOrder);
expect(postAccountingPresenceUpdates.length).toBeGreaterThan(0);
}); });
it('does not submit a block when only the reported SV2 difficulty is huge', async () => { it('does not submit a block when only the reported SV2 difficulty is huge', async () => {
@@ -308,6 +407,8 @@ describe('StratumV2Client extended channels', () => {
worker: 'worker', worker: 'worker',
sessionId: 'sv2-session', sessionId: 'sv2-session',
blockData: expect.any(String), blockData: expect.any(String),
payoutSnapshotId: null,
payoutMode: 'solo',
})); }));
expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalled(); expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalled();
expect(addressSettingsService.resetBestDifficultyAndShares).toHaveBeenCalled(); expect(addressSettingsService.resetBestDifficultyAndShares).toHaveBeenCalled();
@@ -317,11 +418,12 @@ describe('StratumV2Client extended channels', () => {
client: StratumV2Client; client: StratumV2Client;
sentFrames: any[]; sentFrames: any[];
bitcoinRpcService: { SUBMIT_BLOCK: jest.Mock }; bitcoinRpcService: { SUBMIT_BLOCK: jest.Mock };
clientService: { updateHashRate: jest.Mock };
blocksService: { save: jest.Mock }; blocksService: { save: jest.Mock };
notificationService: { notifySubscribersBlockFound: jest.Mock }; notificationService: { notifySubscribersBlockFound: jest.Mock };
addressSettingsService: { resetBestDifficultyAndShares: jest.Mock; updateBestDifficultyIfHigher: jest.Mock }; addressSettingsService: { resetBestDifficultyAndShares: jest.Mock; updateBestDifficultyIfHigher: jest.Mock };
shareAccountingService: { recordAcceptedShare: jest.Mock }; shareAccountingService: { recordAcceptedShare: jest.Mock };
redisMessagingService: { setClientPresence: jest.Mock; removeClientPresence: jest.Mock }; redisMessagingService: Record<string, never>;
jobTemplate: any; jobTemplate: any;
}> { }> {
const blockTemplate$ = new BehaviorSubject(MockRecording1.BLOCK_TEMPLATE); const blockTemplate$ = new BehaviorSubject(MockRecording1.BLOCK_TEMPLATE);
@@ -364,6 +466,7 @@ describe('StratumV2Client extended channels', () => {
insert: jest.fn().mockResolvedValue(clientEntity), insert: jest.fn().mockResolvedValue(clientEntity),
delete: jest.fn().mockResolvedValue(undefined), delete: jest.fn().mockResolvedValue(undefined),
updateBestDifficultyIfHigher: jest.fn().mockResolvedValue(undefined), updateBestDifficultyIfHigher: jest.fn().mockResolvedValue(undefined),
updateHashRate: jest.fn().mockResolvedValue(undefined),
}; };
const shareAccountingService = { const shareAccountingService = {
recordAcceptedShare: jest.fn().mockResolvedValue(undefined), recordAcceptedShare: jest.fn().mockResolvedValue(undefined),
@@ -374,10 +477,7 @@ describe('StratumV2Client extended channels', () => {
const blocksService = { const blocksService = {
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
const redisMessagingService = { const redisMessagingService = {};
setClientPresence: jest.fn().mockResolvedValue(undefined),
removeClientPresence: jest.fn().mockResolvedValue(undefined),
};
const addressSettingsService = { const addressSettingsService = {
resetBestDifficultyAndShares: jest.fn().mockResolvedValue(undefined), resetBestDifficultyAndShares: jest.fn().mockResolvedValue(undefined),
updateBestDifficultyIfHigher: jest.fn().mockResolvedValue(undefined), updateBestDifficultyIfHigher: jest.fn().mockResolvedValue(undefined),
@@ -443,6 +543,7 @@ describe('StratumV2Client extended channels', () => {
client, client,
sentFrames, sentFrames,
bitcoinRpcService, bitcoinRpcService,
clientService,
blocksService, blocksService,
notificationService, notificationService,
addressSettingsService, addressSettingsService,
@@ -452,3 +553,19 @@ describe('StratumV2Client extended channels', () => {
}; };
} }
}); });
function serializeCoinbaseOutputs(outputs: { address: string; amountSats: number }[]): Buffer {
return Buffer.concat([
Buffer.from([outputs.length]),
...outputs.map(output => {
const script = bitcoinjs.address.toOutputScript(output.address, bitcoinjs.networks.testnet);
const value = Buffer.alloc(8);
value.writeBigUInt64LE(BigInt(output.amountSats), 0);
return Buffer.concat([
value,
Buffer.from([script.length]),
script,
]);
}),
]);
}
+136 -32
View File
@@ -23,6 +23,7 @@ import { DifficultyUtils } from '../utils/difficulty.utils';
import { hash256 } from '../utils/hash.utils'; import { hash256 } from '../utils/hash.utils';
import { AddressObject, MiningJob } from './MiningJob'; import { AddressObject, MiningJob } from './MiningJob';
import { StratumV1ClientStatistics } from './StratumV1ClientStatistics'; import { StratumV1ClientStatistics } from './StratumV1ClientStatistics';
import { PayoutMode } from '../types/payout-mode';
import { BufferReader } from './sv2/sv2-binary-codec'; import { BufferReader } from './sv2/sv2-binary-codec';
import { import {
SV2_CHANNEL_MSG_FLAG, SV2_CHANNEL_MSG_FLAG,
@@ -69,6 +70,7 @@ const DEFAULT_START_DIFFICULTY = 100000;
const DEFAULT_MIN_DIFFICULTY = 0.001; const DEFAULT_MIN_DIFFICULTY = 0.001;
const DEFAULT_TARGET_SHARES_PER_MINUTE = 2; const DEFAULT_TARGET_SHARES_PER_MINUTE = 2;
const DEFAULT_DIFFICULTY_CHECK_INTERVAL_MS = 60 * 1000; const DEFAULT_DIFFICULTY_CHECK_INTERVAL_MS = 60 * 1000;
const DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS = 60 * 1000;
const FIXED_STANDARD_EXTRANONCE2 = '0000000000000000'; const FIXED_STANDARD_EXTRANONCE2 = '0000000000000000';
const RETIRED_EXTENDED_JOB_RETENTION_MS = 5 * 60 * 1000; const RETIRED_EXTENDED_JOB_RETENTION_MS = 5 * 60 * 1000;
const SV2_AUTH_FAILURE_LOG_INTERVAL_MS = 60 * 1000; const SV2_AUTH_FAILURE_LOG_INTERVAL_MS = 60 * 1000;
@@ -132,6 +134,7 @@ export class StratumV2Client {
private creatingEntity: Promise<void> = null; private creatingEntity: Promise<void> = null;
private readonly firstChunkSummary: string; private readonly firstChunkSummary: string;
private workSelectionEnabled = false; private workSelectionEnabled = false;
private lastHashRatePersistedAt = 0;
constructor( constructor(
private readonly socket: Socket, private readonly socket: Socket,
@@ -149,6 +152,7 @@ export class StratumV2Client {
private readonly shareAccountingService?: ShareAccountingService, private readonly shareAccountingService?: ShareAccountingService,
private readonly redisMessagingService?: RedisMessagingService, private readonly redisMessagingService?: RedisMessagingService,
private readonly payoutSnapshotService?: PayoutSnapshotService, private readonly payoutSnapshotService?: PayoutSnapshotService,
private readonly payoutMode: PayoutMode = 'solo',
) { ) {
this.firstChunkSummary = this.describeChunk(firstChunk); this.firstChunkSummary = this.describeChunk(firstChunk);
this.noiseSession = new Sv2NoiseSession(this.stratumV2Service.getNoiseConfig()); this.noiseSession = new Sv2NoiseSession(this.stratumV2Service.getNoiseConfig());
@@ -187,7 +191,6 @@ export class StratumV2Client {
} }
this.channels.clear(); this.channels.clear();
if (this.clientEntity?.id != null) { if (this.clientEntity?.id != null) {
await this.redisMessagingService?.removeClientPresence(this.clientEntity.id, this.clientEntity.address);
await this.clientService.delete(this.clientEntity.id); await this.clientService.delete(this.clientEntity.id);
} }
} }
@@ -766,6 +769,26 @@ export class StratumV2Client {
msg, msg,
channel.extranoncePrefix.length + channel.extranonceSize, channel.extranoncePrefix.length + channel.extranonceSize,
); );
const payoutValidation = this.validateCoinbasePayoutOutputs(
Buffer.concat([
split.coinbasePrefix,
Buffer.alloc(channel.extranoncePrefix.length + channel.extranonceSize),
split.coinbaseSuffix,
]),
latestTemplate,
this.getPayoutInformation(latestTemplate, this.address),
);
if (!payoutValidation.valid) {
await this.sendFrame(
Sv2MsgType.SET_CUSTOM_MINING_JOB_ERROR,
serializeSetCustomMiningJobError({
channelId: msg.channelId,
requestId: msg.requestId,
errorCode: payoutValidation.errorCode,
}),
);
return;
}
const placeholderJob = new MiningJob( const placeholderJob = new MiningJob(
this.network, this.network,
jobIdHex, jobIdHex,
@@ -862,13 +885,19 @@ export class StratumV2Client {
sessionId: this.sessionId, sessionId: this.sessionId,
blockData: blockHex, blockData: blockHex,
blockSubmissionResult, blockSubmissionResult,
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId ?? null, payoutSnapshotId: this.payoutMode === 'pplns'
}); ? jobTemplate.blockData.payoutSnapshotId ?? null
await this.payoutSnapshotService?.finalizeSnapshotForBlock({ : null,
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId, payoutMode: this.payoutMode,
blockHeight: jobTemplate.blockData.height,
blockSubmissionResult,
}); });
if (this.payoutMode === 'pplns') {
await this.payoutSnapshotService?.finalizeSnapshotForBlock({
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId,
blockHeight: jobTemplate.blockData.height,
blockSubmissionResult,
payoutMode: this.payoutMode,
});
}
await this.notificationService.notifySubscribersBlockFound( await this.notificationService.notifySubscribersBlockFound(
this.address, this.address,
jobTemplate.blockData.height, jobTemplate.blockData.height,
@@ -882,6 +911,7 @@ export class StratumV2Client {
await this.shareAccountingService?.recordAcceptedShare({ await this.shareAccountingService?.recordAcceptedShare({
protocol: metadata.workProtocol === 'sv2_jdp' ? 'sv2_jdp' : 'sv2', protocol: metadata.workProtocol === 'sv2_jdp' ? 'sv2_jdp' : 'sv2',
payoutMode: this.payoutMode,
workSource: metadata.workProtocol === 'sv2_jdp' ? 'miner_template' : 'pool_template', workSource: metadata.workProtocol === 'sv2_jdp' ? 'miner_template' : 'pool_template',
workProtocol: metadata.workProtocol ?? 'pool', workProtocol: metadata.workProtocol ?? 'pool',
address: this.address, address: this.address,
@@ -905,7 +935,7 @@ export class StratumV2Client {
const now = new Date(); const now = new Date();
this.clientEntity.updatedAt = now; this.clientEntity.updatedAt = now;
this.clientEntity.hashRate = this.statistics.hashRate; this.clientEntity.hashRate = this.statistics.hashRate;
await this.updateClientPresence(now); await this.persistClientHashRate(now);
if (submissionDifficulty > this.clientEntity.bestDifficulty) { if (submissionDifficulty > this.clientEntity.bestDifficulty) {
await this.clientService.updateBestDifficultyIfHigher(this.clientEntity.id, submissionDifficulty); await this.clientService.updateBestDifficultyIfHigher(this.clientEntity.id, submissionDifficulty);
@@ -915,7 +945,6 @@ export class StratumV2Client {
submissionDifficulty, submissionDifficulty,
this.userAgent, this.userAgent,
); );
await this.updateClientPresence(new Date());
} }
} }
@@ -929,13 +958,12 @@ export class StratumV2Client {
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 => Object.assign(new bitcoinjs.Transaction(), tx)); testBlock.transactions = jobTemplate.block.transactions.map(tx => Object.assign(new bitcoinjs.Transaction(), tx));
const coinbaseTx = extendedJob.miningJob.cloneCoinbaseTransaction(); const coinbaseTx = bitcoinjs.Transaction.fromBuffer(Buffer.concat([
const script = coinbaseTx.ins[0].script; extendedJob.coinbasePrefix,
coinbaseTx.ins[0].script = Buffer.concat([
script.subarray(0, script.length - (extranoncePrefix.length + submission.extranonce.length)),
extranoncePrefix, extranoncePrefix,
submission.extranonce, submission.extranonce,
]); extendedJob.coinbaseSuffix,
]));
testBlock.transactions[0] = coinbaseTx; testBlock.transactions[0] = coinbaseTx;
testBlock.version = submission.version; testBlock.version = submission.version;
testBlock.nonce = submission.nonce; testBlock.nonce = submission.nonce;
@@ -1282,35 +1310,46 @@ export class StratumV2Client {
clientName: this.workerName, clientName: this.workerName,
userAgent: this.userAgent, userAgent: this.userAgent,
startTime: new Date(), startTime: new Date(),
payoutMode: this.payoutMode,
bestDifficulty: 0, bestDifficulty: 0,
}); });
await this.updateClientPresence(new Date());
})(); })();
} }
await this.creatingEntity; await this.creatingEntity;
} }
private async updateClientPresence(lastSeen: Date): Promise<void> { private async persistClientHashRate(now: Date): Promise<void> {
if (this.clientEntity == null) { if (this.clientEntity?.id == null) {
return; return;
} }
try { const hashRate = Number(this.statistics?.hashRate ?? 0);
await this.redisMessagingService?.setClientPresence({ if (!Number.isFinite(hashRate) || hashRate <= 0) {
clientId: this.clientEntity.id, return;
address: this.clientEntity.address,
clientName: this.clientEntity.clientName,
sessionId: this.clientEntity.sessionId,
userAgent: this.clientEntity.userAgent,
startTime: new Date(this.clientEntity.startTime).toISOString(),
lastSeen: lastSeen.toISOString(),
hashRate: this.statistics.hashRate,
bestDifficulty: Number(this.clientEntity.bestDifficulty ?? 0),
});
} catch (error) {
console.error(`Failed to update SV2 client presence: ${error.message}`);
} }
const intervalMs = this.getHashRatePersistIntervalMs();
const nowMs = now.getTime();
if (this.lastHashRatePersistedAt > 0 && nowMs - this.lastHashRatePersistedAt < intervalMs) {
return;
}
this.lastHashRatePersistedAt = nowMs;
try {
await this.clientService.updateHashRate(this.clientEntity.id, hashRate, now);
} catch (error) {
console.error(`Failed to persist SV2 client hashrate: ${error.message}`);
}
}
private getHashRatePersistIntervalMs(): number {
const configured = Number(this.configService.get<string>('CLIENT_HASHRATE_PERSIST_INTERVAL_MS'));
if (Number.isFinite(configured) && configured >= 0) {
return configured;
}
return DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS;
} }
private parseUserIdentity(userIdentity: string): { address: string; workerName: string } { private parseUserIdentity(userIdentity: string): { address: string; workerName: string } {
@@ -1394,13 +1433,78 @@ export class StratumV2Client {
} }
private getPayoutInformation(jobTemplate: IJobTemplate, fallbackAddress: string): AddressObject[] { private getPayoutInformation(jobTemplate: IJobTemplate, fallbackAddress: string): AddressObject[] {
if (this.configService.get('PAYOUT_COINBASE_MODE') === 'snapshot' && jobTemplate.blockData.payoutOutputs?.length > 0) { if (this.payoutMode === 'pplns' && jobTemplate.blockData.payoutOutputs?.length > 0) {
return jobTemplate.blockData.payoutOutputs; return jobTemplate.blockData.payoutOutputs;
} }
return [{ address: fallbackAddress, percent: 100 }]; return [{ address: fallbackAddress, percent: 100 }];
} }
private validateCoinbasePayoutOutputs(
coinbaseTxBytes: Buffer,
jobTemplate: IJobTemplate,
payoutInformation: AddressObject[],
): { valid: boolean; errorCode?: string } {
let transaction: bitcoinjs.Transaction;
try {
transaction = bitcoinjs.Transaction.fromBuffer(coinbaseTxBytes);
} catch {
return { valid: false, errorCode: 'invalid-coinbase-transaction' };
}
const expectedOutputs = this.buildExpectedPayoutOutputs(payoutInformation, jobTemplate.blockData.coinbasevalue);
const submittedOutputs = transaction.outs
.filter(output => !this.isWitnessCommitmentOutput(output.script))
.filter(output => BigInt(output.value) !== 0n)
.map(output => ({
value: BigInt(output.value),
scriptPubKey: Buffer.from(output.script),
}));
if (submittedOutputs.length !== expectedOutputs.length) {
return { valid: false, errorCode: 'invalid-coinbase-payout-outputs' };
}
for (let i = 0; i < expectedOutputs.length; i++) {
const expected = expectedOutputs[i];
const submitted = submittedOutputs[i];
if (submitted.value !== expected.value || !submitted.scriptPubKey.equals(expected.scriptPubKey)) {
return { valid: false, errorCode: 'invalid-coinbase-payout-outputs' };
}
}
return { valid: true };
}
private buildExpectedPayoutOutputs(
payoutInformation: AddressObject[],
coinbaseValue: number,
): { value: bigint; scriptPubKey: Buffer }[] {
let rewardBalance = BigInt(Math.max(0, Math.floor(coinbaseValue)));
const outputs = payoutInformation.map(recipientAddress => {
const value = recipientAddress.amountSats == null
? BigInt(Math.floor(((recipientAddress.percent ?? 0) / 100) * coinbaseValue))
: BigInt(recipientAddress.amountSats);
rewardBalance -= value;
return {
value,
scriptPubKey: bitcoinjs.address.toOutputScript(recipientAddress.address, this.network),
};
});
if (outputs.length > 0 && rewardBalance !== 0n) {
outputs[0] = {
...outputs[0],
value: outputs[0].value + rewardBalance,
};
}
return outputs;
}
private isWitnessCommitmentOutput(script: Buffer): boolean {
return script.length === 38
&& script[0] === bitcoinjs.opcodes.OP_RETURN
&& script[1] === 0x24
&& script.subarray(2, 6).equals(Buffer.from('aa21a9ed', 'hex'));
}
private isSuccessfulBlockSubmission(result?: string | null): boolean { private isSuccessfulBlockSubmission(result?: string | null): boolean {
return result == null || result === 'SUCCESS!'; return result == null || result === 'SUCCESS!';
} }
+41 -1
View File
@@ -80,11 +80,15 @@ describe('datum-codec', () => {
it('serializes coinbaser fetch responses', () => { it('serializes coinbaser fetch responses', () => {
const response = serializeDatumCoinbaserFetchResponse(50n, [ const response = serializeDatumCoinbaserFetchResponse(50n, [
{ value: 50n, scriptPubKey: Buffer.from('6a', 'hex') }, { value: 50n, scriptPubKey: Buffer.from('6a', 'hex') },
]); ], 7);
const mining = deserializeDatumMiningCommand(response); const mining = deserializeDatumMiningCommand(response);
expect(mining.command).toBe(DatumMiningCommand.FETCH_COINBASER_RESPONSE); expect(mining.command).toBe(DatumMiningCommand.FETCH_COINBASER_RESPONSE);
expect(mining.body.readBigUInt64LE(0)).toBe(50n); expect(mining.body.readBigUInt64LE(0)).toBe(50n);
expect(mining.body.readUInt32LE(8)).toBe(11); 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', () => { it('deserializes coinbaser fetch requests', () => {
@@ -178,6 +182,42 @@ describe('datum-codec', () => {
expect(parsed.coinbasePairs.get(2)?.coinb2.toString('hex')).toBe('010203'); 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', () => { it('rejects DATUM POW submissions with non-standard extranonce sizes', () => {
const payload = Buffer.alloc(18); const payload = Buffer.alloc(18);
payload[16] = 1; payload[16] = 1;
+7 -7
View File
@@ -332,21 +332,21 @@ export function deserializeDatumCoinbaserFetch(payload: Buffer): DatumCoinbaserF
return { rewardValue: payload.readBigUInt64LE(0) }; return { rewardValue: payload.readBigUInt64LE(0) };
} }
export function serializeDatumCoinbaserFetchResponse(rewardValue: bigint, outputs: DatumPayoutOutput[]): Buffer { export function serializeDatumCoinbaserFetchResponse(rewardValue: bigint, outputs: DatumPayoutOutput[], coinbaserId = 1): Buffer {
const w = new BufferWriter(); const w = new BufferWriter();
w.writeU64(rewardValue); w.writeU64(rewardValue);
const outputsBuffer = serializeDatumPayoutOutputs(outputs); const outputsBuffer = serializeDatumPayoutOutputs(outputs, coinbaserId);
w.writeU32(outputsBuffer.length); w.writeU32(outputsBuffer.length);
w.writeBytes(outputsBuffer); w.writeBytes(outputsBuffer);
return serializeDatumMiningCommand(DatumMiningCommand.FETCH_COINBASER_RESPONSE, Buffer.from(w.toBuffer())); return serializeDatumMiningCommand(DatumMiningCommand.FETCH_COINBASER_RESPONSE, Buffer.from(w.toBuffer()));
} }
export function serializeDatumPayoutOutputs(outputs: DatumPayoutOutput[]): Buffer { export function serializeDatumPayoutOutputs(outputs: DatumPayoutOutput[], coinbaserId = 1): Buffer {
if (outputs.length > 255) { if (!Number.isInteger(coinbaserId) || coinbaserId < 0 || coinbaserId > 255) {
throw new RangeError('DATUM payout output count must fit in one byte'); throw new RangeError('DATUM coinbaser id must fit in one byte');
} }
const w = new BufferWriter(); const w = new BufferWriter();
w.writeU8(outputs.length); w.writeU8(coinbaserId);
for (const output of outputs) { for (const output of outputs) {
if (output.scriptPubKey.length > 255) { if (output.scriptPubKey.length > 255) {
throw new RangeError('DATUM scriptPubKey length must fit in one byte'); throw new RangeError('DATUM scriptPubKey length must fit in one byte');
@@ -422,7 +422,7 @@ export function deserializeDatumPowSubmit(payload: Buffer): DatumPowSubmit {
coinb1: reader.readBytes(coinb1Len), coinb1: reader.readBytes(coinb1Len),
coinb2: reader.readBytes(coinb2Len), coinb2: reader.readBytes(coinb2Len),
}; };
if (coinbaseType === 255 || coinbaseId === 255) { if (coinbaseType === 255) {
result.subsidyOnlyCoinbase = coinbase; result.subsidyOnlyCoinbase = coinbase;
} else { } else {
coinbasePairs.set(coinbaseType, coinbase); coinbasePairs.set(coinbaseType, coinbase);
+2
View File
@@ -84,6 +84,8 @@ export class AppService implements OnModuleInit {
this.refreshingPoolSummary = true; this.refreshingPoolSummary = true;
try { try {
await this.shareAccountingService.refreshPoolSummary(); await this.shareAccountingService.refreshPoolSummary();
await this.shareAccountingService.refreshPoolSummary('pplns');
await this.shareAccountingService.refreshPoolSummary('solo');
} catch (error) { } catch (error) {
console.error(`Failed refreshing pool accounting summary: ${error.message}`); console.error(`Failed refreshing pool accounting summary: ${error.message}`);
} finally { } finally {
+309 -4
View File
@@ -1,9 +1,26 @@
import { Socket } from 'net'; import { Socket } from 'net';
import * as bitcoinjs from 'bitcoinjs-lib';
import { DatumProtocolCommand } from '../models/datum/datum-codec'; import { DatumProtocolCommand } from '../models/datum/datum-codec';
import { DatumService } from './datum.service'; import { DatumService } from './datum.service';
import { TemplateProviderService } from './template-provider.service'; import { TemplateProviderService } from './template-provider.service';
import { StratumV1ClientStatistics } from '../models/StratumV1ClientStatistics';
function createService(): DatumService { function createService(overrides: {
configService?: any;
clientService?: any;
redisMessagingService?: any;
} = {}): DatumService {
const configService = overrides.configService ?? {
get: jest.fn((key: string) => {
if (key === 'NETWORK') {
return 'testnet';
}
if (key === 'PAYOUT_COINBASE_MODE') {
return 'snapshot';
}
return undefined;
}),
};
const templateProvider = { const templateProvider = {
validateTransactionData: jest.fn(({ transactionList, expectedCount, maxTotalBytes }) => { validateTransactionData: jest.fn(({ transactionList, expectedCount, maxTotalBytes }) => {
if (expectedCount != null && transactionList.length !== expectedCount) { if (expectedCount != null && transactionList.length !== expectedCount) {
@@ -17,15 +34,15 @@ function createService(): DatumService {
}), }),
}; };
return new DatumService( return new DatumService(
configService as any,
{} as any, {} as any,
{} as any, {} as any,
{} as any, overrides.clientService ?? {} as any,
{} as any,
{} as any, {} as any,
{} as any, {} as any,
{} as any, {} as any,
templateProvider as unknown as TemplateProviderService, templateProvider as unknown as TemplateProviderService,
undefined, overrides.redisMessagingService,
); );
} }
@@ -48,6 +65,10 @@ function createState(cache: any): any {
} }
describe('DatumService job validation', () => { describe('DatumService job validation', () => {
afterEach(() => {
jest.useRealTimers();
});
it('requests short transaction IDs once a DATUM job advertises transactions', async () => { it('requests short transaction IDs once a DATUM job advertises transactions', async () => {
const service = createService() as any; const service = createService() as any;
const socket = createSocket(); const socket = createSocket();
@@ -153,4 +174,288 @@ describe('DatumService job validation', () => {
}); });
expect(socket.write).not.toHaveBeenCalled(); expect(socket.write).not.toHaveBeenCalled();
}); });
it('persists DATUM client hashrate after accepted shares', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-06-13T15:00:00.000Z'));
const clientService = {
updateBestDifficultyIfHigher: jest.fn().mockResolvedValue(undefined),
updateHashRate: jest.fn().mockResolvedValue(undefined),
};
const service = createService({ clientService }) as any;
const state = {
sessionId: 'datum-session',
userAgent: 'datum/test',
clientEntity: {
id: '3db0db03-3a62-4e3b-91bc-243adff4b542',
address: 'tb1qdatum',
clientName: 'datum-worker',
sessionId: 'datum-session',
startTime: new Date('2026-06-13T14:59:00.000Z'),
bestDifficulty: 0,
hashRate: 0,
},
statistics: new StratumV1ClientStatistics(1),
lastHashRatePersistedAt: 0,
};
await service.updateAcceptedSharePresence(state, 'tb1qdatum', 'datum-worker', 10, 1);
jest.setSystemTime(new Date('2026-06-13T15:00:31.000Z'));
await service.updateAcceptedSharePresence(state, 'tb1qdatum', 'datum-worker', 20, 1);
jest.setSystemTime(new Date('2026-06-13T15:01:02.000Z'));
await service.updateAcceptedSharePresence(state, 'tb1qdatum', 'datum-worker', 30, 1);
expect(clientService.updateBestDifficultyIfHigher).toHaveBeenLastCalledWith(
'3db0db03-3a62-4e3b-91bc-243adff4b542',
30,
);
expect(state.clientEntity.hashRate).toBeGreaterThan(0);
expect(clientService.updateHashRate).toHaveBeenCalledWith(
'3db0db03-3a62-4e3b-91bc-243adff4b542',
state.clientEntity.hashRate,
new Date('2026-06-13T15:01:02.000Z'),
);
});
it('derives submitted share difficulty from DATUM target byte', () => {
const service = createService() as any;
expect(service.getDatumSubmittedShareDifficulty({ targetByte: 0x00 })).toBe(1);
expect(service.getDatumSubmittedShareDifficulty({ targetByte: 0x0e })).toBe(16_384);
expect(service.getDatumSubmittedShareDifficulty({ targetByte: 0x14 })).toBe(1_048_576);
});
it('falls back to configured DATUM share difficulty for invalid target bytes', () => {
const service = createService({
configService: {
get: jest.fn((key: string) => {
if (key === 'DATUM_SHARE_DIFFICULTY') {
return '4096';
}
if (key === 'NETWORK') {
return 'testnet';
}
return undefined;
}),
},
}) as any;
expect(service.getDatumSubmittedShareDifficulty({ targetByte: 0xff })).toBe(4096);
});
it('accepts DATUM coinbases that exactly match snapshot payout outputs', () => {
const service = createService() as any;
const extranonce = Buffer.alloc(12, 1);
const expectedOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 421 },
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 133 },
{ address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', amountSats: 42 },
];
const coinbase = createDatumCoinbaseSplit(expectedOutputs, extranonce);
const latestTemplate = {
blockData: {
coinbasevalue: 596,
payoutOutputs: expectedOutputs,
},
};
expect(service.validateDatumCoinbasePayouts(
coinbase,
{ extranonce, targetByte: 0 },
latestTemplate,
596n,
undefined,
'pplns',
).valid).toBe(true);
});
it('accepts DATUM coinbases with zero-value OP_RETURN metadata plus matching snapshot payouts', () => {
const service = createService() as any;
const extranonce = Buffer.alloc(12, 1);
const expectedOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 421 },
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 133 },
{ address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', amountSats: 42 },
];
const coinbase = createDatumCoinbaseSplit(expectedOutputs, extranonce, true);
const latestTemplate = {
blockData: {
coinbasevalue: 596,
payoutOutputs: expectedOutputs,
},
};
const validation = service.validateDatumCoinbasePayouts(
coinbase,
{ extranonce, targetByte: 0 },
latestTemplate,
596n,
undefined,
'pplns',
);
expect(validation.valid).toBe(true);
expect(validation.submittedOutputs).toHaveLength(3);
});
it('rejects DATUM coinbases with extra spendable outputs beyond snapshot payouts', () => {
const service = createService() as any;
const extranonce = Buffer.alloc(12, 1);
const expectedOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 421 },
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 133 },
{ address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', amountSats: 42 },
];
const coinbase = createDatumCoinbaseSplit([
...expectedOutputs,
{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', amountSats: 1 },
], extranonce);
const latestTemplate = {
blockData: {
coinbasevalue: 596,
payoutOutputs: expectedOutputs,
},
};
const validation = service.validateDatumCoinbasePayouts(
coinbase,
{ extranonce, targetByte: 0 },
latestTemplate,
596n,
undefined,
'pplns',
);
expect(validation.valid).toBe(false);
expect(validation.error).toBe('output-count-mismatch');
});
it('rejects DATUM coinbases that do not pay the pool snapshot outputs', () => {
const service = createService() as any;
const extranonce = Buffer.alloc(12, 1);
const expectedOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 421 },
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 133 },
{ address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', amountSats: 42 },
];
const maliciousCoinbase = createDatumCoinbaseSplit([
{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', amountSats: 596 },
], extranonce);
const latestTemplate = {
blockData: {
coinbasevalue: 596,
payoutOutputs: expectedOutputs,
},
};
expect(service.validateDatumCoinbasePayouts(
maliciousCoinbase,
{ extranonce, targetByte: 0 },
latestTemplate,
596n,
undefined,
'pplns',
).valid).toBe(false);
});
it('validates DATUM coinbases against the coinbaser-id payout outputs instead of the latest template', () => {
const service = createService() as any;
const extranonce = Buffer.alloc(12, 1);
const fetchedOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 596 },
];
const laterTemplateOutputs = [
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 596 },
];
const coinbase = createDatumCoinbaseSplit(fetchedOutputs, extranonce);
const latestTemplate = {
blockData: {
coinbasevalue: 596,
payoutOutputs: laterTemplateOutputs,
},
};
const expectedPayoutOutputs = (service as any).getDatumPayoutOutputs({
blockData: {
payoutOutputs: fetchedOutputs,
},
}, 596, 'pplns');
expect(service.validateDatumCoinbasePayouts(
coinbase,
{ extranonce, targetByte: 0 },
latestTemplate,
596n,
expectedPayoutOutputs,
'pplns',
).valid).toBe(true);
});
it('carries the coinbaser payout snapshot id into the DATUM job cache', () => {
const service = createService() as any;
const payoutOutputs = [{
value: 596n,
scriptPubKey: bitcoinjs.address.toOutputScript(
'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh',
bitcoinjs.networks.testnet,
),
}];
const state = {
datumJobs: new Map(),
coinbaserPayoutContexts: new Map([[9, {
payoutOutputs,
payoutSnapshotId: '95',
blockHeight: 4991366,
}]]),
};
const cache = service.updateDatumJobCache(state, {
jobId: 7,
coinbaserId: 9,
coinbasePairs: new Map(),
});
expect(cache.coinbaserId).toBe(9);
expect(cache.expectedPayoutOutputs).toBe(payoutOutputs);
expect(cache.payoutSnapshotId).toBe('95');
});
}); });
function createDatumCoinbaseSplit(
outputs: { address: string; amountSats: number }[],
extranonce: Buffer,
includeDatumMetadata = false,
): { coinb1: Buffer; coinb2: Buffer } {
const tx = new bitcoinjs.Transaction();
tx.version = 2;
tx.addInput(Buffer.alloc(32), 0xffffffff, 0xffffffff);
tx.ins[0].script = Buffer.concat([
Buffer.from([0x03, 0x51, 0x27, 0x4c]),
extranonce,
]);
tx.ins[0].witness = [Buffer.alloc(32)];
for (const output of outputs) {
tx.addOutput(
bitcoinjs.address.toOutputScript(output.address, bitcoinjs.networks.testnet),
output.amountSats,
);
}
if (includeDatumMetadata) {
tx.addOutput(bitcoinjs.script.compile([bitcoinjs.opcodes.OP_RETURN, Buffer.from([0])]), 0);
}
tx.addOutput(
bitcoinjs.script.compile([
bitcoinjs.opcodes.OP_RETURN,
Buffer.concat([Buffer.from('aa21a9ed', 'hex'), Buffer.alloc(32, 2)]),
]),
0,
);
const serialized = tx.toBuffer();
const index = serialized.indexOf(extranonce);
if (index < 0) {
throw new Error('test coinbase split missing extranonce');
}
return {
coinb1: serialized.subarray(0, index),
coinb2: serialized.subarray(index + extranonce.length),
};
}
+299 -39
View File
@@ -19,6 +19,7 @@ import {
DatumPowSubmit, DatumPowSubmit,
DatumJobValidationStatus, DatumJobValidationStatus,
DatumJobValidationResponse, DatumJobValidationResponse,
DatumPayoutOutput,
deserializeDatumCoinbaserFetch, deserializeDatumCoinbaserFetch,
deserializeDatumJobValidationResponse, deserializeDatumJobValidationResponse,
deserializeDatumMiningCommand, deserializeDatumMiningCommand,
@@ -33,12 +34,17 @@ import { DatumCryptoSession } from '../models/datum/datum-crypto';
import { BitcoinRpcService } from './bitcoin-rpc.service'; import { BitcoinRpcService } from './bitcoin-rpc.service';
import { CustomWorkService } from './custom-work.service'; import { CustomWorkService } from './custom-work.service';
import { RedisMessagingService } from './redis-messaging.service'; import { RedisMessagingService } from './redis-messaging.service';
import { StratumV1JobsService } from './stratum-v1-jobs.service'; import { IJobTemplate, StratumV1JobsService } from './stratum-v1-jobs.service';
import { DatumKeyPair } from '../models/datum/datum-crypto'; import { DatumKeyPair } from '../models/datum/datum-crypto';
import { TemplateProviderService } from './template-provider.service'; import { TemplateProviderService } from './template-provider.service';
import { StratumV1ClientStatistics } from '../models/StratumV1ClientStatistics';
import type { AddressObject } from '../models/MiningJob';
import { PayoutSnapshotService } from '../ORM/payout-snapshot/payout-snapshot.service';
import { parsePayoutModePorts, PayoutMode } from '../types/payout-mode';
const DEFAULT_DATUM_SHARE_DIFFICULTY = 1; const DEFAULT_DATUM_SHARE_DIFFICULTY = 1;
const DEFAULT_DATUM_PING_INTERVAL_MS = 30_000; const DEFAULT_DATUM_PING_INTERVAL_MS = 30_000;
const DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS = 60_000;
@Injectable() @Injectable()
export class DatumService implements OnModuleInit { export class DatumService implements OnModuleInit {
@@ -55,6 +61,7 @@ export class DatumService implements OnModuleInit {
private readonly customWorkService: CustomWorkService, private readonly customWorkService: CustomWorkService,
private readonly templateProvider: TemplateProviderService, private readonly templateProvider: TemplateProviderService,
private readonly redisMessagingService?: RedisMessagingService, private readonly redisMessagingService?: RedisMessagingService,
private readonly payoutSnapshotService?: PayoutSnapshotService,
) {} ) {}
public async onModuleInit(): Promise<void> { public async onModuleInit(): Promise<void> {
@@ -70,25 +77,25 @@ export class DatumService implements OnModuleInit {
this.identityKeys = this.getIdentityKeys(); this.identityKeys = this.getIdentityKeys();
console.log(`DATUM server public key: ${Buffer.concat([this.identityKeys.edPublicKey, this.identityKeys.xPublicKey]).toString('hex')}`); console.log(`DATUM server public key: ${Buffer.concat([this.identityKeys.edPublicKey, this.identityKeys.xPublicKey]).toString('hex')}`);
for (const port of ports) { for (const { port, payoutMode } of ports) {
await this.startServer(port); await this.startServer(port, payoutMode);
} }
} }
private async startServer(port: number): Promise<void> { private async startServer(port: number, payoutMode: PayoutMode): Promise<void> {
const server = new Server(socket => { const server = new Server(socket => {
void this.handleSocket(socket); void this.handleSocket(socket, payoutMode);
}); });
server.on('error', error => { server.on('error', error => {
console.error(`DATUM server error on port ${port}: ${error.message}`); console.error(`DATUM server error on port ${port}: ${error.message}`);
}); });
server.listen(port, () => { server.listen(port, () => {
console.log(`DATUM server is listening on port ${port}`); console.log(`DATUM ${payoutMode} server is listening on port ${port}`);
}); });
this.servers.push(server); this.servers.push(server);
} }
private async handleSocket(socket: Socket): Promise<void> { private async handleSocket(socket: Socket, payoutMode: PayoutMode): Promise<void> {
socket.setKeepAlive(true, 60_000); socket.setKeepAlive(true, 60_000);
socket.setNoDelay(true); socket.setNoDelay(true);
@@ -96,6 +103,7 @@ export class DatumService implements OnModuleInit {
const reader = new DatumFrameReader(DATUM_INITIAL_HEADER_KEY); const reader = new DatumFrameReader(DATUM_INITIAL_HEADER_KEY);
const state: DatumClientState = { const state: DatumClientState = {
sessionId: Math.random().toString(16).slice(2, 10), sessionId: Math.random().toString(16).slice(2, 10),
payoutMode,
session, session,
clientEntity: null, clientEntity: null,
address: null, address: null,
@@ -103,6 +111,10 @@ export class DatumService implements OnModuleInit {
userAgent: 'datum/unknown', userAgent: 'datum/unknown',
pingTimer: null, pingTimer: null,
datumJobs: new Map(), datumJobs: new Map(),
coinbaserPayoutContexts: new Map(),
nextCoinbaserId: 1,
statistics: new StratumV1ClientStatistics(this.getConfiguredDatumShareDifficulty()),
lastHashRatePersistedAt: 0,
}; };
console.log(`[DATUM ${state.sessionId}] connection accepted from ${socket.remoteAddress}:${socket.remotePort}`); console.log(`[DATUM ${state.sessionId}] connection accepted from ${socket.remoteAddress}:${socket.remotePort}`);
@@ -188,7 +200,7 @@ export class DatumService implements OnModuleInit {
throw new Error(`DATUM coinbase tag is too long: ${coinbaseTag.length}`); throw new Error(`DATUM coinbase tag is too long: ${coinbaseTag.length}`);
} }
const minDifficulty = Math.max(1, Math.floor(this.getDatumShareDifficulty())); const minDifficulty = Math.max(1, Math.floor(this.getConfiguredDatumShareDifficulty()));
const vardiffMin = 1n << BigInt(Math.ceil(Math.log2(minDifficulty))); const vardiffMin = 1n << BigInt(Math.ceil(Math.log2(minDifficulty)));
const vardiffMinBuffer = Buffer.alloc(8); const vardiffMinBuffer = Buffer.alloc(8);
vardiffMinBuffer.writeBigUInt64LE(vardiffMin, 0); vardiffMinBuffer.writeBigUInt64LE(vardiffMin, 0);
@@ -208,16 +220,27 @@ export class DatumService implements OnModuleInit {
private async handleCoinbaserFetch(socket: Socket, state: DatumClientState, payload: Buffer): Promise<void> { private async handleCoinbaserFetch(socket: Socket, state: DatumClientState, payload: Buffer): Promise<void> {
const fetch = deserializeDatumCoinbaserFetch(payload); const fetch = deserializeDatumCoinbaserFetch(payload);
const payoutAddress = this.getDatumPoolPayoutAddress(); const latestTemplate = await firstValueFrom(this.jobsService.newMiningJob$);
if (!payoutAddress) { const payoutOutputs = this.getDatumPayoutOutputs(latestTemplate, Number(fetch.rewardValue), state.payoutMode);
if (payoutOutputs.length === 0) {
throw new Error('DATUM_POOL_PAYOUT_ADDRESS or DEV_FEE_ADDRESS must be set before DATUM coinbaser fetches can be served'); throw new Error('DATUM_POOL_PAYOUT_ADDRESS or DEV_FEE_ADDRESS must be set before DATUM coinbaser fetches can be served');
} }
const scriptPubKey = bitcoinjs.address.toOutputScript(payoutAddress, this.getNetwork()); const coinbaserId = this.nextDatumCoinbaserId(state);
const response = serializeDatumCoinbaserFetchResponse(fetch.rewardValue, [{ state.coinbaserPayoutContexts.set(coinbaserId, {
value: fetch.rewardValue, payoutOutputs,
scriptPubKey, payoutSnapshotId: latestTemplate.blockData.payoutSnapshotId ?? null,
}]); blockHeight: latestTemplate.blockData.height,
payoutMode: state.payoutMode,
});
if (state.coinbaserPayoutContexts.size > 512) {
const oldestCoinbaserId = state.coinbaserPayoutContexts.keys().next().value;
if (oldestCoinbaserId != null) {
state.coinbaserPayoutContexts.delete(oldestCoinbaserId);
}
}
const response = serializeDatumCoinbaserFetchResponse(fetch.rewardValue, payoutOutputs, coinbaserId);
await this.writeRaw(socket, state.session.encryptChannelFrame(DatumProtocolCommand.MINING, response)); await this.writeRaw(socket, state.session.encryptChannelFrame(DatumProtocolCommand.MINING, response));
} }
@@ -273,8 +296,14 @@ export class DatumService implements OnModuleInit {
await this.sendShareResponse(socket, state, DatumShareResponseStatus.REJECTED, DatumRejectReason.OTHER, pow.nonce, pow.targetByte, pow.jobId); await this.sendShareResponse(socket, state, DatumShareResponseStatus.REJECTED, DatumRejectReason.OTHER, pow.nonce, pow.targetByte, pow.jobId);
return; return;
} }
const payoutValidation = this.validateDatumCoinbasePayouts(coinbase, pow, latestTemplate, datumJob.coinbaseValue, datumJob.expectedPayoutOutputs, state.payoutMode);
if (!payoutValidation.valid) {
this.logDatumCoinbaseMismatchOnce(state, payoutValidation);
await this.sendShareResponse(socket, state, DatumShareResponseStatus.REJECTED, DatumRejectReason.BAD_COINBASER_ID, pow.nonce, pow.targetByte, pow.jobId);
return;
}
const shareDifficulty = this.getDatumShareDifficulty(); const shareDifficulty = this.getDatumSubmittedShareDifficulty(pow);
const nBits = datumJob.nBits.readUInt32LE(0); const nBits = datumJob.nBits.readUInt32LE(0);
const validation = this.customWorkService.validateShare({ const validation = this.customWorkService.validateShare({
coinbasePrefix: coinbase.coinb1, coinbasePrefix: coinbase.coinb1,
@@ -310,11 +339,23 @@ export class DatumService implements OnModuleInit {
sessionId: state.sessionId, sessionId: state.sessionId,
blockData: validation.header.toString('hex'), blockData: validation.header.toString('hex'),
blockSubmissionResult, blockSubmissionResult,
payoutSnapshotId: null, payoutSnapshotId: state.payoutMode === 'pplns'
? datumJob.payoutSnapshotId ?? null
: null,
payoutMode: state.payoutMode,
}); });
if (state.payoutMode === 'pplns') {
await this.payoutSnapshotService?.finalizeSnapshotForBlock({
payoutSnapshotId: datumJob.payoutSnapshotId,
blockHeight: datumJob.height ?? latestTemplate.blockData.height,
blockSubmissionResult,
payoutMode: state.payoutMode,
});
}
} }
await this.shareAccountingService.recordAcceptedShare({ await this.shareAccountingService.recordAcceptedShare({
protocol: 'datum', protocol: 'datum',
payoutMode: state.payoutMode,
workSource: 'miner_template', workSource: 'miner_template',
workProtocol: 'datum', workProtocol: 'datum',
address, address,
@@ -334,17 +375,27 @@ export class DatumService implements OnModuleInit {
isBlockCandidate, isBlockCandidate,
blockSubmissionResult, blockSubmissionResult,
}); });
await this.redisMessagingService?.setClientPresence({ await this.updateAcceptedSharePresence(state, address, workerName, validation.submissionDifficulty, shareDifficulty);
clientId: state.clientEntity.id, }
address,
clientName: workerName, private async updateAcceptedSharePresence(
sessionId: state.sessionId, state: DatumClientState,
userAgent: state.userAgent, address: string,
startTime: new Date(state.clientEntity.startTime).toISOString(), workerName: string,
lastSeen: new Date().toISOString(), submissionDifficulty: number,
hashRate: 0, creditedDifficulty: number,
bestDifficulty: validation.submissionDifficulty, ): Promise<void> {
}); if (state.clientEntity == null) {
return;
}
await state.statistics.addShares(state.clientEntity, creditedDifficulty);
state.clientEntity.hashRate = state.statistics.hashRate;
await this.persistClientHashRate(state, new Date());
if (submissionDifficulty > Number(state.clientEntity.bestDifficulty ?? 0)) {
await this.clientService.updateBestDifficultyIfHigher(state.clientEntity.id, submissionDifficulty);
state.clientEntity.bestDifficulty = submissionDifficulty;
}
} }
private updateDatumJobCache(state: DatumClientState, pow: DatumPowSubmit): DatumJobCache { private updateDatumJobCache(state: DatumClientState, pow: DatumPowSubmit): DatumJobCache {
@@ -367,6 +418,11 @@ export class DatumService implements OnModuleInit {
} }
if (pow.coinbaserId != null) { if (pow.coinbaserId != null) {
cache.coinbaserId = pow.coinbaserId; cache.coinbaserId = pow.coinbaserId;
const payoutContext = state.coinbaserPayoutContexts.get(pow.coinbaserId);
if (payoutContext != null) {
cache.expectedPayoutOutputs = payoutContext.payoutOutputs;
cache.payoutSnapshotId = payoutContext.payoutSnapshotId;
}
} }
if (pow.height != null) { if (pow.height != null) {
cache.height = pow.height; cache.height = pow.height;
@@ -507,6 +563,152 @@ export class DatumService implements OnModuleInit {
return cache.coinbasePairs.get(pow.coinbaseId) ?? cache.subsidyOnlyCoinbase; return cache.coinbasePairs.get(pow.coinbaseId) ?? cache.subsidyOnlyCoinbase;
} }
private validateDatumCoinbasePayouts(
coinbase: { coinb1: Buffer; coinb2: Buffer },
pow: Pick<DatumPowSubmit, 'extranonce' | 'targetByteIndex' | 'targetByte'>,
latestTemplate: IJobTemplate,
coinbaseValue?: bigint,
expectedPayoutOutputs?: DatumPayoutOutput[],
payoutMode?: PayoutMode,
): DatumCoinbasePayoutValidation {
const rewardValue = coinbaseValue == null
? latestTemplate.blockData.coinbasevalue
: Number(coinbaseValue);
const expectedOutputs = expectedPayoutOutputs ?? this.getDatumPayoutOutputs(latestTemplate, rewardValue, payoutMode);
if (expectedOutputs.length === 0) {
return { valid: false, expectedOutputs, submittedOutputs: [], error: 'missing-expected-outputs' };
}
let coinbaseTx = Buffer.concat([
coinbase.coinb1,
pow.extranonce,
coinbase.coinb2,
]);
coinbaseTx = Buffer.from(coinbaseTx);
if (pow.targetByteIndex != null) {
if (pow.targetByteIndex < 0 || pow.targetByteIndex >= coinbaseTx.length) {
return { valid: false, expectedOutputs, submittedOutputs: [], error: 'target-byte-out-of-range' };
}
coinbaseTx[pow.targetByteIndex] = pow.targetByte & 0xff;
}
let transaction: bitcoinjs.Transaction;
try {
transaction = bitcoinjs.Transaction.fromBuffer(coinbaseTx);
} catch {
return { valid: false, expectedOutputs, submittedOutputs: [], error: 'invalid-coinbase-transaction' };
}
const submittedOutputs = transaction.outs
.filter(output => !this.isIgnoredCoinbaseMetadataOutput(output))
.map(output => ({
value: BigInt(output.value),
scriptPubKey: Buffer.from(output.script),
}));
if (submittedOutputs.length !== expectedOutputs.length) {
return { valid: false, expectedOutputs, submittedOutputs, error: 'output-count-mismatch' };
}
const valid = expectedOutputs.every((expected, index) => {
const submitted = submittedOutputs[index];
return submitted.value === expected.value
&& submitted.scriptPubKey.equals(expected.scriptPubKey);
});
return {
valid,
expectedOutputs,
submittedOutputs,
error: valid ? undefined : 'output-mismatch',
};
}
private getDatumPayoutOutputs(latestTemplate: { blockData?: { payoutOutputs?: AddressObject[] } }, rewardValue: number, payoutMode: PayoutMode = 'solo'): DatumPayoutOutput[] {
const configuredOutputs = latestTemplate?.blockData?.payoutOutputs;
const payoutAddresses = payoutMode === 'pplns' && configuredOutputs?.length > 0
? configuredOutputs
: this.getDatumFallbackPayoutOutputs(rewardValue);
let rewardBalance = Math.max(0, Math.floor(rewardValue));
const outputs = payoutAddresses.map((recipientAddress, index) => {
const amount = recipientAddress.amountSats == null
? Math.floor(((recipientAddress.percent ?? 0) / 100) * rewardValue)
: recipientAddress.amountSats;
rewardBalance -= amount;
return {
value: BigInt(amount),
scriptPubKey: bitcoinjs.address.toOutputScript(recipientAddress.address, this.getNetwork()),
};
});
if (outputs.length > 0 && rewardBalance !== 0) {
outputs[0] = {
...outputs[0],
value: outputs[0].value + BigInt(rewardBalance),
};
}
return outputs;
}
private nextDatumCoinbaserId(state: DatumClientState): number {
const id = state.nextCoinbaserId;
state.nextCoinbaserId = state.nextCoinbaserId >= 254 ? 1 : state.nextCoinbaserId + 1;
return id;
}
private getDatumFallbackPayoutOutputs(rewardValue: number): AddressObject[] {
const payoutAddress = this.getDatumPoolPayoutAddress();
if (!payoutAddress) {
return [];
}
return [{ address: payoutAddress, amountSats: Math.max(0, Math.floor(rewardValue)) }];
}
private isIgnoredCoinbaseMetadataOutput(output: { value: bigint | number; script: Buffer }): boolean {
if (this.isWitnessCommitmentOutput(output.script)) {
return true;
}
return BigInt(output.value) === 0n
&& output.script.length > 0
&& output.script[0] === bitcoinjs.opcodes.OP_RETURN;
}
private isWitnessCommitmentOutput(script: Buffer): boolean {
return script.length === 38
&& script[0] === bitcoinjs.opcodes.OP_RETURN
&& script[1] === 0x24
&& script.subarray(2, 6).equals(Buffer.from('aa21a9ed', 'hex'));
}
private logDatumCoinbaseMismatchOnce(
state: DatumClientState,
validation: DatumCoinbasePayoutValidation,
): void {
if (state.coinbaseMismatchLogged) {
return;
}
state.coinbaseMismatchLogged = true;
console.warn(`[DATUM ${state.sessionId}] Coinbase payout mismatch (${validation.error}); expected=${this.describeDatumOutputs(validation.expectedOutputs)} submitted=${this.describeDatumOutputs(validation.submittedOutputs)}`);
}
private describeDatumOutputs(outputs: DatumPayoutOutput[]): string {
return outputs
.map(output => {
const address = this.tryOutputAddress(output.scriptPubKey);
return `${output.value.toString()}:${address ?? output.scriptPubKey.toString('hex')}`;
})
.join(',');
}
private tryOutputAddress(scriptPubKey: Buffer): string | null {
try {
return bitcoinjs.address.fromOutputScript(scriptPubKey, this.getNetwork());
} catch {
return null;
}
}
private async sendShareResponse( private async sendShareResponse(
socket: Socket, socket: Socket,
state: DatumClientState, state: DatumClientState,
@@ -530,16 +732,49 @@ export class DatumService implements OnModuleInit {
clientName: state.workerName, clientName: state.workerName,
userAgent: state.userAgent, userAgent: state.userAgent,
startTime: new Date(), startTime: new Date(),
payoutMode: state.payoutMode,
bestDifficulty: 0, bestDifficulty: 0,
}); });
} }
private async persistClientHashRate(state: DatumClientState, now: Date): Promise<void> {
if (state.clientEntity?.id == null) {
return;
}
const hashRate = Number(state.statistics?.hashRate ?? 0);
if (!Number.isFinite(hashRate) || hashRate <= 0) {
return;
}
const intervalMs = this.getHashRatePersistIntervalMs();
const nowMs = now.getTime();
if (state.lastHashRatePersistedAt > 0 && nowMs - state.lastHashRatePersistedAt < intervalMs) {
return;
}
state.lastHashRatePersistedAt = nowMs;
try {
await this.clientService.updateHashRate(state.clientEntity.id, hashRate, now);
} catch (error) {
console.error(`Failed to persist DATUM client hashrate: ${error.message}`);
}
}
private getHashRatePersistIntervalMs(): number {
const configured = Number(this.configService.get<string>('CLIENT_HASHRATE_PERSIST_INTERVAL_MS'));
if (Number.isFinite(configured) && configured >= 0) {
return configured;
}
return DEFAULT_CLIENT_HASHRATE_PERSIST_INTERVAL_MS;
}
private async destroyClient(state: DatumClientState): Promise<void> { private async destroyClient(state: DatumClientState): Promise<void> {
this.stopDatumPing(state); this.stopDatumPing(state);
if (state.clientEntity?.id == null) { if (state.clientEntity?.id == null) {
return; return;
} }
await this.redisMessagingService?.removeClientPresence(state.clientEntity.id, state.clientEntity.address);
await this.clientService.delete(state.clientEntity.id); await this.clientService.delete(state.clientEntity.id);
state.clientEntity = null; state.clientEntity = null;
} }
@@ -612,11 +847,18 @@ export class DatumService implements OnModuleInit {
|| ''; || '';
} }
private getDatumShareDifficulty(): number { private getConfiguredDatumShareDifficulty(): number {
const configured = parseFloat(this.configService.get<string>('DATUM_SHARE_DIFFICULTY') ?? ''); const configured = parseFloat(this.configService.get<string>('DATUM_SHARE_DIFFICULTY') ?? '');
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_DATUM_SHARE_DIFFICULTY; return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_DATUM_SHARE_DIFFICULTY;
} }
private getDatumSubmittedShareDifficulty(pow: Pick<DatumPowSubmit, 'targetByte'>): number {
if (!Number.isInteger(pow.targetByte) || pow.targetByte < 0 || pow.targetByte > 63) {
return this.getConfiguredDatumShareDifficulty();
}
return Math.pow(2, pow.targetByte);
}
private mapDatumTemplateRejectReason(errorCode?: string): DatumRejectReason { private mapDatumTemplateRejectReason(errorCode?: string): DatumRejectReason {
switch (errorCode) { switch (errorCode) {
case 'prevhash-mismatch': case 'prevhash-mismatch':
@@ -655,15 +897,11 @@ export class DatumService implements OnModuleInit {
return DatumCryptoSession.generateKeyPairFromSeed(Buffer.from(seedHex, 'hex')); return DatumCryptoSession.generateKeyPairFromSeed(Buffer.from(seedHex, 'hex'));
} }
private getPorts(): number[] { private getPorts(): { port: number; payoutMode: PayoutMode }[] {
const configured = this.configService.get<string>('DATUM_PORTS'); return parsePayoutModePorts(
if (!configured?.trim()) { this.configService.get<string>('DATUM_PORTS'),
return []; this.configService.get<string>('PPLNS_DATUM_PORTS'),
} );
return Array.from(new Set(configured
.split(',')
.map(port => parseInt(port.trim(), 10))
.filter(port => Number.isInteger(port) && port > 0 && port <= 65535)));
} }
private getNetwork(): bitcoinjs.networks.Network { private getNetwork(): bitcoinjs.networks.Network {
@@ -683,6 +921,7 @@ export class DatumService implements OnModuleInit {
interface DatumClientState { interface DatumClientState {
sessionId: string; sessionId: string;
payoutMode: PayoutMode;
session: DatumCryptoSession; session: DatumCryptoSession;
clientEntity: ClientEntity | null; clientEntity: ClientEntity | null;
address: string | null; address: string | null;
@@ -690,6 +929,18 @@ interface DatumClientState {
userAgent: string; userAgent: string;
pingTimer: NodeJS.Timeout | null; pingTimer: NodeJS.Timeout | null;
datumJobs: Map<number, DatumJobCache>; datumJobs: Map<number, DatumJobCache>;
coinbaserPayoutContexts: Map<number, DatumCoinbaserPayoutContext>;
nextCoinbaserId: number;
statistics: StratumV1ClientStatistics;
lastHashRatePersistedAt: number;
coinbaseMismatchLogged?: boolean;
}
interface DatumCoinbaserPayoutContext {
payoutOutputs: DatumPayoutOutput[];
payoutSnapshotId?: string | null;
blockHeight?: number;
payoutMode?: PayoutMode;
} }
interface DatumJobCache { interface DatumJobCache {
@@ -713,6 +964,15 @@ interface DatumJobCache {
validationShortTxCrosscheck?: Buffer; validationShortTxCrosscheck?: Buffer;
validationTransactions?: Buffer[]; validationTransactions?: Buffer[];
validationError?: string; validationError?: string;
expectedPayoutOutputs?: DatumPayoutOutput[];
payoutSnapshotId?: string | null;
}
interface DatumCoinbasePayoutValidation {
valid: boolean;
expectedOutputs: DatumPayoutOutput[];
submittedOutputs: DatumPayoutOutput[];
error?: string;
} }
function uint32le(value: number): Buffer { function uint32le(value: number): Buffer {
@@ -61,58 +61,6 @@ describe('RedisMessagingService', () => {
consoleSpy.mockRestore(); consoleSpy.mockRestore();
}); });
it('should store, index, and remove client presence', async () => {
await service.connect();
await service.setClientPresence({
clientId: '00000000-0000-4000-8000-000000000001',
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
clientName: 'worker',
sessionId: '57a6f098',
userAgent: 'bitaxe',
startTime: '2026-06-07T12:00:00.000Z',
lastSeen: '2026-06-07T12:01:00.000Z',
hashRate: 100,
bestDifficulty: 200,
});
expect(await service.getClientPresence('00000000-0000-4000-8000-000000000001'))
.toEqual(expect.objectContaining({
clientId: '00000000-0000-4000-8000-000000000001',
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
hashRate: 100,
bestDifficulty: 200,
}));
expect(await service.getClientPresenceByAddress('tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4'))
.toHaveLength(1);
expect(await service.getAllClientPresence()).toHaveLength(1);
await service.removeClientPresence('00000000-0000-4000-8000-000000000001');
expect(await service.getAllClientPresence()).toHaveLength(0);
});
it('should clear all client presence keys', async () => {
await service.connect();
await service.setClientPresence({
clientId: '00000000-0000-4000-8000-000000000001',
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
clientName: 'worker',
sessionId: '57a6f098',
userAgent: 'bitaxe',
startTime: '2026-06-07T12:00:00.000Z',
lastSeen: '2026-06-07T12:01:00.000Z',
hashRate: 100,
bestDifficulty: 200,
});
await service.clearClientPresence();
expect(await service.getAllClientPresence()).toHaveLength(0);
expect([...store.keys()].filter(key => key.startsWith('client-presence'))).toHaveLength(0);
expect([...sets.keys()].filter(key => key.startsWith('client-presence'))).toHaveLength(0);
});
}); });
const store = new Map<string, string>(); const store = new Map<string, string>();
+1 -176
View File
@@ -8,37 +8,18 @@ import { IMiningInfo } from '../models/bitcoin-rpc/IMiningInfo';
const MINING_INFO_CHANNEL = 'mining-info.updated'; const MINING_INFO_CHANNEL = 'mining-info.updated';
const MINING_INFO_KEY = 'mining-info:latest'; const MINING_INFO_KEY = 'mining-info:latest';
const BLOCK_TEMPLATE_LATEST_KEY = 'block-template:latest'; const BLOCK_TEMPLATE_LATEST_KEY = 'block-template:latest';
const CLIENT_PRESENCE_TTL_SECONDS = 180;
const blockTemplateKey = (height: number) => `block-template:${height}`; const blockTemplateKey = (height: number) => `block-template:${height}`;
const CLIENT_PRESENCE_ALL_KEY = 'client-presence:all';
const clientPresenceKey = (clientId: string) => `client-presence:${clientId}`;
const clientPresenceAddressKey = (address: string) => `client-presence:address:${address}`;
const jsonCacheKey = (key: string) => `json-cache:${key}`; const jsonCacheKey = (key: string) => `json-cache:${key}`;
export interface ClientPresence {
clientId: string;
address: string;
clientName: string;
sessionId: string;
userAgent?: string | null;
startTime: string;
lastSeen: string;
hashRate: number;
bestDifficulty: number;
}
@Injectable() @Injectable()
export class RedisMessagingService implements OnModuleInit, OnModuleDestroy { export class RedisMessagingService implements OnModuleInit, OnModuleDestroy {
private publisher: RedisClientType; private publisher: RedisClientType;
private subscriber: RedisClientType; private subscriber: RedisClientType;
private connected = false; private connected = false;
private readonly clientPresenceTtlSeconds: number;
constructor( constructor(
private readonly configService: ConfigService, private readonly configService: ConfigService,
) { ) { }
this.clientPresenceTtlSeconds = this.readPositiveInt('CLIENT_PRESENCE_TTL_SECONDS', CLIENT_PRESENCE_TTL_SECONDS);
}
public async onModuleInit() { public async onModuleInit() {
await this.connect().catch(error => { await this.connect().catch(error => {
@@ -136,89 +117,6 @@ export class RedisMessagingService implements OnModuleInit, OnModuleDestroy {
return value == null ? null : JSON.parse(value as string); return value == null ? null : JSON.parse(value as string);
} }
public async setClientPresence(presence: ClientPresence): Promise<void> {
if (!await this.ensureConnected()) {
return;
}
const serialized = JSON.stringify({
...presence,
userAgent: presence.userAgent ?? null,
hashRate: Number.isFinite(Number(presence.hashRate)) ? Number(presence.hashRate) : 0,
bestDifficulty: Number.isFinite(Number(presence.bestDifficulty)) ? Number(presence.bestDifficulty) : 0,
});
await Promise.all([
this.publisher.setEx(clientPresenceKey(presence.clientId), this.clientPresenceTtlSeconds, serialized),
this.publisher.sAdd(CLIENT_PRESENCE_ALL_KEY, presence.clientId),
this.publisher.sAdd(clientPresenceAddressKey(presence.address), presence.clientId),
]);
}
public async removeClientPresence(clientId: string, address?: string): Promise<void> {
if (!await this.ensureConnected()) {
return;
}
let resolvedAddress = address;
if (resolvedAddress == null) {
const presence = await this.getClientPresence(clientId);
resolvedAddress = presence?.address;
}
const removals: Promise<unknown>[] = [
this.publisher.del(clientPresenceKey(clientId)),
this.publisher.sRem(CLIENT_PRESENCE_ALL_KEY, clientId),
];
if (resolvedAddress != null) {
removals.push(this.publisher.sRem(clientPresenceAddressKey(resolvedAddress), clientId));
}
await Promise.all(removals);
}
public async getClientPresence(clientId: string): Promise<ClientPresence | null> {
if (!await this.ensureConnected()) {
return null;
}
const value = await this.publisher.get(clientPresenceKey(clientId));
return this.parseClientPresence(value);
}
public async getClientPresenceByAddress(address: string): Promise<ClientPresence[]> {
if (!await this.ensureConnected()) {
return [];
}
return this.getPresenceFromSet(clientPresenceAddressKey(address));
}
public async getAllClientPresence(): Promise<ClientPresence[]> {
if (!await this.ensureConnected()) {
return [];
}
return this.getPresenceFromSet(CLIENT_PRESENCE_ALL_KEY);
}
public async clearClientPresence(): Promise<void> {
if (!await this.ensureConnected()) {
return;
}
const batch: string[] = [];
for await (const keyOrKeys of (this.publisher as any).scanIterator({ MATCH: 'client-presence*', COUNT: 1000 })) {
const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];
batch.push(...keys.map(key => key as string));
if (batch.length >= 500) {
await this.deleteKeys(batch.splice(0));
}
}
await this.deleteKeys(batch);
}
public async getJsonCache<T>(key: string): Promise<T | null> { public async getJsonCache<T>(key: string): Promise<T | null> {
if (!await this.ensureConnected()) { if (!await this.ensureConnected()) {
return null; return null;
@@ -262,77 +160,4 @@ export class RedisMessagingService implements OnModuleInit, OnModuleDestroy {
return true; return true;
} }
private async getPresenceFromSet(setKey: string): Promise<ClientPresence[]> {
const clientIds = await this.publisher.sMembers(setKey);
if (clientIds.length === 0) {
return [];
}
const presences: ClientPresence[] = [];
const staleClientIds: string[] = [];
for (let i = 0; i < clientIds.length; i += 1000) {
const chunk = clientIds.slice(i, i + 1000);
const values = await this.publisher.mGet(chunk.map(clientPresenceKey));
values.forEach((value, index) => {
const presence = this.parseClientPresence(value);
if (presence == null) {
staleClientIds.push(chunk[index]);
return;
}
presences.push(presence);
});
}
for (let i = 0; i < staleClientIds.length; i += 1000) {
const staleChunk = staleClientIds.slice(i, i + 1000);
if (staleChunk.length === 0) {
continue;
}
await this.publisher.sRem(setKey, staleChunk);
if (setKey !== CLIENT_PRESENCE_ALL_KEY) {
await this.publisher.sRem(CLIENT_PRESENCE_ALL_KEY, staleChunk);
}
}
return presences;
}
private parseClientPresence(value: unknown): ClientPresence | null {
if (value == null) {
return null;
}
try {
const parsed = JSON.parse(value as string);
if (parsed?.clientId == null || parsed?.address == null) {
return null;
}
return {
clientId: parsed.clientId,
address: parsed.address,
clientName: parsed.clientName ?? 'default',
sessionId: parsed.sessionId ?? parsed.clientId,
userAgent: parsed.userAgent ?? null,
startTime: parsed.startTime,
lastSeen: parsed.lastSeen,
hashRate: Number(parsed.hashRate ?? 0),
bestDifficulty: Number(parsed.bestDifficulty ?? 0),
};
} catch (error) {
console.error(`Invalid Redis client presence: ${error.message}`);
return null;
}
}
private readPositiveInt(name: string, defaultValue: number): number {
const value = Number(this.configService.get<string>(name) ?? process.env[name]);
return Number.isInteger(value) && value > 0 ? value : defaultValue;
}
private async deleteKeys(keys: string[]): Promise<void> {
if (keys.length === 0) {
return;
}
await (this.publisher as any).del(...keys);
}
} }
+9 -7
View File
@@ -31,9 +31,7 @@ describe('StratumV1Service', () => {
ensureInitialized: jest.fn().mockResolvedValue(undefined), ensureInitialized: jest.fn().mockResolvedValue(undefined),
createClient: jest.fn() createClient: jest.fn()
}; };
redisMessagingService = { redisMessagingService = {};
clearClientPresence: jest.fn().mockResolvedValue(undefined)
};
service = new StratumV1Service( service = new StratumV1Service(
{} as any, {} as any,
clientService, clientService,
@@ -75,7 +73,6 @@ describe('StratumV1Service', () => {
jest.runOnlyPendingTimers(); jest.runOnlyPendingTimers();
expect(clientService.deleteAll).toHaveBeenCalled(); expect(clientService.deleteAll).toHaveBeenCalled();
expect(redisMessagingService.clearClientPresence).toHaveBeenCalled();
expect(userAgentReportService.refreshReport).toHaveBeenCalled(); expect(userAgentReportService.refreshReport).toHaveBeenCalled();
expect(startSocketServerSpy).not.toHaveBeenCalled(); expect(startSocketServerSpy).not.toHaveBeenCalled();
expect(startSecureSocketServerSpy).not.toHaveBeenCalled(); expect(startSecureSocketServerSpy).not.toHaveBeenCalled();
@@ -85,8 +82,10 @@ describe('StratumV1Service', () => {
it('should start Stratum listeners in worker processes', async () => { it('should start Stratum listeners in worker processes', async () => {
process.env.MASTER = 'false'; process.env.MASTER = 'false';
process.env.STRATUM_PORTS = '3333,3334'; process.env.STRATUM_PORTS = '3333,3334';
process.env.PPLNS_STRATUM_PORTS = '13333';
process.env.STRATUM_SECURE = 'true'; process.env.STRATUM_SECURE = 'true';
process.env.SECURE_STRATUM_PORTS = '4333'; process.env.SECURE_STRATUM_PORTS = '4333';
process.env.PPLNS_SECURE_STRATUM_PORTS = '14333';
const startSocketServerSpy = jest.spyOn(service as any, 'startSocketServer').mockImplementation(() => undefined); const startSocketServerSpy = jest.spyOn(service as any, 'startSocketServer').mockImplementation(() => undefined);
const startSecureSocketServerSpy = jest.spyOn(service as any, 'startSecureSocketServer').mockImplementation(() => undefined); const startSecureSocketServerSpy = jest.spyOn(service as any, 'startSecureSocketServer').mockImplementation(() => undefined);
@@ -95,9 +94,11 @@ describe('StratumV1Service', () => {
expect(clientService.deleteAll).not.toHaveBeenCalled(); expect(clientService.deleteAll).not.toHaveBeenCalled();
expect(userAgentReportService.refreshReport).not.toHaveBeenCalled(); expect(userAgentReportService.refreshReport).not.toHaveBeenCalled();
expect(startSocketServerSpy).toHaveBeenCalledWith(3333); expect(startSocketServerSpy).toHaveBeenCalledWith(3333, 'solo');
expect(startSocketServerSpy).toHaveBeenCalledWith(3334); expect(startSocketServerSpy).toHaveBeenCalledWith(3334, 'solo');
expect(startSecureSocketServerSpy).toHaveBeenCalledWith(4333); expect(startSocketServerSpy).toHaveBeenCalledWith(13333, 'pplns');
expect(startSecureSocketServerSpy).toHaveBeenCalledWith(4333, 'solo');
expect(startSecureSocketServerSpy).toHaveBeenCalledWith(14333, 'pplns');
}); });
it('should pause listeners when worker backpressure is high', () => { it('should pause listeners when worker backpressure is high', () => {
@@ -105,6 +106,7 @@ describe('StratumV1Service', () => {
(service as any).listeners.push({ (service as any).listeners.push({
port: 3333, port: 3333,
secure: false, secure: false,
payoutMode: 'solo',
server: { close }, server: { close },
paused: false paused: false
}); });
+25 -15
View File
@@ -16,6 +16,7 @@ import { NotificationService } from './notification.service';
import { RedisMessagingService } from './redis-messaging.service'; import { RedisMessagingService } from './redis-messaging.service';
import { StratumV1JobsService } from './stratum-v1-jobs.service'; import { StratumV1JobsService } from './stratum-v1-jobs.service';
import { StratumV2Service } from './stratum-v2.service'; import { StratumV2Service } from './stratum-v2.service';
import { parsePayoutModePorts, PayoutMode } from '../types/payout-mode';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { TlsOptions, TLSSocket, createServer } from 'tls'; import { TlsOptions, TLSSocket, createServer } from 'tls';
@@ -24,6 +25,7 @@ import * as path from 'path';
interface StratumListenerState { interface StratumListenerState {
port: number; port: number;
secure: boolean; secure: boolean;
payoutMode: PayoutMode;
server: Server | null; server: Server | null;
paused: boolean; paused: boolean;
} }
@@ -79,7 +81,6 @@ export class StratumV1Service implements OnModuleInit {
if (process.env.MASTER == 'true') { if (process.env.MASTER == 'true') {
await this.clientService.deleteAll(); await this.clientService.deleteAll();
await this.redisMessagingService?.clearClientPresence();
await this.userAgentReportService.refreshReport(); await this.userAgentReportService.refreshReport();
console.log('Master process skipping Stratum socket listeners'); console.log('Master process skipping Stratum socket listeners');
return; return;
@@ -87,12 +88,18 @@ export class StratumV1Service implements OnModuleInit {
// wait for all the other processes to init for an even connection distribution // wait for all the other processes to init for an even connection distribution
setTimeout(() => { setTimeout(() => {
process.env.STRATUM_PORTS.split(',').forEach(port => { parsePayoutModePorts(
this.startSocketServer(parseInt(port)); process.env.STRATUM_PORTS,
process.env.PPLNS_STRATUM_PORTS,
).forEach(({ port, payoutMode }) => {
this.startSocketServer(port, payoutMode);
}); });
if (process.env.STRATUM_SECURE?.toLowerCase() === 'true') { if (process.env.STRATUM_SECURE?.toLowerCase() === 'true') {
process.env.SECURE_STRATUM_PORTS.split(',').forEach(port => { parsePayoutModePorts(
this.startSecureSocketServer(parseInt(port)); process.env.SECURE_STRATUM_PORTS,
process.env.PPLNS_SECURE_STRATUM_PORTS,
).forEach(({ port, payoutMode }) => {
this.startSecureSocketServer(port, payoutMode);
}); });
} }
}, (10000)); }, (10000));
@@ -109,10 +116,11 @@ export class StratumV1Service implements OnModuleInit {
} }
private startSocketServer(port: number) { private startSocketServer(port: number, payoutMode: PayoutMode) {
const listener: StratumListenerState = { const listener: StratumListenerState = {
port, port,
secure: false, secure: false,
payoutMode,
server: null, server: null,
paused: false paused: false
}; };
@@ -120,7 +128,7 @@ export class StratumV1Service implements OnModuleInit {
this.listen(listener); this.listen(listener);
} }
private createSocketServer(): Server { private createSocketServer(payoutMode: PayoutMode): Server {
const server = new Server(async (socket: Socket) => { const server = new Server(async (socket: Socket) => {
socket.setTimeout(this.getSocketTimeoutMs()); socket.setTimeout(this.getSocketTimeoutMs());
socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs()); socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs());
@@ -188,14 +196,14 @@ export class StratumV1Service implements OnModuleInit {
try { try {
protocol = this.detectProtocol(firstChunk); protocol = this.detectProtocol(firstChunk);
if (protocol === 'v1') { if (protocol === 'v1') {
client = this.createV1Client(socket, 'sv1'); client = this.createV1Client(socket, 'sv1', payoutMode);
socket.emit('data', firstChunk); socket.emit('data', firstChunk);
return; return;
} }
if (protocol === 'v2') { if (protocol === 'v2') {
await this.stratumV2Service.ensureInitialized(); await this.stratumV2Service.ensureInitialized();
client = this.stratumV2Service.createClient(socket, firstChunk); client = this.stratumV2Service.createClient(socket, firstChunk, payoutMode);
return; return;
} }
@@ -220,7 +228,7 @@ export class StratumV1Service implements OnModuleInit {
return server; return server;
} }
private createV1Client(socket: Socket, accountingProtocol: 'sv1' | 'sv1_tls'): StratumV1Client { private createV1Client(socket: Socket, accountingProtocol: 'sv1' | 'sv1_tls', payoutMode: PayoutMode): StratumV1Client {
return new StratumV1Client( return new StratumV1Client(
socket, socket,
this.stratumV1JobsService, this.stratumV1JobsService,
@@ -234,13 +242,15 @@ export class StratumV1Service implements OnModuleInit {
this.redisMessagingService, this.redisMessagingService,
this.payoutSnapshotService, this.payoutSnapshotService,
accountingProtocol, accountingProtocol,
payoutMode,
); );
} }
private startSecureSocketServer(port: number) { private startSecureSocketServer(port: number, payoutMode: PayoutMode) {
const listener: StratumListenerState = { const listener: StratumListenerState = {
port, port,
secure: true, secure: true,
payoutMode,
server: null, server: null,
paused: false paused: false
}; };
@@ -248,7 +258,7 @@ export class StratumV1Service implements OnModuleInit {
this.listen(listener); this.listen(listener);
} }
private createSecureSocketServer(): Server { private createSecureSocketServer(payoutMode: PayoutMode): Server {
const currentDirectory = process.cwd(); const currentDirectory = process.cwd();
const keyPath = path.join(currentDirectory, 'secrets', 'key.pem'); const keyPath = path.join(currentDirectory, 'secrets', 'key.pem');
@@ -264,7 +274,7 @@ export class StratumV1Service implements OnModuleInit {
socket.setTimeout(this.getSocketTimeoutMs()); socket.setTimeout(this.getSocketTimeoutMs());
socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs()); socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs());
const client = this.createV1Client(socket, 'sv1_tls'); const client = this.createV1Client(socket, 'sv1_tls', payoutMode);
let cleanedUp = false; let cleanedUp = false;
const cleanup = async (reason: string) => { const cleanup = async (reason: string) => {
@@ -329,12 +339,12 @@ export class StratumV1Service implements OnModuleInit {
return; return;
} }
const server = listener.secure ? this.createSecureSocketServer() : this.createSocketServer(); const server = listener.secure ? this.createSecureSocketServer(listener.payoutMode) : this.createSocketServer(listener.payoutMode);
listener.server = server; listener.server = server;
listener.paused = false; listener.paused = false;
server.listen(listener.port, () => { server.listen(listener.port, () => {
console.log(`${listener.secure ? 'Stratum TLS' : 'Stratum'} server is listening on port ${listener.port}`); console.log(`${listener.secure ? 'Stratum TLS' : 'Stratum'} ${listener.payoutMode} server is listening on port ${listener.port}`);
}); });
} }
+12 -17
View File
@@ -24,6 +24,7 @@ import { NotificationService } from './notification.service';
import { RedisMessagingService } from './redis-messaging.service'; import { RedisMessagingService } from './redis-messaging.service';
import { StratumV1JobsService } from './stratum-v1-jobs.service'; import { StratumV1JobsService } from './stratum-v1-jobs.service';
import { Sv2JobDeclarationRegistryService } from './sv2-job-declaration-registry.service'; import { Sv2JobDeclarationRegistryService } from './sv2-job-declaration-registry.service';
import { parsePayoutModePorts, PayoutMode } from '../types/payout-mode';
const DEFAULT_SOCKET_TIMEOUT_MS = 1000 * 60 * 60; const DEFAULT_SOCKET_TIMEOUT_MS = 1000 * 60 * 60;
const DEFAULT_TCP_KEEPALIVE_INITIAL_DELAY_MS = 1000 * 60; const DEFAULT_TCP_KEEPALIVE_INITIAL_DELAY_MS = 1000 * 60;
@@ -70,7 +71,7 @@ export class StratumV2Service implements OnModuleInit {
} }
await this.ensureInitialized(); await this.ensureInitialized();
ports.forEach(port => this.startSocketServer(port)); ports.forEach(({ port, payoutMode }) => this.startSocketServer(port, payoutMode));
} }
public async ensureInitialized(): Promise<void> { public async ensureInitialized(): Promise<void> {
@@ -81,7 +82,7 @@ export class StratumV2Service implements OnModuleInit {
await this.initializeNoiseConfig(); await this.initializeNoiseConfig();
} }
public createClient(socket: Socket, firstChunk: Buffer): StratumV2Client { public createClient(socket: Socket, firstChunk: Buffer, payoutMode: PayoutMode = 'solo'): StratumV2Client {
if (this.noiseConfig == null) { if (this.noiseConfig == null) {
throw new Error('Stratum V2 service is not initialized'); throw new Error('Stratum V2 service is not initialized');
} }
@@ -102,6 +103,7 @@ export class StratumV2Service implements OnModuleInit {
this.shareAccountingService, this.shareAccountingService,
this.redisMessagingService, this.redisMessagingService,
this.payoutSnapshotService, this.payoutSnapshotService,
payoutMode,
); );
} }
@@ -170,21 +172,14 @@ export class StratumV2Service implements OnModuleInit {
}; };
} }
private getPorts(): number[] { private getPorts(): { port: number; payoutMode: PayoutMode }[] {
const configuredPorts = this.configService.get<string>('STRATUM_V2_PORTS'); return parsePayoutModePorts(
if (!configuredPorts?.trim()) { this.configService.get<string>('STRATUM_V2_PORTS'),
return []; this.configService.get<string>('PPLNS_STRATUM_V2_PORTS'),
} );
const ports = configuredPorts
.split(',')
.map(port => parseInt(port.trim(), 10))
.filter(port => Number.isInteger(port) && port > 0 && port <= 65535);
return Array.from(new Set(ports));
} }
private startSocketServer(port: number): void { private startSocketServer(port: number, payoutMode: PayoutMode): void {
const server = new Server((socket: Socket) => { const server = new Server((socket: Socket) => {
socket.setTimeout(this.getSocketTimeoutMs()); socket.setTimeout(this.getSocketTimeoutMs());
socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs()); socket.setKeepAlive(true, this.getTcpKeepAliveInitialDelayMs());
@@ -202,7 +197,7 @@ export class StratumV2Service implements OnModuleInit {
}; };
socket.once('data', (firstChunk: Buffer) => { socket.once('data', (firstChunk: Buffer) => {
client = this.createClient(socket, firstChunk); client = this.createClient(socket, firstChunk, payoutMode);
}); });
socket.on('timeout', closeSocket); socket.on('timeout', closeSocket);
@@ -224,7 +219,7 @@ export class StratumV2Service implements OnModuleInit {
}); });
server.listen(port, () => { server.listen(port, () => {
console.log(`Stratum V2 server is listening on port ${port}`); console.log(`Stratum V2 ${payoutMode} server is listening on port ${port}`);
}); });
this.servers.push(server); this.servers.push(server);
} }
@@ -3,9 +3,11 @@ import * as bitcoinjs from 'bitcoinjs-lib';
import { BufferReader } from '../models/sv2/sv2-binary-codec'; import { BufferReader } from '../models/sv2/sv2-binary-codec';
import { Sv2JdpSetupFlags, Sv2MsgType, Sv2Protocol } from '../models/sv2/sv2-constants'; import { Sv2JdpSetupFlags, Sv2MsgType, Sv2Protocol } from '../models/sv2/sv2-constants';
import { import {
deserializeAllocateMiningJobTokenSuccess,
deserializeDeclareMiningJobError, deserializeDeclareMiningJobError,
deserializeDeclareMiningJobSuccess, deserializeDeclareMiningJobSuccess,
deserializeProvideMissingTransactions, deserializeProvideMissingTransactions,
serializeAllocateMiningJobToken,
serializeDeclareMiningJob, serializeDeclareMiningJob,
serializeProvideMissingTransactionsSuccess, serializeProvideMissingTransactionsSuccess,
serializePushSolution, serializePushSolution,
@@ -60,6 +62,43 @@ describe('Sv2JobDeclarationConnection compliance', () => {
expect(registry.declareJob).not.toHaveBeenCalled(); expect(registry.declareJob).not.toHaveBeenCalled();
}); });
it('allocates a zero-value JDP token output while fixed payouts remain in the template', async () => {
const registry = new Sv2JobDeclarationRegistryService();
const payoutOutputs = [
{ address: 'tb1q42vtlphyjjcun9wcv9f0d9pkhup9dcf5z9k4gh', amountSats: 391 },
{ address: 'tb1q9r8gvnx3j4d6jvl0fqjrmy3dar4k4l3052af7q', amountSats: 110 },
{ address: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', amountSats: 95 },
];
const { connection, sentFrames } = createConnection({
registry,
templateProvider: {
getLatestTemplate: jest.fn().mockReturnValue({
jobTemplate: {
blockData: {
coinbasevalue: 596,
payoutOutputs,
},
},
}),
},
});
await (connection as any).handleAllocateMiningJobToken(serializeAllocateMiningJobToken({
requestId: 7,
userIdentifier: 'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2.sri-jdc',
}));
const successFrame = sentFrames.find(frame => frame.msgType === Sv2MsgType.JDP_ALLOCATE_MINING_JOB_TOKEN_SUCCESS);
const success = deserializeAllocateMiningJobTokenSuccess(new BufferReader(successFrame.payload));
expect(success.requestId).toBe(7);
const tokenOutputs = readSerializedTxOutputs(success.coinbaseOutputs);
expect(tokenOutputs).toHaveLength(1);
expect(tokenOutputs[0].value).toBe(0);
expect(bitcoinjs.address.fromOutputScript(tokenOutputs[0].script, bitcoinjs.networks.testnet))
.toBe('tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4');
});
it('accepts DeclareMiningJob when all wtxids are known to the template provider', async () => { it('accepts DeclareMiningJob when all wtxids are known to the template provider', async () => {
const registry = new Sv2JobDeclarationRegistryService(); const registry = new Sv2JobDeclarationRegistryService();
const allocated = registry.allocateToken('bc1ptest.worker', Buffer.alloc(0)); const allocated = registry.allocateToken('bc1ptest.worker', Buffer.alloc(0));
@@ -208,6 +247,7 @@ describe('Sv2JobDeclarationConnection compliance', () => {
blocksService, blocksService,
payoutSnapshotService, payoutSnapshotService,
notificationService, notificationService,
payoutMode: 'pplns',
}); });
(connection as any).latestDeclaredJob = { (connection as any).latestDeclaredJob = {
token: Buffer.from('0123456789abcdef0123456789abcdef', 'hex'), token: Buffer.from('0123456789abcdef0123456789abcdef', 'hex'),
@@ -241,6 +281,7 @@ describe('Sv2JobDeclarationConnection compliance', () => {
payoutSnapshotId: '17', payoutSnapshotId: '17',
blockHeight: 4990255, blockHeight: 4990255,
blockSubmissionResult: null, blockSubmissionResult: null,
payoutMode: 'pplns',
}); });
expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalledWith( expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalledWith(
'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
@@ -283,6 +324,7 @@ describe('Sv2JobDeclarationConnection compliance', () => {
blocksService, blocksService,
payoutSnapshotService, payoutSnapshotService,
notificationService, notificationService,
payoutMode: 'pplns',
}); });
(connection as any).latestDeclaredJob = { (connection as any).latestDeclaredJob = {
token: Buffer.from('0123456789abcdef0123456789abcdef', 'hex'), token: Buffer.from('0123456789abcdef0123456789abcdef', 'hex'),
@@ -409,6 +451,7 @@ describe('Sv2JobDeclarationConnection compliance', () => {
blocksService?: any; blocksService?: any;
payoutSnapshotService?: any; payoutSnapshotService?: any;
notificationService?: any; notificationService?: any;
payoutMode?: 'solo' | 'pplns';
} = {}): { } = {}): {
connection: Sv2JobDeclarationConnection; connection: Sv2JobDeclarationConnection;
sentFrames: any[]; sentFrames: any[];
@@ -428,6 +471,24 @@ describe('Sv2JobDeclarationConnection compliance', () => {
declareJob: jest.fn(), declareJob: jest.fn(),
}; };
const templateProvider = { const templateProvider = {
getLatestTemplate: jest.fn().mockReturnValue(undefined),
buildCoinbasePayoutOutputs: jest.fn((payoutInformation, coinbaseValue, network) => {
let balance = BigInt(coinbaseValue);
const outputs = payoutInformation.map(recipient => {
const value = recipient.amountSats == null
? BigInt(Math.floor(((recipient.percent ?? 0) / 100) * Number(coinbaseValue)))
: BigInt(recipient.amountSats);
balance -= value;
return {
value,
scriptPubKey: bitcoinjs.address.toOutputScript(recipient.address, network),
};
});
if (outputs.length > 0 && balance !== 0n) {
outputs[0] = { ...outputs[0], value: outputs[0].value + balance };
}
return outputs;
}),
validateDeclaredWtxids: jest.fn().mockReturnValue({ valid: false, errorCode: 'template-not-found' }), validateDeclaredWtxids: jest.fn().mockReturnValue({ valid: false, errorCode: 'template-not-found' }),
validateProvidedTransactions: jest.fn().mockReturnValue({ valid: false, errorCode: 'template-not-found' }), validateProvidedTransactions: jest.fn().mockReturnValue({ valid: false, errorCode: 'template-not-found' }),
validateCoinbaseTransactionHeight: jest.fn().mockReturnValue({ valid: true }), validateCoinbaseTransactionHeight: jest.fn().mockReturnValue({ valid: true }),
@@ -450,7 +511,9 @@ describe('Sv2JobDeclarationConnection compliance', () => {
}), }),
} as any, } as any,
registry as any, registry as any,
{} as any, {
encodeBitcoinVarInt: encodeBitcoinVarIntForTest,
} as any,
templateProvider, templateProvider,
overrides.bitcoinRpcService ?? { overrides.bitcoinRpcService ?? {
SUBMIT_BLOCK: jest.fn().mockResolvedValue(null), SUBMIT_BLOCK: jest.fn().mockResolvedValue(null),
@@ -466,6 +529,7 @@ describe('Sv2JobDeclarationConnection compliance', () => {
}, },
'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
bitcoinjs.networks.testnet, bitcoinjs.networks.testnet,
overrides.payoutMode ?? 'solo',
); );
const sentFrames: any[] = []; const sentFrames: any[] = [];
(connection as any).sendFrame = jest.fn((msgType: number, payload: Buffer) => { (connection as any).sendFrame = jest.fn((msgType: number, payload: Buffer) => {
@@ -500,4 +564,28 @@ describe('Sv2JobDeclarationConnection compliance', () => {
}], }],
}; };
} }
function readSerializedTxOutputs(outputs: Buffer): bitcoinjs.TxOutput[] {
const tx = bitcoinjs.Transaction.fromBuffer(Buffer.concat([
Buffer.from('0200000001', 'hex'),
Buffer.alloc(32),
Buffer.from('ffffffff00ffffffff', 'hex'),
outputs,
Buffer.from('00000000', 'hex'),
]));
return tx.outs;
}
function encodeBitcoinVarIntForTest(value: number): Buffer {
if (value < 0xfd) {
return Buffer.from([value]);
}
if (value <= 0xffff) {
const result = Buffer.alloc(3);
result[0] = 0xfd;
result.writeUInt16LE(value, 1);
return result;
}
throw new RangeError(`Unsupported test varint ${value}`);
}
}); });
+49 -26
View File
@@ -31,6 +31,7 @@ import { NotificationService } from './notification.service';
import { StratumV2Service } from './stratum-v2.service'; import { StratumV2Service } from './stratum-v2.service';
import { Sv2DeclaredMiningJob, Sv2JobDeclarationRegistryService } from './sv2-job-declaration-registry.service'; import { Sv2DeclaredMiningJob, Sv2JobDeclarationRegistryService } from './sv2-job-declaration-registry.service';
import { TemplateProviderService } from './template-provider.service'; import { TemplateProviderService } from './template-provider.service';
import { parsePayoutModePorts, PayoutMode } from '../types/payout-mode';
@Injectable() @Injectable()
export class Sv2JobDeclarationService implements OnModuleInit { export class Sv2JobDeclarationService implements OnModuleInit {
@@ -59,12 +60,12 @@ export class Sv2JobDeclarationService implements OnModuleInit {
} }
await this.stratumV2Service.ensureInitialized(); await this.stratumV2Service.ensureInitialized();
for (const port of ports) { for (const { port, payoutMode } of ports) {
this.startServer(port); this.startServer(port, payoutMode);
} }
} }
private startServer(port: number): void { private startServer(port: number, payoutMode: PayoutMode): void {
const server = new Server(socket => { const server = new Server(socket => {
void new Sv2JobDeclarationConnection( void new Sv2JobDeclarationConnection(
socket, socket,
@@ -78,10 +79,11 @@ export class Sv2JobDeclarationService implements OnModuleInit {
this.notificationService, this.notificationService,
this.getPoolPayoutAddress(), this.getPoolPayoutAddress(),
this.getNetwork(), this.getNetwork(),
payoutMode,
).start(); ).start();
}); });
server.on('error', error => console.error(`SV2 JDP server error on port ${port}: ${error.message}`)); server.on('error', error => console.error(`SV2 JDP server error on port ${port}: ${error.message}`));
server.listen(port, () => console.log(`SV2 Job Declaration server is listening on port ${port}`)); server.listen(port, () => console.log(`SV2 Job Declaration ${payoutMode} server is listening on port ${port}`));
this.servers.push(server); this.servers.push(server);
} }
@@ -93,15 +95,11 @@ export class Sv2JobDeclarationService implements OnModuleInit {
|| ''; || '';
} }
private getPorts(): number[] { private getPorts(): { port: number; payoutMode: PayoutMode }[] {
const configured = this.configService.get<string>('SV2_JDP_PORTS'); return parsePayoutModePorts(
if (!configured?.trim()) { this.configService.get<string>('SV2_JDP_PORTS'),
return []; this.configService.get<string>('PPLNS_SV2_JDP_PORTS'),
} );
return Array.from(new Set(configured
.split(',')
.map(port => parseInt(port.trim(), 10))
.filter(port => Number.isInteger(port) && port > 0 && port <= 65535)));
} }
private getNetwork(): bitcoinjs.networks.Network { private getNetwork(): bitcoinjs.networks.Network {
@@ -148,6 +146,7 @@ export class Sv2JobDeclarationConnection {
private readonly notificationService: NotificationService, private readonly notificationService: NotificationService,
private readonly poolPayoutAddress: string, private readonly poolPayoutAddress: string,
private readonly network: bitcoinjs.networks.Network, private readonly network: bitcoinjs.networks.Network,
private readonly payoutMode: PayoutMode,
) { ) {
this.noiseSession = new Sv2NoiseSession(stratumV2Service.getNoiseConfig()); this.noiseSession = new Sv2NoiseSession(stratumV2Service.getNoiseConfig());
} }
@@ -239,8 +238,8 @@ export class Sv2JobDeclarationConnection {
private async handleAllocateMiningJobToken(payload: Buffer): Promise<void> { private async handleAllocateMiningJobToken(payload: Buffer): Promise<void> {
const request = deserializeAllocateMiningJobToken(new BufferReader(payload)); const request = deserializeAllocateMiningJobToken(new BufferReader(payload));
const token = this.registry.allocateToken( const token = this.registry.allocateToken(
request.userIdentifier, request.userIdentifier,
this.buildPoolCoinbaseOutputs(request.userIdentifier), this.buildPoolCoinbaseOutputs(request.userIdentifier),
); );
await this.sendFrame(Sv2MsgType.JDP_ALLOCATE_MINING_JOB_TOKEN_SUCCESS, serializeAllocateMiningJobTokenSuccess({ await this.sendFrame(Sv2MsgType.JDP_ALLOCATE_MINING_JOB_TOKEN_SUCCESS, serializeAllocateMiningJobTokenSuccess({
@@ -413,13 +412,19 @@ export class Sv2JobDeclarationConnection {
sessionId: declared.token.toString('hex').slice(0, 8), sessionId: declared.token.toString('hex').slice(0, 8),
blockData: blockHex, blockData: blockHex,
blockSubmissionResult: result, blockSubmissionResult: result,
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId ?? null, payoutSnapshotId: this.payoutMode === 'pplns'
}); ? template.jobTemplate.blockData.payoutSnapshotId ?? null
await this.payoutSnapshotService.finalizeSnapshotForBlock({ : null,
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId, payoutMode: this.payoutMode,
blockHeight: template.height,
blockSubmissionResult: result,
}); });
if (this.payoutMode === 'pplns') {
await this.payoutSnapshotService.finalizeSnapshotForBlock({
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId,
blockHeight: template.height,
blockSubmissionResult: result,
payoutMode: this.payoutMode,
});
}
await this.notificationService.notifySubscribersBlockFound(address, template.height, block, result); await this.notificationService.notifySubscribersBlockFound(address, template.height, block, result);
console.log(`[SV2 JDP] PushSolution submitted block at height ${template.height}: ${result ?? 'accepted'}`); console.log(`[SV2 JDP] PushSolution submitted block at height ${template.height}: ${result ?? 'accepted'}`);
} catch (error) { } catch (error) {
@@ -428,14 +433,32 @@ export class Sv2JobDeclarationConnection {
} }
private buildPoolCoinbaseOutputs(userIdentifier: string): Buffer { private buildPoolCoinbaseOutputs(userIdentifier: string): Buffer {
const snapshotOutputs = this.payoutMode === 'pplns'
? this.templateProvider.getLatestTemplate()?.jobTemplate.blockData.payoutOutputs ?? []
: [];
if (snapshotOutputs.length > 0) {
return this.serializeCoinbaseOutputs(snapshotOutputs.map(output => ({
value: 0n,
scriptPubKey: bitcoinjs.address.toOutputScript(output.address, this.network),
})));
}
const address = this.poolPayoutAddress || userIdentifier.split('.')[0]; const address = this.poolPayoutAddress || userIdentifier.split('.')[0];
const script = bitcoinjs.address.toOutputScript(address, this.network); const script = bitcoinjs.address.toOutputScript(address, this.network);
const value = Buffer.alloc(8); return this.serializeCoinbaseOutputs([{ value: 0n, scriptPubKey: script }]);
}
private serializeCoinbaseOutputs(outputs: Array<{ value: bigint; scriptPubKey: Buffer }>): Buffer {
return Buffer.concat([ return Buffer.concat([
this.customWorkService.encodeBitcoinVarInt(1), this.customWorkService.encodeBitcoinVarInt(outputs.length),
value, ...outputs.flatMap(output => {
this.customWorkService.encodeBitcoinVarInt(script.length), const value = Buffer.alloc(8);
script, value.writeBigUInt64LE(output.value, 0);
return [
value,
this.customWorkService.encodeBitcoinVarInt(output.scriptPubKey.length),
output.scriptPubKey,
];
}),
]); ]);
} }
@@ -3,7 +3,6 @@ import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { MockRecording1 } from '../../test/models/MockRecording1'; import { MockRecording1 } from '../../test/models/MockRecording1';
import { BufferReader } from '../models/sv2/sv2-binary-codec'; import { BufferReader } from '../models/sv2/sv2-binary-codec';
import { MiningJob } from '../models/MiningJob';
import { Sv2MsgType, Sv2Protocol } from '../models/sv2/sv2-constants'; import { Sv2MsgType, Sv2Protocol } from '../models/sv2/sv2-constants';
import { import {
deserializeSetupConnectionSuccess, deserializeSetupConnectionSuccess,
@@ -56,20 +55,23 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
expect(sentFrames.some(frame => frame.msgType === Sv2MsgType.TDP_SET_NEW_PREV_HASH)).toBe(true); expect(sentFrames.some(frame => frame.msgType === Sv2MsgType.TDP_SET_NEW_PREV_HASH)).toBe(true);
const templateFrame = sentFrames.find(frame => frame.msgType === Sv2MsgType.TDP_NEW_TEMPLATE); const templateFrame = sentFrames.find(frame => frame.msgType === Sv2MsgType.TDP_NEW_TEMPLATE);
const template = deserializeTdpNewTemplate(new BufferReader(templateFrame.payload)); const template = deserializeTdpNewTemplate(new BufferReader(templateFrame.payload));
const expectedJob = new MiningJob( const heightPrefix = templateProvider.buildCoinbaseHeightPrefix(MockRecording1.BLOCK_TEMPLATE.height);
expect(template.coinbasePrefix).toEqual(heightPrefix);
expect(template.coinbasePrefix.subarray(0, 4)).not.toEqual(Buffer.from('02000000', 'hex'));
expect(template.coinbaseTxVersion).toBe(2);
expect(template.coinbaseTxInputSequence).toBe(0xffffffff);
expect(template.coinbaseTxValueRemaining).toBe(0n);
expect(template.coinbaseTxOutputsCount).toBe(2);
expect(template.coinbaseTxOutputs).toEqual((connection as any).serializeFixedCoinbaseOutputs(jobTemplate).serialized);
expect(template.coinbaseTxOutputs.includes(bitcoinjs.address.toOutputScript(
'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
bitcoinjs.networks.testnet, bitcoinjs.networks.testnet,
jobTemplate.blockData.id, ))).toBe(true);
[{ address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', percent: 100 }], expect(template.coinbaseTxOutputs.includes(Buffer.concat([
jobTemplate, Buffer.from('aa21a9ed', 'hex'),
); jobTemplate.block.witnessCommit,
const expectedCoinbaseTx = expectedJob.cloneCoinbaseTransaction(); ]))).toBe(true);
expect(template.coinbasePrefix).toEqual(expectedJob.getCoinbasePrefixBuffer()); expect(template.coinbaseTxLocktime).toBe(0);
expect(template.coinbasePrefix.includes(templateProvider.buildCoinbaseHeightPrefix(MockRecording1.BLOCK_TEMPLATE.height))).toBe(true);
expect(template.coinbaseTxVersion).toBe(expectedCoinbaseTx.version);
expect(template.coinbaseTxInputSequence).toBe(expectedCoinbaseTx.ins[0].sequence);
expect(template.coinbaseTxOutputsCount).toBe(expectedCoinbaseTx.outs.length);
expect(template.coinbaseTxOutputs).toEqual((connection as any).serializeCoinbaseOutputs(expectedCoinbaseTx));
expect(template.coinbaseTxLocktime).toBe(expectedCoinbaseTx.locktime);
}); });
it('serves transaction data for known templates', async () => { it('serves transaction data for known templates', async () => {
@@ -88,7 +90,7 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
}); });
it('submits reconstructed blocks from SubmitSolution', async () => { it('submits reconstructed blocks from SubmitSolution', async () => {
const { connection, templateProvider, jobTemplate, bitcoinRpcService, blocksService, payoutSnapshotService, notificationService } = await createConnection(); const { connection, templateProvider, jobTemplate, bitcoinRpcService, blocksService, payoutSnapshotService, notificationService } = await createConnection('pplns');
const template = templateProvider.upsert(jobTemplate); const template = templateProvider.upsert(jobTemplate);
const callOrder: string[] = []; const callOrder: string[] = [];
bitcoinRpcService.SUBMIT_BLOCK.mockImplementation(async () => { bitcoinRpcService.SUBMIT_BLOCK.mockImplementation(async () => {
@@ -98,7 +100,10 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
blocksService.save.mockImplementation(async () => { blocksService.save.mockImplementation(async () => {
callOrder.push('save'); callOrder.push('save');
}); });
const coinbaseTx = createCoinbaseTransaction(templateProvider.buildCoinbaseHeightPrefix(template.height)); const coinbaseTx = createPayoutCoinbaseTransaction(
templateProvider.buildCoinbaseHeightPrefix(template.height),
jobTemplate.blockData.coinbasevalue,
);
await (connection as any).handleFrame( await (connection as any).handleFrame(
Sv2MsgType.TDP_SUBMIT_SOLUTION, Sv2MsgType.TDP_SUBMIT_SOLUTION,
@@ -123,6 +128,7 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId, payoutSnapshotId: jobTemplate.blockData.payoutSnapshotId,
blockHeight: MockRecording1.BLOCK_TEMPLATE.height, blockHeight: MockRecording1.BLOCK_TEMPLATE.height,
blockSubmissionResult: null, blockSubmissionResult: null,
payoutMode: 'pplns',
}); });
expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalledWith( expect(notificationService.notifySubscribersBlockFound).toHaveBeenCalledWith(
'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
@@ -135,7 +141,10 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
it('does not resubmit duplicate SubmitSolution messages', async () => { it('does not resubmit duplicate SubmitSolution messages', async () => {
const { connection, templateProvider, jobTemplate, bitcoinRpcService } = await createConnection(); const { connection, templateProvider, jobTemplate, bitcoinRpcService } = await createConnection();
const template = templateProvider.upsert(jobTemplate); const template = templateProvider.upsert(jobTemplate);
const coinbaseTx = createCoinbaseTransaction(templateProvider.buildCoinbaseHeightPrefix(template.height)); const coinbaseTx = createPayoutCoinbaseTransaction(
templateProvider.buildCoinbaseHeightPrefix(template.height),
jobTemplate.blockData.coinbasevalue,
);
const payload = serializeTdpSubmitSolution({ const payload = serializeTdpSubmitSolution({
templateId: template.templateId, templateId: template.templateId,
version: template.version, version: template.version,
@@ -173,13 +182,44 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
warn.mockRestore(); warn.mockRestore();
}); });
it('rejects SubmitSolution locally when the coinbase does not pay the pool outputs', async () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
const { connection, templateProvider, jobTemplate, bitcoinRpcService, blocksService } = await createConnection();
const template = templateProvider.upsert(jobTemplate);
const coinbaseTx = createPayoutCoinbaseTransaction(
templateProvider.buildCoinbaseHeightPrefix(template.height),
jobTemplate.blockData.coinbasevalue,
'tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2',
);
await (connection as any).handleFrame(
Sv2MsgType.TDP_SUBMIT_SOLUTION,
serializeTdpSubmitSolution({
templateId: template.templateId,
version: template.version,
headerTimestamp: template.minNtime,
headerNonce: 123,
coinbaseTx: coinbaseTx.toBuffer(),
}),
);
expect(bitcoinRpcService.SUBMIT_BLOCK).not.toHaveBeenCalled();
expect(blocksService.save).not.toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('coinbase-payout-output-mismatch'));
warn.mockRestore();
});
it('submits using a served template snapshot after provider cache cleanup', async () => { it('submits using a served template snapshot after provider cache cleanup', async () => {
const { connection, sentFrames, templateProvider, jobTemplate, bitcoinRpcService, blocksService } = await createConnection(); const { connection, sentFrames, templateProvider, jobTemplate, bitcoinRpcService, blocksService } = await createConnection();
await (connection as any).sendTemplate(jobTemplate); await (connection as any).sendTemplate(jobTemplate);
const templateId = BigInt(parseInt(jobTemplate.blockData.id, 16)); const templateId = BigInt(parseInt(jobTemplate.blockData.id, 16));
jest.spyOn(templateProvider, 'getTemplate').mockReturnValue(undefined); jest.spyOn(templateProvider, 'getTemplate').mockReturnValue(undefined);
sentFrames.length = 0; sentFrames.length = 0;
const coinbaseTx = createCoinbaseTransaction(templateProvider.buildCoinbaseHeightPrefix(jobTemplate.blockData.height)); const coinbaseTx = createPayoutCoinbaseTransaction(
templateProvider.buildCoinbaseHeightPrefix(jobTemplate.blockData.height),
jobTemplate.blockData.coinbasevalue,
);
await (connection as any).handleFrame( await (connection as any).handleFrame(
Sv2MsgType.TDP_SUBMIT_SOLUTION, Sv2MsgType.TDP_SUBMIT_SOLUTION,
@@ -200,7 +240,7 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
expect(sentFrames.some(frame => frame.msgType === Sv2MsgType.TDP_REQUEST_TRANSACTION_DATA_ERROR)).toBe(false); expect(sentFrames.some(frame => frame.msgType === Sv2MsgType.TDP_REQUEST_TRANSACTION_DATA_ERROR)).toBe(false);
}); });
async function createConnection(): Promise<{ async function createConnection(payoutMode: 'solo' | 'pplns' = 'solo'): Promise<{
connection: Sv2TemplateDistributionConnection; connection: Sv2TemplateDistributionConnection;
sentFrames: any[]; sentFrames: any[];
templateProvider: TemplateProviderService; templateProvider: TemplateProviderService;
@@ -262,6 +302,7 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
notificationService as any, notificationService as any,
'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
bitcoinjs.networks.testnet, bitcoinjs.networks.testnet,
payoutMode,
); );
const sentFrames: any[] = []; const sentFrames: any[] = [];
(connection as any).sendFrame = jest.fn((msgType: number, payload: Buffer) => { (connection as any).sendFrame = jest.fn((msgType: number, payload: Buffer) => {
@@ -287,4 +328,19 @@ describe('Sv2TemplateDistributionConnection compliance', () => {
tx.addOutput(Buffer.from('6a', 'hex'), 0); tx.addOutput(Buffer.from('6a', 'hex'), 0);
return tx; return tx;
} }
function createPayoutCoinbaseTransaction(
script: Buffer,
coinbaseValue: number,
address = 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
): bitcoinjs.Transaction {
const tx = new bitcoinjs.Transaction();
tx.version = 2;
tx.addInput(Buffer.alloc(32), 0xffffffff, 0xffffffff, script);
tx.addOutput(
bitcoinjs.address.toOutputScript(address, bitcoinjs.networks.testnet),
coinbaseValue,
);
return tx;
}
}); });
@@ -14,7 +14,6 @@ import {
serializeSetupConnectionError, serializeSetupConnectionError,
serializeSetupConnectionSuccess, serializeSetupConnectionSuccess,
} from '../models/sv2/sv2-messages'; } from '../models/sv2/sv2-messages';
import { AddressObject, MiningJob } from '../models/MiningJob';
import { Sv2NoiseSession } from '../models/sv2/sv2-noise'; import { Sv2NoiseSession } from '../models/sv2/sv2-noise';
import { import {
deserializeTdpCoinbaseOutputConstraints, deserializeTdpCoinbaseOutputConstraints,
@@ -30,6 +29,8 @@ import { NotificationService } from './notification.service';
import { IJobTemplate, StratumV1JobsService } from './stratum-v1-jobs.service'; import { IJobTemplate, StratumV1JobsService } from './stratum-v1-jobs.service';
import { StratumV2Service } from './stratum-v2.service'; import { StratumV2Service } from './stratum-v2.service';
import { TemplateProviderService, TemplateProviderTemplate } from './template-provider.service'; import { TemplateProviderService, TemplateProviderTemplate } from './template-provider.service';
import { AddressObject } from '../models/MiningJob';
import { parsePayoutModePorts, PayoutMode } from '../types/payout-mode';
interface TdpCoinbaseTemplateFields { interface TdpCoinbaseTemplateFields {
coinbaseTxVersion: number; coinbaseTxVersion: number;
@@ -67,12 +68,12 @@ export class Sv2TemplateDistributionService implements OnModuleInit {
} }
await this.stratumV2Service.ensureInitialized(); await this.stratumV2Service.ensureInitialized();
for (const port of ports) { for (const { port, payoutMode } of ports) {
this.startServer(port); this.startServer(port, payoutMode);
} }
} }
private startServer(port: number): void { private startServer(port: number, payoutMode: PayoutMode): void {
const server = new Server(socket => { const server = new Server(socket => {
void new Sv2TemplateDistributionConnection( void new Sv2TemplateDistributionConnection(
socket, socket,
@@ -85,22 +86,19 @@ export class Sv2TemplateDistributionService implements OnModuleInit {
this.notificationService, this.notificationService,
this.getPoolPayoutAddress(), this.getPoolPayoutAddress(),
this.getNetwork(), this.getNetwork(),
payoutMode,
).start(); ).start();
}); });
server.on('error', error => console.error(`SV2 TDP server error on port ${port}: ${error.message}`)); server.on('error', error => console.error(`SV2 TDP server error on port ${port}: ${error.message}`));
server.listen(port, () => console.log(`SV2 Template Distribution server is listening on port ${port}`)); server.listen(port, () => console.log(`SV2 Template Distribution ${payoutMode} server is listening on port ${port}`));
this.servers.push(server); this.servers.push(server);
} }
private getPorts(): number[] { private getPorts(): { port: number; payoutMode: PayoutMode }[] {
const configured = this.configService.get<string>('SV2_TDP_PORTS'); return parsePayoutModePorts(
if (!configured?.trim()) { this.configService.get<string>('SV2_TDP_PORTS'),
return []; this.configService.get<string>('PPLNS_SV2_TDP_PORTS'),
} );
return Array.from(new Set(configured
.split(',')
.map(port => parseInt(port.trim(), 10))
.filter(port => Number.isInteger(port) && port > 0 && port <= 65535)));
} }
private getPoolPayoutAddress(): string { private getPoolPayoutAddress(): string {
@@ -149,6 +147,7 @@ export class Sv2TemplateDistributionConnection {
private readonly notificationService: NotificationService, private readonly notificationService: NotificationService,
private readonly poolPayoutAddress: string, private readonly poolPayoutAddress: string,
private readonly network: bitcoinjs.networks.Network, private readonly network: bitcoinjs.networks.Network,
private readonly payoutMode: PayoutMode,
) { ) {
this.noiseSession = new Sv2NoiseSession(stratumV2Service.getNoiseConfig()); this.noiseSession = new Sv2NoiseSession(stratumV2Service.getNoiseConfig());
} }
@@ -272,43 +271,65 @@ export class Sv2TemplateDistributionConnection {
} }
private buildCoinbaseTemplateFields(template: IJobTemplate): TdpCoinbaseTemplateFields { private buildCoinbaseTemplateFields(template: IJobTemplate): TdpCoinbaseTemplateFields {
const job = new MiningJob( const coinbaseTxOutputs = this.serializeFixedCoinbaseOutputs(template);
this.network, const spendableValue = coinbaseTxOutputs.spendableValue;
template.blockData.id,
this.getPayoutInformation(template),
template,
);
const coinbaseTx = job.cloneCoinbaseTransaction();
return { return {
coinbaseTxVersion: coinbaseTx.version, coinbaseTxVersion: 2,
coinbasePrefix: job.getCoinbasePrefixBuffer(), coinbasePrefix: this.templateProvider.buildCoinbaseHeightPrefix(template.blockData.height),
coinbaseTxInputSequence: coinbaseTx.ins[0]?.sequence ?? 0xffffffff, coinbaseTxInputSequence: 0xffffffff,
coinbaseTxValueRemaining: BigInt(template.blockData.coinbasevalue), coinbaseTxValueRemaining: BigInt(template.blockData.coinbasevalue) - spendableValue,
coinbaseTxOutputsCount: coinbaseTx.outs.length, coinbaseTxOutputsCount: coinbaseTxOutputs.count,
coinbaseTxOutputs: this.serializeCoinbaseOutputs(coinbaseTx), coinbaseTxOutputs: coinbaseTxOutputs.serialized,
coinbaseTxLocktime: coinbaseTx.locktime, coinbaseTxLocktime: 0,
};
}
private serializeFixedCoinbaseOutputs(template: IJobTemplate): { count: number; serialized: Buffer; spendableValue: bigint } {
const payoutOutputs = this.templateProvider.buildCoinbasePayoutOutputs(
this.getPayoutInformation(template),
template.blockData.coinbasevalue,
this.network,
);
const outputs: { value: bigint; script: Buffer }[] = payoutOutputs.map(output => ({
value: output.value,
script: output.scriptPubKey,
}));
const spendableValue = payoutOutputs.reduce((sum, output) => sum + output.value, 0n);
if (template.block.witnessCommit != null) {
const segwitMagicBits = Buffer.from('aa21a9ed', 'hex');
outputs.push({
value: 0n,
script: bitcoinjs.script.compile([
bitcoinjs.opcodes.OP_RETURN,
Buffer.concat([segwitMagicBits, template.block.witnessCommit]),
]),
});
}
return {
count: outputs.length,
serialized: Buffer.concat(outputs.map(output => this.serializeCoinbaseOutput(output.value, output.script))),
spendableValue,
}; };
} }
private getPayoutInformation(template: IJobTemplate): AddressObject[] { private getPayoutInformation(template: IJobTemplate): AddressObject[] {
if (template.blockData.payoutOutputs?.length > 0) { if (this.payoutMode === 'pplns' && template.blockData.payoutOutputs?.length > 0) {
return template.blockData.payoutOutputs; return template.blockData.payoutOutputs;
} }
return [{ address: this.poolPayoutAddress, percent: 100 }]; return [{ address: this.poolPayoutAddress, percent: 100 }];
} }
private serializeCoinbaseOutputs(coinbaseTx: bitcoinjs.Transaction): Buffer { private serializeCoinbaseOutput(valueSats: bigint, script: Buffer): Buffer {
return Buffer.concat(coinbaseTx.outs.map(output => { const value = Buffer.alloc(8);
const value = Buffer.alloc(8); value.writeBigUInt64LE(valueSats, 0);
value.writeBigUInt64LE(BigInt(output.value), 0); return Buffer.concat([
return Buffer.concat([ value,
value, this.encodeBitcoinVarInt(script.length),
this.encodeBitcoinVarInt(output.script.length), Buffer.from(script),
Buffer.from(output.script), ]);
]);
}));
} }
private encodeBitcoinVarInt(value: number): Buffer { private encodeBitcoinVarInt(value: number): Buffer {
@@ -369,6 +390,16 @@ export class Sv2TemplateDistributionConnection {
console.warn(`[SV2 TDP] SubmitSolution rejected locally: ${coinbaseValidation.errorCode}`); console.warn(`[SV2 TDP] SubmitSolution rejected locally: ${coinbaseValidation.errorCode}`);
return; return;
} }
const payoutValidation = this.templateProvider.validateCoinbaseTransactionPayoutOutputs({
coinbaseTx: solution.coinbaseTx,
payoutInformation: this.getPayoutInformation(template.jobTemplate),
coinbaseValue: template.coinbaseValue,
network: this.network,
});
if (!payoutValidation.valid) {
console.warn(`[SV2 TDP] SubmitSolution rejected locally: ${payoutValidation.errorCode}`);
return;
}
const block = this.templateProvider.buildBlockFromSolution({ const block = this.templateProvider.buildBlockFromSolution({
template, template,
coinbaseTx: solution.coinbaseTx, coinbaseTx: solution.coinbaseTx,
@@ -390,13 +421,19 @@ export class Sv2TemplateDistributionConnection {
sessionId: solution.templateId.toString(16).slice(-8).padStart(8, '0'), sessionId: solution.templateId.toString(16).slice(-8).padStart(8, '0'),
blockData: blockHex, blockData: blockHex,
blockSubmissionResult: result, blockSubmissionResult: result,
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId ?? null, payoutSnapshotId: this.payoutMode === 'pplns'
}); ? template.jobTemplate.blockData.payoutSnapshotId ?? null
await this.payoutSnapshotService.finalizeSnapshotForBlock({ : null,
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId, payoutMode: this.payoutMode,
blockHeight: template.height,
blockSubmissionResult: result,
}); });
if (this.payoutMode === 'pplns') {
await this.payoutSnapshotService.finalizeSnapshotForBlock({
payoutSnapshotId: template.jobTemplate.blockData.payoutSnapshotId,
blockHeight: template.height,
blockSubmissionResult: result,
payoutMode: this.payoutMode,
});
}
await this.notificationService.notifySubscribersBlockFound( await this.notificationService.notifySubscribersBlockFound(
this.poolPayoutAddress || 'sv2-tdp', this.poolPayoutAddress || 'sv2-tdp',
template.height, template.height,
@@ -114,6 +114,49 @@ describe('TemplateProviderService', () => {
expect(validation.template).toBe(template); expect(validation.template).toBe(template);
}); });
it('accepts declared SV2 JDP script-only coinbase prefixes that start with the required BIP34 height', async () => {
const { provider, jobTemplate } = await createProvider();
const template = provider.upsert(jobTemplate);
const scriptOnlyPrefix = Buffer.concat([
provider.buildCoinbaseHeightPrefix(template.height),
Buffer.from('/public-pool-sri-jdc-e2e/', 'utf8'),
]);
const validation = provider.validateDeclaredWtxids({
version: MockRecording1.BLOCK_TEMPLATE.version,
coinbaseTxPrefix: scriptOnlyPrefix,
wtxidList: [],
});
expect(validation.valid).toBe(true);
expect(validation.template).toBe(template);
});
it('ignores zero-value extra outputs when validating coinbase payouts', async () => {
const { provider, jobTemplate } = await createProvider();
const coinbaseTx = createCoinbaseTransaction(provider.buildCoinbaseHeightPrefix(jobTemplate.blockData.height));
coinbaseTx.addOutput(
bitcoinjs.address.toOutputScript('tb1qdyjakeepue4trak9d3hvyelrd0aw7mwju2d0c2', bitcoinjs.networks.testnet),
0,
);
coinbaseTx.addOutput(
bitcoinjs.address.toOutputScript('tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', bitcoinjs.networks.testnet),
jobTemplate.blockData.coinbasevalue,
);
const validation = provider.validateCoinbaseTransactionPayoutOutputs({
coinbaseTx: coinbaseTx.toBuffer(),
payoutInformation: [{
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
amountSats: jobTemplate.blockData.coinbasevalue,
}],
coinbaseValue: jobTemplate.blockData.coinbasevalue,
network: bitcoinjs.networks.testnet,
});
expect(validation.valid).toBe(true);
});
it('accepts DATUM template metadata matching the latest template fast path', async () => { it('accepts DATUM template metadata matching the latest template fast path', async () => {
const { provider, jobTemplate } = await createProvider(); const { provider, jobTemplate } = await createProvider();
const template = provider.upsert(jobTemplate); const template = provider.upsert(jobTemplate);
+109 -1
View File
@@ -3,6 +3,7 @@ import * as bitcoinjs from 'bitcoinjs-lib';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { IBlockTemplateTx } from '../models/bitcoin-rpc/IBlockTemplate'; import { IBlockTemplateTx } from '../models/bitcoin-rpc/IBlockTemplate';
import { AddressObject } from '../models/MiningJob';
import { Sv2DeclareMiningJob, Sv2PushSolution } from '../models/sv2/sv2-jdp-messages'; import { Sv2DeclareMiningJob, Sv2PushSolution } from '../models/sv2/sv2-jdp-messages';
import { hash256 } from '../utils/hash.utils'; import { hash256 } from '../utils/hash.utils';
import { BitcoinRpcService } from './bitcoin-rpc.service'; import { BitcoinRpcService } from './bitcoin-rpc.service';
@@ -76,6 +77,18 @@ export interface CoinbaseHeightValidationResult {
errorCode?: string; errorCode?: string;
} }
export interface CoinbasePayoutOutput {
value: bigint;
scriptPubKey: Buffer;
}
export interface CoinbasePayoutValidationResult {
valid: boolean;
errorCode?: string;
expectedOutputs?: CoinbasePayoutOutput[];
submittedOutputs?: CoinbasePayoutOutput[];
}
const VERSION_ROLLING_MASK = 0x1fffe000; const VERSION_ROLLING_MASK = 0x1fffe000;
@Injectable() @Injectable()
@@ -211,10 +224,98 @@ export class TemplateProviderService implements OnModuleInit {
return this.validateCoinbaseScriptHeight(tx.ins[0].script, height); return this.validateCoinbaseScriptHeight(tx.ins[0].script, height);
} }
public buildCoinbasePayoutOutputs(
payoutInformation: AddressObject[],
coinbaseValue: number | bigint,
network: bitcoinjs.networks.Network,
): CoinbasePayoutOutput[] {
const rewardValue = typeof coinbaseValue === 'bigint' ? coinbaseValue : BigInt(Math.max(0, Math.floor(coinbaseValue)));
let rewardBalance = rewardValue;
const outputs = payoutInformation.map(recipientAddress => {
const value = recipientAddress.amountSats == null
? BigInt(Math.floor(((recipientAddress.percent ?? 0) / 100) * Number(rewardValue)))
: BigInt(recipientAddress.amountSats);
rewardBalance -= value;
return {
value,
scriptPubKey: bitcoinjs.address.toOutputScript(recipientAddress.address, network),
};
});
if (outputs.length > 0 && rewardBalance !== 0n) {
outputs[0] = {
...outputs[0],
value: outputs[0].value + rewardBalance,
};
}
return outputs;
}
public validateCoinbaseTransactionPayoutOutputs(input: {
coinbaseTx: Buffer;
payoutInformation: AddressObject[];
coinbaseValue: number | bigint;
network: bitcoinjs.networks.Network;
}): CoinbasePayoutValidationResult {
const expectedOutputs = this.buildCoinbasePayoutOutputs(
input.payoutInformation,
input.coinbaseValue,
input.network,
);
if (expectedOutputs.length === 0) {
return { valid: false, errorCode: 'missing-expected-coinbase-payouts', expectedOutputs, submittedOutputs: [] };
}
let tx: bitcoinjs.Transaction;
try {
tx = bitcoinjs.Transaction.fromBuffer(input.coinbaseTx);
} catch (error) {
return {
valid: false,
errorCode: `invalid-coinbase-transaction:${error instanceof Error ? error.message : String(error)}`,
expectedOutputs,
submittedOutputs: [],
};
}
const submittedOutputs = tx.outs
.filter(output => !this.isWitnessCommitmentOutput(output.script))
.filter(output => BigInt(output.value) !== 0n)
.map(output => ({
value: BigInt(output.value),
scriptPubKey: Buffer.from(output.script),
}));
if (submittedOutputs.length !== expectedOutputs.length) {
return {
valid: false,
errorCode: `coinbase-payout-output-count-mismatch:${expectedOutputs.length}:${submittedOutputs.length}`,
expectedOutputs,
submittedOutputs,
};
}
for (let i = 0; i < expectedOutputs.length; i++) {
const expected = expectedOutputs[i];
const submitted = submittedOutputs[i];
if (expected.value !== submitted.value || !expected.scriptPubKey.equals(submitted.scriptPubKey)) {
return {
valid: false,
errorCode: `coinbase-payout-output-mismatch:${i}`,
expectedOutputs,
submittedOutputs,
};
}
}
return { valid: true, expectedOutputs, submittedOutputs };
}
public validateDeclaredCoinbasePrefixHeight(coinbaseTxPrefix: Buffer, height: number): CoinbaseHeightValidationResult { public validateDeclaredCoinbasePrefixHeight(coinbaseTxPrefix: Buffer, height: number): CoinbaseHeightValidationResult {
const scriptStart = this.getCoinbaseInputScriptStart(coinbaseTxPrefix); const scriptStart = this.getCoinbaseInputScriptStart(coinbaseTxPrefix);
if (scriptStart == null) { if (scriptStart == null) {
return { valid: false, errorCode: 'invalid-job-param-value-coinbase_tx_prefix' }; return this.validateCoinbaseScriptHeight(coinbaseTxPrefix, height);
} }
const expected = this.buildCoinbaseHeightPrefix(height); const expected = this.buildCoinbaseHeightPrefix(height);
if (coinbaseTxPrefix.length < scriptStart + expected.length) { if (coinbaseTxPrefix.length < scriptStart + expected.length) {
@@ -482,6 +583,13 @@ export class TemplateProviderService implements OnModuleInit {
return { valid: true }; return { valid: true };
} }
private isWitnessCommitmentOutput(script: Buffer): boolean {
return script.length === 38
&& script[0] === bitcoinjs.opcodes.OP_RETURN
&& script[1] === 0x24
&& script.subarray(2, 6).equals(Buffer.from('aa21a9ed', 'hex'));
}
private getCoinbaseInputScriptStart(txPrefix: Buffer): number | null { private getCoinbaseInputScriptStart(txPrefix: Buffer): number | null {
let cursor = 4; let cursor = 4;
if (txPrefix.length < cursor + 1) { if (txPrefix.length < cursor + 1) {
+22
View File
@@ -0,0 +1,22 @@
import { normalizePayoutMode, parsePayoutModePorts } from './payout-mode';
describe('payout mode helpers', () => {
it('maps legacy ports to solo and PPLNS ports to pplns', () => {
expect(parsePayoutModePorts('3333,3332', '13333')).toEqual([
{ port: 3333, payoutMode: 'solo' },
{ port: 3332, payoutMode: 'solo' },
{ port: 13333, payoutMode: 'pplns' },
]);
});
it('rejects a port configured for both payout modes', () => {
expect(() => parsePayoutModePorts('3333', '3333'))
.toThrow('Port 3333 is configured for both solo and pplns payout modes');
});
it('normalizes unknown mode values to solo', () => {
expect(normalizePayoutMode('pplns')).toBe('pplns');
expect(normalizePayoutMode('pool')).toBe('solo');
expect(normalizePayoutMode(undefined)).toBe('solo');
});
});
+44
View File
@@ -0,0 +1,44 @@
export type PayoutMode = 'solo' | 'pplns';
export interface PayoutModePort {
port: number;
payoutMode: PayoutMode;
}
export const DEFAULT_PAYOUT_MODE: PayoutMode = 'solo';
export function normalizePayoutMode(value: unknown): PayoutMode {
return value === 'pplns' ? 'pplns' : 'solo';
}
export function parsePortList(configured?: string | null): number[] {
if (!configured?.trim()) {
return [];
}
return configured
.split(',')
.map(port => parseInt(port.trim(), 10))
.filter(port => Number.isInteger(port) && port > 0 && port <= 65535);
}
export function parsePayoutModePorts(
soloPorts?: string | null,
pplnsPorts?: string | null,
): PayoutModePort[] {
const byPort = new Map<number, PayoutMode>();
const addPorts = (configured: string | null | undefined, payoutMode: PayoutMode) => {
for (const port of parsePortList(configured)) {
const existingMode = byPort.get(port);
if (existingMode != null && existingMode !== payoutMode) {
throw new Error(`Port ${port} is configured for both ${existingMode} and ${payoutMode} payout modes`);
}
byPort.set(port, payoutMode);
}
};
addPorts(soloPorts, 'solo');
addPorts(pplnsPorts, 'pplns');
return Array.from(byPort.entries()).map(([port, payoutMode]) => ({ port, payoutMode }));
}
+133 -23
View File
@@ -8,6 +8,7 @@ import { ClientStatisticsService } from '../src/ORM/client-statistics/client-sta
import { ClientEntity } from '../src/ORM/client/client.entity'; import { ClientEntity } from '../src/ORM/client/client.entity';
import { PayoutSnapshotService } from '../src/ORM/payout-snapshot/payout-snapshot.service'; import { PayoutSnapshotService } from '../src/ORM/payout-snapshot/payout-snapshot.service';
import { ShareAccountingService } from '../src/ORM/share-accounting/share-accounting.service'; import { ShareAccountingService } from '../src/ORM/share-accounting/share-accounting.service';
import { ShareHighScoreService } from '../src/ORM/share-accounting/share-high-score.service';
import { RedisMessagingService } from '../src/services/redis-messaging.service'; import { RedisMessagingService } from '../src/services/redis-messaging.service';
describe('TimescaleDB and Redis integration', () => { describe('TimescaleDB and Redis integration', () => {
@@ -49,11 +50,11 @@ describe('TimescaleDB and Redis integration', () => {
await dataSource.query(`DELETE FROM payout_balance`); await dataSource.query(`DELETE FROM payout_balance`);
await dataSource.query(`DELETE FROM share_rollup_batch_summary`); await dataSource.query(`DELETE FROM share_rollup_batch_summary`);
await dataSource.query(`DELETE FROM share_rollup_batch`); await dataSource.query(`DELETE FROM share_rollup_batch`);
await dataSource.query(`DELETE FROM accepted_share_high_score`);
await dataSource.query(`DELETE FROM accepted_share_entity`); await dataSource.query(`DELETE FROM accepted_share_entity`);
await dataSource.query(`DELETE FROM blocks_entity`); await dataSource.query(`DELETE FROM blocks_entity`);
await dataSource.query(`DELETE FROM client_entity`); await dataSource.query(`DELETE FROM client_entity`);
await dataSource.query(`REFRESH MATERIALIZED VIEW user_agent_report_view`); await dataSource.query(`REFRESH MATERIALIZED VIEW user_agent_report_view`);
await redisMessagingService.clearClientPresence();
await (redisMessagingService as any).publisher.del('json-cache:presence:user-agent-report'); await (redisMessagingService as any).publisher.del('json-cache:presence:user-agent-report');
}); });
@@ -64,10 +65,13 @@ describe('TimescaleDB and Redis integration', () => {
const hypertables = await dataSource.query(` const hypertables = await dataSource.query(`
SELECT hypertable_name, compression_enabled SELECT hypertable_name, compression_enabled
FROM timescaledb_information.hypertables FROM timescaledb_information.hypertables
WHERE hypertable_name = 'accepted_share_entity' WHERE hypertable_name IN ('accepted_share_entity', 'share_rollup_batch_summary')
ORDER BY hypertable_name
`); `);
expect(hypertables).toHaveLength(1); expect(hypertables).toEqual([
expect(hypertables[0].compression_enabled).toBe(true); expect.objectContaining({ hypertable_name: 'accepted_share_entity', compression_enabled: true }),
expect.objectContaining({ hypertable_name: 'share_rollup_batch_summary', compression_enabled: true }),
]);
const aggregates = await dataSource.query(` const aggregates = await dataSource.query(`
SELECT view_name SELECT view_name
@@ -91,37 +95,55 @@ describe('TimescaleDB and Redis integration', () => {
expect(legacyTables).toHaveLength(0); expect(legacyTables).toHaveLength(0);
const policies = await dataSource.query(` const policies = await dataSource.query(`
SELECT proc_name, schedule_interval::text AS schedule_interval SELECT proc_name, schedule_interval::text AS schedule_interval, hypertable_name
FROM timescaledb_information.jobs FROM timescaledb_information.jobs
WHERE hypertable_name = 'accepted_share_entity' WHERE hypertable_name = 'accepted_share_entity'
OR hypertable_name = 'share_rollup_batch_summary'
OR proc_name = 'prune_share_rollup_batches'
OR application_name LIKE 'Refresh Continuous Aggregate Policy%' OR application_name LIKE 'Refresh Continuous Aggregate Policy%'
ORDER BY proc_name, schedule_interval ORDER BY proc_name, schedule_interval
`); `);
expect(policies).toEqual(expect.arrayContaining([ expect(policies).toEqual(expect.arrayContaining([
expect.objectContaining({ proc_name: 'policy_compression' }), expect.objectContaining({ proc_name: 'policy_compression', hypertable_name: 'accepted_share_entity' }),
expect.objectContaining({ proc_name: 'policy_retention' }), expect.objectContaining({ proc_name: 'policy_compression', hypertable_name: 'share_rollup_batch_summary' }),
expect.objectContaining({ proc_name: 'policy_retention', hypertable_name: 'accepted_share_entity' }),
expect.objectContaining({ proc_name: 'prune_share_rollup_batches' }),
expect.objectContaining({ proc_name: 'policy_refresh_continuous_aggregate' }), expect.objectContaining({ proc_name: 'policy_refresh_continuous_aggregate' }),
])); ]));
const shareOrderObjects = await dataSource.query(` const shareOrderObjects = await dataSource.query(`
SELECT to_regclass('public.accepted_share_index_seq') AS sequence_name, SELECT to_regclass('public.accepted_share_index_seq') AS sequence_name,
to_regclass('public."IDX_accepted_share_order"') AS index_name to_regclass('public."IDX_accepted_share_mode_order"') AS index_name,
to_regclass('public."IDX_accepted_share_accounting_lookup"') AS dropped_accounting_lookup,
to_regclass('public."IDX_accepted_share_client_lookup"') AS dropped_client_lookup,
to_regclass('public."IDX_accepted_share_round_best"') AS dropped_round_best
`); `);
expect(shareOrderObjects[0]).toEqual({ expect(shareOrderObjects[0]).toEqual({
sequence_name: 'accepted_share_index_seq', sequence_name: 'accepted_share_index_seq',
index_name: '"IDX_accepted_share_order"', index_name: '"IDX_accepted_share_mode_order"',
dropped_accounting_lookup: null,
dropped_client_lookup: null,
dropped_round_best: null,
}); });
const shareRollupObjects = await dataSource.query(` const shareRollupObjects = await dataSource.query(`
SELECT SELECT
to_regclass('public.share_rollup_batch') AS batch_table, to_regclass('public.share_rollup_batch') AS batch_table,
to_regclass('public.share_rollup_batch_summary') AS summary_table, to_regclass('public.share_rollup_batch_summary') AS summary_table,
to_regclass('public."IDX_share_rollup_batch_finalized_end"') AS finalized_index to_regclass('public.accepted_share_high_score') AS high_score_table,
to_regclass('public."IDX_share_rollup_batch_finalized_end"') AS finalized_index,
to_regclass('public."IDX_share_rollup_summary_batch"') AS summary_batch_index,
to_regclass('public."UQ_accepted_share_high_score_scope"') AS high_score_scope_index,
to_regclass('public."IDX_share_rollup_summary_address_batch"') AS dropped_summary_address_index
`); `);
expect(shareRollupObjects[0]).toEqual({ expect(shareRollupObjects[0]).toEqual({
batch_table: 'share_rollup_batch', batch_table: 'share_rollup_batch',
summary_table: 'share_rollup_batch_summary', summary_table: 'share_rollup_batch_summary',
high_score_table: 'accepted_share_high_score',
finalized_index: '"IDX_share_rollup_batch_finalized_end"', finalized_index: '"IDX_share_rollup_batch_finalized_end"',
summary_batch_index: '"IDX_share_rollup_summary_batch"',
high_score_scope_index: '"UQ_accepted_share_high_score_scope"',
dropped_summary_address_index: null,
}); });
const payoutObjects = await dataSource.query(` const payoutObjects = await dataSource.query(`
@@ -156,6 +178,7 @@ describe('TimescaleDB and Redis integration', () => {
await service.recordAcceptedShare({ await service.recordAcceptedShare({
protocol: 'sv1', protocol: 'sv1',
payoutMode: 'pplns',
acceptedAt, acceptedAt,
address: client.address, address: client.address,
clientName: client.clientName, clientName: client.clientName,
@@ -176,6 +199,7 @@ describe('TimescaleDB and Redis integration', () => {
}); });
await service.recordAcceptedShare({ await service.recordAcceptedShare({
protocol: 'sv1', protocol: 'sv1',
payoutMode: 'pplns',
acceptedAt: new Date(acceptedAt.getTime() + 1), acceptedAt: new Date(acceptedAt.getTime() + 1),
address: client.address, address: client.address,
clientName: client.clientName, clientName: client.clientName,
@@ -228,6 +252,100 @@ describe('TimescaleDB and Redis integration', () => {
])); ]));
}); });
it('should retain daily and all-time best share from completed rollup buckets', async () => {
const client = await dataSource.getRepository(ClientEntity).save({
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
clientName: 'high-score-worker',
sessionId: '67a6f099',
userAgent: 'integration-test',
startTime: new Date(),
bestDifficulty: 0,
hashRate: 0,
});
const accountingService = new ShareAccountingService(dataSource.getRepository(AcceptedShareEntity));
const highScoreService = new ShareHighScoreService(dataSource);
const bucketStartMs = Math.floor((Date.now() - 20 * 60 * 1000) / (10 * 60 * 1000)) * 10 * 60 * 1000;
const acceptedAt = new Date(bucketStartMs + 1000);
for (const [index, submissionDifficulty] of [4096, 1024].entries()) {
await accountingService.recordAcceptedShare({
protocol: index === 0 ? 'sv2' : 'sv1',
payoutMode: 'pplns',
acceptedAt: new Date(acceptedAt.getTime() + index),
address: client.address,
clientName: client.clientName,
sessionId: client.sessionId,
clientId: client.id,
jobId: `high-score-${index}`,
jobTemplateId: 'high-score-template',
blockHeight: 900100,
creditedDifficulty: 64,
submissionDifficulty,
networkDifficulty: 100000,
nonce: `high-score-nonce-${index}`,
ntime: '64b3f3ec',
version: '20000000',
extraNonce2: `c70800000000000${index}`,
isBlockCandidate: false,
blockSubmissionResult: null,
});
}
await dataSource.query(
`CALL refresh_continuous_aggregate('accepted_share_block_10m', $1::timestamptz, $2::timestamptz)`,
[new Date(bucketStartMs), new Date(bucketStartMs + 10 * 60 * 1000)],
);
await expect(highScoreService.refreshHighScores()).resolves.toEqual(expect.objectContaining({
processed: true,
}));
const rows = await dataSource.query(`
SELECT
"scope",
"payoutMode",
"submissionDifficulty"::float AS "submissionDifficulty",
"address",
"clientName",
"protocol"
FROM accepted_share_high_score
WHERE "payoutMode" IN ('all', 'pplns')
ORDER BY "payoutMode", "scope"
`);
expect(rows).toEqual(expect.arrayContaining([
expect.objectContaining({
scope: 'all_time',
payoutMode: 'all',
submissionDifficulty: 4096,
address: client.address,
clientName: client.clientName,
protocol: 'sv2',
}),
expect.objectContaining({
scope: 'all_time',
payoutMode: 'pplns',
submissionDifficulty: 4096,
address: client.address,
clientName: client.clientName,
protocol: 'sv2',
}),
expect.objectContaining({
scope: 'daily',
payoutMode: 'pplns',
submissionDifficulty: 4096,
address: client.address,
clientName: client.clientName,
protocol: 'sv2',
}),
]));
const summaryService = new ShareAccountingService(dataSource.getRepository(AcceptedShareEntity));
await expect(summaryService.refreshPoolSummary('pplns')).resolves.toEqual(expect.objectContaining({
bestSubmissionDifficulty: 4096,
}));
});
it('should finalize accepted shares into share rollup batches without mutating raw rows', async () => { it('should finalize accepted shares into share rollup batches without mutating raw rows', async () => {
const client = await dataSource.getRepository(ClientEntity).save({ const client = await dataSource.getRepository(ClientEntity).save({
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
@@ -243,6 +361,7 @@ describe('TimescaleDB and Redis integration', () => {
await service.recordAcceptedShare({ await service.recordAcceptedShare({
protocol: 'sv1', protocol: 'sv1',
payoutMode: 'pplns',
acceptedAt, acceptedAt,
address: client.address, address: client.address,
clientName: client.clientName, clientName: client.clientName,
@@ -263,6 +382,7 @@ describe('TimescaleDB and Redis integration', () => {
}); });
await service.recordAcceptedShare({ await service.recordAcceptedShare({
protocol: 'sv2', protocol: 'sv2',
payoutMode: 'pplns',
acceptedAt: new Date(acceptedAt.getTime() + 1), acceptedAt: new Date(acceptedAt.getTime() + 1),
address: client.address, address: client.address,
clientName: client.clientName, clientName: client.clientName,
@@ -357,6 +477,7 @@ describe('TimescaleDB and Redis integration', () => {
for (const [index, client] of clients.entries()) { for (const [index, client] of clients.entries()) {
await accountingService.recordAcceptedShare({ await accountingService.recordAcceptedShare({
protocol: 'sv1', protocol: 'sv1',
payoutMode: 'pplns',
acceptedAt: new Date(acceptedAt.getTime() + index), acceptedAt: new Date(acceptedAt.getTime() + index),
address: client.address, address: client.address,
clientName: client.clientName, clientName: client.clientName,
@@ -491,7 +612,7 @@ describe('TimescaleDB and Redis integration', () => {
bestDifficulty: 11, bestDifficulty: 11,
hashRate: 0, hashRate: 0,
}); });
await repository.save({ const staleClient = await repository.save({
address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4', address: 'tb1qumezefzdeqqwn5zfvgdrhxjzc5ylr39uhuxcz4',
clientName: 'stale-live-worker', clientName: 'stale-live-worker',
sessionId: '92b2c3d4', sessionId: '92b2c3d4',
@@ -500,18 +621,7 @@ describe('TimescaleDB and Redis integration', () => {
bestDifficulty: 22, bestDifficulty: 22,
hashRate: 200, hashRate: 200,
}); });
await repository.softDelete(staleClient.id);
await redisMessagingService.setClientPresence({
clientId: activeClient.id,
address: activeClient.address,
clientName: activeClient.clientName,
sessionId: activeClient.sessionId,
userAgent,
startTime: activeClient.startTime.toISOString(),
lastSeen: new Date().toISOString(),
bestDifficulty: Number(activeClient.bestDifficulty),
hashRate: 0,
});
const rows = await reportService.getReport(); const rows = await reportService.getReport();
expect(rows).toEqual(expect.arrayContaining([{ expect(rows).toEqual(expect.arrayContaining([{