difficulty calculation, move from randomx to autolykos2

This commit is contained in:
2026-03-30 15:42:28 +02:00
parent c358115af4
commit b47ff30bc7
18 changed files with 1163 additions and 224 deletions

View File

@@ -10,6 +10,7 @@ set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF) set(CMAKE_C_EXTENSIONS OFF)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
include(FetchContent)
# OpenSSL # OpenSSL
find_package(OpenSSL QUIET) find_package(OpenSSL QUIET)
@@ -42,37 +43,39 @@ if(NOT SECP256K1_FOUND)
endif() endif()
endif() endif()
# RandomX # Autolykos2 CPU reference backend (optional)
set(RANDOMX_ROOT "" CACHE PATH "Root directory of a RandomX installation") option(MINICOIN_ENABLE_AUTOLYKOS2_REF "Enable Autolykos2 CPU reference backend" ON)
set(RANDOMX_USING_FETCHCONTENT OFF) set(MINICOIN_AUTOLYKOS2_REF_AVAILABLE OFF)
if(PkgConfig_FOUND)
pkg_check_modules(RANDOMX QUIET IMPORTED_TARGET randomx)
endif()
if(NOT RANDOMX_FOUND) if(MINICOIN_ENABLE_AUTOLYKOS2_REF)
find_path(RANDOMX_INCLUDE_DIR
NAMES randomx.h
HINTS ${RANDOMX_ROOT}
PATH_SUFFIXES include
)
find_library(RANDOMX_LIBRARY
NAMES randomx
HINTS ${RANDOMX_ROOT}
PATH_SUFFIXES lib
)
if(NOT RANDOMX_INCLUDE_DIR OR NOT RANDOMX_LIBRARY)
include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
randomx_src autolykos2_ref_src
GIT_REPOSITORY https://github.com/tevador/RandomX.git GIT_REPOSITORY https://github.com/mhssamadani/Autolykos2_NV_Miner.git
GIT_TAG master GIT_TAG main
GIT_SHALLOW TRUE GIT_SHALLOW TRUE
) )
FetchContent_MakeAvailable(randomx_src) FetchContent_MakeAvailable(autolykos2_ref_src)
set(RANDOMX_USING_FETCHCONTENT ON)
set(RANDOMX_INCLUDE_DIR ${randomx_src_SOURCE_DIR}/src) set(AUTOLYKOS2_REF_BASE ${autolykos2_ref_src_SOURCE_DIR}/secp256k1)
endif() set(AUTOLYKOS2_REF_SOURCES
${AUTOLYKOS2_REF_BASE}/src/cpuAutolykos.cc
${AUTOLYKOS2_REF_BASE}/src/conversion.cc
${AUTOLYKOS2_REF_BASE}/src/cryptography.cc
${AUTOLYKOS2_REF_BASE}/src/definitions.cc
${AUTOLYKOS2_REF_BASE}/src/easylogging++.cc
${AUTOLYKOS2_REF_BASE}/src/jsmn.c
${PROJECT_SOURCE_DIR}/src/autolykos2/easylogging_init.cpp
${PROJECT_SOURCE_DIR}/src/autolykos2/autolykos2_ref_wrapper.cpp
)
add_library(autolykos2_ref STATIC ${AUTOLYKOS2_REF_SOURCES})
target_include_directories(autolykos2_ref PRIVATE ${AUTOLYKOS2_REF_BASE}/include)
target_link_libraries(autolykos2_ref PRIVATE
${CMAKE_THREAD_LIBS_INIT}
OpenSSL::SSL
OpenSSL::Crypto
)
set(MINICOIN_AUTOLYKOS2_REF_AVAILABLE ON)
endif() endif()
# --------------------------------------------------------- # ---------------------------------------------------------
@@ -105,14 +108,8 @@ else()
target_link_libraries(node PRIVATE ${SECP256K1_LIBRARY}) target_link_libraries(node PRIVATE ${SECP256K1_LIBRARY})
endif() endif()
if(RANDOMX_FOUND) if(MINICOIN_AUTOLYKOS2_REF_AVAILABLE)
target_link_libraries(node PRIVATE PkgConfig::RANDOMX) target_link_libraries(node PRIVATE autolykos2_ref)
elseif(RANDOMX_USING_FETCHCONTENT)
target_link_libraries(node PRIVATE randomx)
target_include_directories(node PRIVATE ${RANDOMX_INCLUDE_DIR})
else()
target_include_directories(node PRIVATE ${RANDOMX_INCLUDE_DIR})
target_link_libraries(node PRIVATE ${RANDOMX_LIBRARY})
endif() endif()
target_include_directories(node PRIVATE target_include_directories(node PRIVATE
@@ -126,5 +123,6 @@ target_compile_options(node PRIVATE
) )
target_compile_definitions(node PRIVATE target_compile_definitions(node PRIVATE
CHAIN_DATA_DIR="${CMAKE_BINARY_DIR}/chain_data" CHAIN_DATA_DIR="${CMAKE_BINARY_DIR}/chain_data"
$<$<BOOL:${MINICOIN_AUTOLYKOS2_REF_AVAILABLE}>:MINICOIN_AUTOLYKOS2_REF_AVAILABLE>
) )
set_target_properties(node PROPERTIES OUTPUT_NAME "minicoin_node") set_target_properties(node PROPERTIES OUTPUT_NAME "minicoin_node")

504
LICENSE Normal file
View File

@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey 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 library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -1,8 +1,20 @@
# MiniCoin # MiniCoin
Basic blockchain currency implementation in C, for educational purposes. Not intended for production use. Privacy coin made in C. One day hopefully with a purpose beyond "educational" :)
Some notes for me right now:
cmake: cmake:
```bash ```bash
cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="-fsanitize=address -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address" cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="-fsanitize=address -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address"
``` ```
Build with clang/clang++ (I don't want to deal with the gcc/MSVC shenangans right now)
Use:
```bash
./bin/minicoin_node <-mine>
```
Main Hashing Algorithm: SHA256d (double SHA256) for now.
Proof-of-Work Algorithm: Autolykos2

View File

@@ -1,2 +1,8 @@
Move to a GPU algo. RandomX is a good candidate, but CPU mining is not that attractive to anyone but people who actually want to support the project. Move to a GPU algo. RandomX is a good candidate, but CPU mining is not that attractive to anyone but people who actually want to support the project.
It won't incentivize people who want to profit, which let's be fair, is the majority of miners. It won't incentivize people who want to profit, which let's be fair, is the majority of miners.
Implement Horizen's "Reorg Penalty" system to make it harder for the young chain to be attacked by a powerful miner.
Make transactions private. A bit more work, but it's a challenge worth taking on.
I want to make an "optional privacy" system, where the TX can be public or private. Of course private TXs need more bytes, so the fees (although low) will be higher for them.
I need to figure out a way to make the privacy work without a UTXO system, and instead, with a "Balance Sheet" approach.

View File

@@ -0,0 +1,55 @@
#ifndef MINICOIN_AUTOLYKOS2_H
#define MINICOIN_AUTOLYKOS2_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct Autolykos2Context Autolykos2Context;
Autolykos2Context* Autolykos2_Create(void);
void Autolykos2_Destroy(Autolykos2Context* ctx);
bool Autolykos2_DagAllocate(Autolykos2Context* ctx, size_t bytes);
bool Autolykos2_DagAppend(Autolykos2Context* ctx, const uint8_t* data, size_t len);
void Autolykos2_DagClear(Autolykos2Context* ctx);
size_t Autolykos2_DagSize(const Autolykos2Context* ctx);
bool Autolykos2_Hash(
Autolykos2Context* ctx,
const uint8_t* message,
size_t messageLen,
uint64_t nonce,
uint32_t height,
uint8_t outHash[32]
);
bool Autolykos2_CheckTarget(
Autolykos2Context* ctx,
const uint8_t message32[32],
uint64_t nonce,
uint32_t height,
const uint8_t target32[32],
uint8_t outHash[32]
);
bool Autolykos2_FindNonceSingleCore(
Autolykos2Context* ctx,
const uint8_t message32[32],
uint32_t height,
const uint8_t target32[32],
uint64_t startNonce,
uint64_t maxIterations,
uint64_t* outNonce,
uint8_t outHash[32]
);
#ifdef __cplusplus
}
#endif
#endif

14
include/blake2/blake2.h Normal file
View File

@@ -0,0 +1,14 @@
#ifndef MINICOIN_BLAKE2_H
#define MINICOIN_BLAKE2_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define MINICOIN_BLAKE2B_OUTBYTES 64
#define MINICOIN_BLAKE2S_OUTBYTES 32
bool Blake2b_Hash(const uint8_t* input, size_t inputLen, uint8_t* out, size_t outLen);
bool Blake2s_Hash(const uint8_t* input, size_t inputLen, uint8_t* out, size_t outLen);
#endif

View File

@@ -7,7 +7,6 @@
#include <block/transaction.h> #include <block/transaction.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include <randomx/librx_wrapper.h>
#include <stdlib.h> #include <stdlib.h>
typedef struct { typedef struct {
@@ -29,11 +28,12 @@ typedef struct {
block_t* Block_Create(); block_t* Block_Create();
void Block_CalculateHash(const block_t* block, uint8_t* outHash); void Block_CalculateHash(const block_t* block, uint8_t* outHash);
void Block_CalculateMerkleRoot(const block_t* block, uint8_t* outHash); void Block_CalculateMerkleRoot(const block_t* block, uint8_t* outHash);
void Block_CalculateRandomXHash(const block_t* block, uint8_t* outHash); void Block_CalculateAutolykos2Hash(const block_t* block, uint8_t* outHash);
void Block_AddTransaction(block_t* block, signed_transaction_t* tx); void Block_AddTransaction(block_t* block, signed_transaction_t* tx);
void Block_RemoveTransaction(block_t* block, uint8_t* txHash); void Block_RemoveTransaction(block_t* block, uint8_t* txHash);
bool Block_HasValidProofOfWork(const block_t* block); bool Block_HasValidProofOfWork(const block_t* block);
bool Block_AllTransactionsValid(const block_t* block); bool Block_AllTransactionsValid(const block_t* block);
void Block_ShutdownPowContext(void);
void Block_Destroy(block_t* block); void Block_Destroy(block_t* block);
void Block_Print(const block_t* block); void Block_Print(const block_t* block);

View File

@@ -25,6 +25,9 @@ void Chain_Wipe(blockchain_t* chain);
// I/O // I/O
bool Chain_SaveToFile(blockchain_t* chain, const char* dirpath, uint256_t currentSupply); bool Chain_SaveToFile(blockchain_t* chain, const char* dirpath, uint256_t currentSupply);
bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* outCurrentSupply); bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* outCurrentSupply, uint32_t* outDifficultyTarget);
// Difficulty
uint32_t Chain_ComputeNextTarget(blockchain_t* chain, uint32_t currentTarget);
#endif #endif

View File

@@ -8,8 +8,29 @@
#define DECIMALS 1000000000000ULL #define DECIMALS 1000000000000ULL
#define DIFFICULTY_ADJUSTMENT_INTERVAL 960 // Every 960 blocks (roughly every 24 hours with a 90 second block time) #define DIFFICULTY_ADJUSTMENT_INTERVAL 960 // Every 960 blocks (roughly every 24 hours with a 90 second block time)
// Max adjustment per is x2. So if blocks are coming in too fast, the difficulty will at most double every 24 hours, and vice versa if they're coming in too slow. // Max adjustment per is x2. So if blocks are coming in too fast, the difficulty will at most double every 24 hours, and vice versa if they're coming in too slow.
#define RANDOMX_KEY_ROTATION_INTERVAL 6720 // 1 week at 90s block time
#define TARGET_BLOCK_TIME 90 // Target block time in seconds #define TARGET_BLOCK_TIME 90 // Target block time in seconds
#define INITIAL_DIFFICULTY 0x1f0c1422 // Default compact target used by Autolykos2 PoW (This is ridiculously low)
//#define INITIAL_DIFFICULTY 0x1d1b7c51 // This takes 90s on my machine with a single thread, good for testing
// Future Autolykos2 constants:
#define EPOCH_LENGTH 350000 // ~1 year at 90s
#define BASE_DAG_SIZE (2ULL << 30) // 2 GB
#define DAG_BASE_GROWTH (1ULL << 30) // 1 GB, calculated fully later
#define DAG_BASE_CAP (8ULL << 30) // 8 GB, adjusted per cycle based off DAG_BASE_GROWTH
// Swings - calculated as MIN(percentage, absolute GB) to prevent absurd swings from low hashrate or very large DAG growth
#define DAG_MAX_UP_SWING_PERCENTAGE 1.3 // 30%
#define DAG_MAX_DOWN_SWING_PERCENTAGE 0.85 // 15%
#define DAG_MAX_UP_SWING_GB (4ULL << 30) // 4 GB
#define DAG_MAX_DOWN_SWING_GB (1ULL << 30) // 1 GB
#define KICKOUT_TARGET_PERCENTAGE 75
#define KICKOUT_TARGET_BLOCK 30000 // 1 month at 90s block time
/**
* Each epoch has 2 phases, connected logarithmically:
* - Phase 1: Aggressive DAG growth (target is ~75% of the max cap) to kick out any ASICs, 30k blocks (roughly 1 month)
* - Phase 2: Stable DAG growth (target is the max cap) to provide a stable environment for GPU miners, 320k blocks (roughly 11 months)
**/
static const uint64_t M_CAP = 18446744073709551615ULL; // Max uint64 static const uint64_t M_CAP = 18446744073709551615ULL; // Max uint64
static const uint64_t TAIL_EMISSION = DECIMALS; // Emission floor is 1.0 coins per block static const uint64_t TAIL_EMISSION = DECIMALS; // Emission floor is 1.0 coins per block
// No max supply. Instead of halving, it'll follow a more gradual, Monero-like emission curve. // No max supply. Instead of halving, it'll follow a more gradual, Monero-like emission curve.

View File

@@ -1,21 +0,0 @@
#ifndef LIBRX_WRAPPER_H
#define LIBRX_WRAPPER_H
#include <stddef.h>
#include <stdint.h>
#include <randomx.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
bool RandomX_Init(const char* key, bool preferFullMemory);
void RandomX_Destroy();
void RandomX_CalculateHash(const uint8_t* input, size_t inputLen, uint8_t* output);
#ifdef __cplusplus
}
#endif
#endif

225
src/autolykos2/autolykos2.c Normal file
View File

@@ -0,0 +1,225 @@
#include <autolykos2/autolykos2.h>
#include "../../include/blake2/blake2.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
uint8_t* buf;
size_t cap;
size_t len;
} dag_buffer_t;
struct Autolykos2Context {
dag_buffer_t dag;
void* backend;
};
#ifdef MINICOIN_AUTOLYKOS2_REF_AVAILABLE
extern void* minicoin_autolykos2_ref_create(void);
extern void minicoin_autolykos2_ref_destroy(void* handle);
extern bool minicoin_autolykos2_ref_check_target(
void* handle,
const uint8_t message32[32],
uint64_t nonce,
uint32_t height,
const uint8_t target32[32]
);
#endif
static bool Autolykos2_FallbackHash(
const Autolykos2Context* ctx,
const uint8_t* message,
size_t messageLen,
uint64_t nonce,
uint32_t height,
uint8_t outHash[32]
) {
uint8_t nonceBytes[8];
uint8_t heightBytes[4];
memcpy(nonceBytes, &nonce, sizeof(nonceBytes));
memcpy(heightBytes, &height, sizeof(heightBytes));
size_t dagChunkLen = 0;
const uint8_t* dagChunk = NULL;
if (ctx && ctx->dag.buf && ctx->dag.len > 0) {
dagChunk = ctx->dag.buf;
dagChunkLen = ctx->dag.len > 64 ? 64 : ctx->dag.len;
}
const size_t totalLen = messageLen + sizeof(nonceBytes) + sizeof(heightBytes) + dagChunkLen;
uint8_t* material = (uint8_t*)malloc(totalLen == 0 ? 1 : totalLen);
if (!material) {
return false;
}
size_t off = 0;
if (messageLen > 0) {
memcpy(material + off, message, messageLen);
off += messageLen;
}
memcpy(material + off, nonceBytes, sizeof(nonceBytes));
off += sizeof(nonceBytes);
memcpy(material + off, heightBytes, sizeof(heightBytes));
off += sizeof(heightBytes);
if (dagChunkLen > 0) {
memcpy(material + off, dagChunk, dagChunkLen);
}
const bool ok = Blake2b_Hash(material, totalLen, outHash, 32);
free(material);
return ok;
}
static int Cmp256BE(const uint8_t a[32], const uint8_t b[32]) {
for (size_t i = 0; i < 32; ++i) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
return 0;
}
Autolykos2Context* Autolykos2_Create(void) {
Autolykos2Context* ctx = (Autolykos2Context*)calloc(1, sizeof(Autolykos2Context));
if (!ctx) {
return NULL;
}
#ifdef MINICOIN_AUTOLYKOS2_REF_AVAILABLE
ctx->backend = minicoin_autolykos2_ref_create();
#endif
return ctx;
}
void Autolykos2_Destroy(Autolykos2Context* ctx) {
if (!ctx) {
return;
}
#ifdef MINICOIN_AUTOLYKOS2_REF_AVAILABLE
if (ctx->backend) {
minicoin_autolykos2_ref_destroy(ctx->backend);
ctx->backend = NULL;
}
#endif
free(ctx->dag.buf);
free(ctx);
}
bool Autolykos2_DagAllocate(Autolykos2Context* ctx, size_t bytes) {
if (!ctx) {
return false;
}
uint8_t* newBuf = (uint8_t*)realloc(ctx->dag.buf, bytes == 0 ? 1 : bytes);
if (!newBuf) {
return false;
}
ctx->dag.buf = newBuf;
ctx->dag.cap = bytes;
if (ctx->dag.len > bytes) {
ctx->dag.len = bytes;
}
if (bytes > 0) {
memset(ctx->dag.buf, 0, bytes);
}
return true;
}
bool Autolykos2_DagAppend(Autolykos2Context* ctx, const uint8_t* data, size_t len) {
if (!ctx || !data || len == 0) {
return false;
}
if (ctx->dag.len + len > ctx->dag.cap) {
return false;
}
memcpy(ctx->dag.buf + ctx->dag.len, data, len);
ctx->dag.len += len;
return true;
}
void Autolykos2_DagClear(Autolykos2Context* ctx) {
if (!ctx || !ctx->dag.buf) {
return;
}
memset(ctx->dag.buf, 0, ctx->dag.cap);
ctx->dag.len = 0;
}
size_t Autolykos2_DagSize(const Autolykos2Context* ctx) {
return ctx ? ctx->dag.len : 0;
}
bool Autolykos2_Hash(
Autolykos2Context* ctx,
const uint8_t* message,
size_t messageLen,
uint64_t nonce,
uint32_t height,
uint8_t outHash[32]
) {
if (!ctx || !message || !outHash) {
return false;
}
return Autolykos2_FallbackHash(ctx, message, messageLen, nonce, height, outHash);
}
bool Autolykos2_CheckTarget(
Autolykos2Context* ctx,
const uint8_t message32[32],
uint64_t nonce,
uint32_t height,
const uint8_t target32[32],
uint8_t outHash[32]
) {
if (!ctx || !message32 || !target32 || !outHash) {
return false;
}
#ifdef MINICOIN_AUTOLYKOS2_REF_AVAILABLE
if (ctx->backend) {
const bool ok = minicoin_autolykos2_ref_check_target(ctx->backend, message32, nonce, height, target32);
if (Autolykos2_FallbackHash(ctx, message32, 32, nonce, height, outHash)) {
return ok;
}
return false;
}
#endif
if (!Autolykos2_FallbackHash(ctx, message32, 32, nonce, height, outHash)) {
return false;
}
return Cmp256BE(outHash, target32) <= 0;
}
bool Autolykos2_FindNonceSingleCore(
Autolykos2Context* ctx,
const uint8_t message32[32],
uint32_t height,
const uint8_t target32[32],
uint64_t startNonce,
uint64_t maxIterations,
uint64_t* outNonce,
uint8_t outHash[32]
) {
if (!ctx || !message32 || !target32 || !outNonce || !outHash) {
return false;
}
uint64_t nonce = startNonce;
for (uint64_t i = 0; i < maxIterations; ++i, ++nonce) {
if (Autolykos2_CheckTarget(ctx, message32, nonce, height, target32, outHash)) {
*outNonce = nonce;
return true;
}
}
return false;
}

View File

@@ -0,0 +1,86 @@
#include <cstdint>
#include <cstring>
#include <cpuAutolykos.h>
#include <definitions.h>
// Reference implementation dependency from request.cc. We provide it locally
// to avoid pulling the network/request stack.
uint32_t calcN(uint32_t Hblock) {
uint32_t headerHeight = 0;
((uint8_t*)&headerHeight)[0] = ((uint8_t*)&Hblock)[3];
((uint8_t*)&headerHeight)[1] = ((uint8_t*)&Hblock)[2];
((uint8_t*)&headerHeight)[2] = ((uint8_t*)&Hblock)[1];
((uint8_t*)&headerHeight)[3] = ((uint8_t*)&Hblock)[0];
uint32_t newN = INIT_N_LEN;
if (headerHeight < IncreaseStart) {
newN = INIT_N_LEN;
} else if (headerHeight >= IncreaseEnd) {
newN = MAX_N_LEN;
} else {
uint32_t itersNumber = (headerHeight - IncreaseStart) / IncreasePeriodForN + 1;
for (uint32_t i = 0; i < itersNumber; i++) {
newN = newN / 100 * 105;
}
}
return newN;
}
struct minicoin_autolykos2_ref_handle {
AutolykosAlg* alg;
};
extern "C" void* minicoin_autolykos2_ref_create(void) {
minicoin_autolykos2_ref_handle* h = new minicoin_autolykos2_ref_handle();
h->alg = new AutolykosAlg();
return h;
}
extern "C" void minicoin_autolykos2_ref_destroy(void* handle) {
if (!handle) {
return;
}
auto* h = static_cast<minicoin_autolykos2_ref_handle*>(handle);
delete h->alg;
delete h;
}
extern "C" bool minicoin_autolykos2_ref_check_target(
void* handle,
const uint8_t message32[32],
uint64_t nonce,
uint32_t height,
const uint8_t target32[32]
) {
if (!handle || !message32 || !target32) {
return false;
}
auto* h = static_cast<minicoin_autolykos2_ref_handle*>(handle);
if (!h->alg) {
return false;
}
uint8_t nonceBytes[8];
uint8_t heightBytes[4];
std::memcpy(nonceBytes, &nonce, sizeof(nonceBytes));
// RunAlg expects height bytes; keep deterministic network order.
heightBytes[0] = static_cast<uint8_t>((height >> 24) & 0xffu);
heightBytes[1] = static_cast<uint8_t>((height >> 16) & 0xffu);
heightBytes[2] = static_cast<uint8_t>((height >> 8) & 0xffu);
heightBytes[3] = static_cast<uint8_t>(height & 0xffu);
uint8_t poolBound[32];
std::memcpy(poolBound, target32, sizeof(poolBound));
return h->alg->RunAlg(
const_cast<uint8_t*>(message32),
nonceBytes,
poolBound,
heightBytes
);
}

View File

@@ -0,0 +1,3 @@
#include <easylogging++.h>
INITIALIZE_EASYLOGGINGPP

50
src/blake2/blake2.c Normal file
View File

@@ -0,0 +1,50 @@
#include "../../include/blake2/blake2.h"
#include <openssl/evp.h>
#include <string.h>
static bool Blake2_HashInternal(
const EVP_MD* md,
size_t maxDigestLen,
const uint8_t* input,
size_t inputLen,
uint8_t* out,
size_t outLen
) {
if (!md || !out || outLen == 0 || outLen > maxDigestLen) {
return false;
}
uint8_t digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) {
return false;
}
bool ok = EVP_DigestInit_ex(ctx, md, NULL) == 1;
if (ok && inputLen > 0) {
ok = EVP_DigestUpdate(ctx, input, inputLen) == 1;
}
if (ok) {
ok = EVP_DigestFinal_ex(ctx, digest, &digestLen) == 1;
}
EVP_MD_CTX_free(ctx);
if (!ok || digestLen < outLen) {
return false;
}
memcpy(out, digest, outLen);
return true;
}
bool Blake2b_Hash(const uint8_t* input, size_t inputLen, uint8_t* out, size_t outLen) {
return Blake2_HashInternal(EVP_blake2b512(), MINICOIN_BLAKE2B_OUTBYTES, input, inputLen, out, outLen);
}
bool Blake2s_Hash(const uint8_t* input, size_t inputLen, uint8_t* out, size_t outLen) {
return Blake2_HashInternal(EVP_blake2s256(), MINICOIN_BLAKE2S_OUTBYTES, input, inputLen, out, outLen);
}

View File

@@ -1,6 +1,23 @@
#include <block/block.h> #include <block/block.h>
#include <autolykos2/autolykos2.h>
#include <stdlib.h> #include <stdlib.h>
static Autolykos2Context* g_autolykos2Ctx = NULL;
static Autolykos2Context* GetAutolykos2Ctx(void) {
if (!g_autolykos2Ctx) {
g_autolykos2Ctx = Autolykos2_Create();
}
return g_autolykos2Ctx;
}
void Block_ShutdownPowContext(void) {
if (g_autolykos2Ctx) {
Autolykos2_Destroy(g_autolykos2Ctx);
g_autolykos2Ctx = NULL;
}
}
block_t* Block_Create() { block_t* Block_Create() {
block_t* block = (block_t*)malloc(sizeof(block_t)); block_t* block = (block_t*)malloc(sizeof(block_t));
if (!block) { if (!block) {
@@ -116,13 +133,28 @@ void Block_CalculateMerkleRoot(const block_t* block, uint8_t* outHash) {
DynArr_destroy(hashes2); DynArr_destroy(hashes2);
} }
void Block_CalculateRandomXHash(const block_t* block, uint8_t* outHash) { void Block_CalculateAutolykos2Hash(const block_t* block, uint8_t* outHash) {
if (!block || !outHash) { if (!block || !outHash) {
return; return;
} }
// PoW hash is also computed from the header only. // PoW hash is computed from the block header, while canonical block hash remains SHA256.
RandomX_CalculateHash((const uint8_t*)&block->header, sizeof(block_header_t), outHash); Autolykos2Context* ctx = GetAutolykos2Ctx();
if (!ctx) {
memset(outHash, 0, 32);
return;
}
if (!Autolykos2_Hash(
ctx,
(const uint8_t*)&block->header,
sizeof(block_header_t),
block->header.nonce,
(uint32_t)block->header.blockNumber,
outHash
)) {
memset(outHash, 0, 32);
}
} }
void Block_AddTransaction(block_t* block, signed_transaction_t* tx) { void Block_AddTransaction(block_t* block, signed_transaction_t* tx) {
@@ -199,7 +231,7 @@ bool Block_HasValidProofOfWork(const block_t* block) {
} }
uint8_t hash[32]; uint8_t hash[32];
Block_CalculateRandomXHash(block, hash); Block_CalculateAutolykos2Hash(block, hash);
return Uint256_CompareBE(hash, target) <= 0; return Uint256_CompareBE(hash, target) <= 0;
} }

View File

@@ -162,6 +162,8 @@ bool Chain_SaveToFile(blockchain_t* chain, const char* dirpath, uint256_t curren
fwrite(zeroHash, sizeof(uint8_t), 32, metaFile); fwrite(zeroHash, sizeof(uint8_t), 32, metaFile);
uint256_t zeroSupply = {0}; uint256_t zeroSupply = {0};
fwrite(&zeroSupply, sizeof(uint256_t), 1, metaFile); fwrite(&zeroSupply, sizeof(uint256_t), 1, metaFile);
uint32_t initialTarget = INITIAL_DIFFICULTY;
fwrite(&initialTarget, sizeof(uint32_t), 1, metaFile);
// TODO: Potentially some other things here, we'll see // TODO: Potentially some other things here, we'll see
} }
@@ -215,6 +217,9 @@ bool Chain_SaveToFile(blockchain_t* chain, const char* dirpath, uint256_t curren
} }
fclose(blockFile); fclose(blockFile);
DynArr_destroy(blk->transactions);
blk->transactions = NULL; // Clear transactions to save memory since they're now saved on disk
} }
// Update metadata with new size and last block hash // Update metadata with new size and last block hash
@@ -228,12 +233,14 @@ bool Chain_SaveToFile(blockchain_t* chain, const char* dirpath, uint256_t curren
fwrite(lastHash, sizeof(uint8_t), 32, metaFile); fwrite(lastHash, sizeof(uint8_t), 32, metaFile);
} }
fwrite(&currentSupply, sizeof(uint256_t), 1, metaFile); fwrite(&currentSupply, sizeof(uint256_t), 1, metaFile);
uint32_t difficultyTarget = ((block_t*)DynArr_at(chain->blocks, newSize - 1))->header.difficultyTarget;
fwrite(&difficultyTarget, sizeof(uint32_t), 1, metaFile);
fclose(metaFile); fclose(metaFile);
return true; return true;
} }
bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* outCurrentSupply) { bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* outCurrentSupply, uint32_t* outDifficultyTarget) {
if (!chain || !chain->blocks || !dirpath || !outCurrentSupply) { if (!chain || !chain->blocks || !dirpath || !outCurrentSupply) {
return false; return false;
} }
@@ -259,6 +266,7 @@ bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* out
uint8_t lastSavedHash[32]; uint8_t lastSavedHash[32];
fread(lastSavedHash, sizeof(uint8_t), 32, metaFile); fread(lastSavedHash, sizeof(uint8_t), 32, metaFile);
fread(outCurrentSupply, sizeof(uint256_t), 1, metaFile); fread(outCurrentSupply, sizeof(uint256_t), 1, metaFile);
fread(outDifficultyTarget, sizeof(uint32_t), 1, metaFile);
fclose(metaFile); fclose(metaFile);
// TODO: Might add a flag to allow reading from a point onward, but just rewrite for now // TODO: Might add a flag to allow reading from a point onward, but just rewrite for now
@@ -308,11 +316,9 @@ bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* out
fclose(blockFile); fclose(blockFile);
Chain_AddBlock(chain, blk); Chain_AddBlock(chain, blk);
if (blk->transactions) { // Chain_AddBlock stores blocks by value, so the copied block now owns
DynArr_destroy(blk->transactions); // blk->transactions. Only free the temporary wrapper struct here.
blk->transactions = NULL; free(blk);
}
free(blk); // chain stores block headers/fields by value
} }
chain->size = savedSize; chain->size = savedSize;
@@ -320,3 +326,78 @@ bool Chain_LoadFromFile(blockchain_t* chain, const char* dirpath, uint256_t* out
// After read, you SHOULD verify chain validity. We're not doing it here since returning false is a bit unclear if the read failed or if the chain is invalid. // After read, you SHOULD verify chain validity. We're not doing it here since returning false is a bit unclear if the read failed or if the chain is invalid.
return true; return true;
} }
uint32_t Chain_ComputeNextTarget(blockchain_t* chain, uint32_t currentTarget) {
if (!chain || !chain->blocks) {
return 0x00; // Impossible difficulty, only valid hash is all zeros (practically impossible)
}
size_t chainSize = DynArr_size(chain->blocks);
if (chainSize < DIFFICULTY_ADJUSTMENT_INTERVAL) {
// Baby-chain, return initial difficulty
return INITIAL_DIFFICULTY;
}
// Assuming block validation validates timestamps, we can assume they're valid and can just read them
block_t* lastBlock = (block_t*)DynArr_at(chain->blocks, chainSize - 1);
block_t* adjustmentBlock = (block_t*)DynArr_at(chain->blocks, chainSize - DIFFICULTY_ADJUSTMENT_INTERVAL);
if (!lastBlock || !adjustmentBlock) {
return 0x00; // Impossible difficulty, only valid hash is all zeros (practically impossible)
}
// Retarget uses whole-window span. Per-block average is implicit:
// (actualTime / interval) / targetBlockTime == actualTime / targetTime.
uint64_t actualTime = 0;
if (lastBlock->header.timestamp > adjustmentBlock->header.timestamp) {
actualTime = lastBlock->header.timestamp - adjustmentBlock->header.timestamp;
}
if (actualTime == 0) {
return currentTarget; // Invalid/non-increasing time window; keep current target
}
const uint64_t targetTime = (uint64_t)TARGET_BLOCK_TIME * (uint64_t)DIFFICULTY_ADJUSTMENT_INTERVAL;
double timeRatio = (double)actualTime / (double)targetTime;
// Clamp per-epoch target movement: at most x2 easier or x2 harder. TODO: Check if the clamp should be more aggressive or looser
if (timeRatio > 2.0) {
timeRatio = 2.0;
} else if (timeRatio < 0.5) {
timeRatio = 0.5;
}
uint32_t exponent = currentTarget >> 24;
uint32_t mantissa = currentTarget & 0x007fffff;
if (mantissa == 0 || exponent == 0) {
return INITIAL_DIFFICULTY;
}
double newMantissa = (double)mantissa * timeRatio;
// Normalize to compact format range.
while (newMantissa > 8388607.0) { // 0x007fffff
newMantissa /= 256.0;
exponent++;
}
while (newMantissa > 0.0 && newMantissa < 32768.0 && exponent > 3) { // Keep coefficient in normal range
newMantissa *= 256.0;
exponent--;
}
if (exponent > 32) {
// Easiest representable target in our decoder range.
return (32u << 24) | 0x007fffff;
}
if (exponent < 1) {
exponent = 1;
}
uint32_t newCoeff = (uint32_t)newMantissa;
if (newCoeff == 0) {
newCoeff = 1;
}
if (newCoeff > 0x007fffff) {
newCoeff = 0x007fffff;
}
return (exponent << 24) | (newCoeff & 0x007fffff);
}

View File

@@ -8,7 +8,6 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <randomx/librx_wrapper.h>
#include <signal.h> #include <signal.h>
#include <constants.h> #include <constants.h>
@@ -19,56 +18,11 @@
void handle_sigint(int sig) { void handle_sigint(int sig) {
printf("Caught signal %d, exiting...\n", sig); printf("Caught signal %d, exiting...\n", sig);
RandomX_Destroy(); Block_ShutdownPowContext();
exit(0); exit(0);
} }
static double MonotonicSeconds(void) { uint32_t difficultyTarget = INITIAL_DIFFICULTY;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + ((double)ts.tv_nsec / 1000000000.0);
}
static double MeasureRandomXHashrate(void) {
uint8_t input[80] = {0};
uint8_t outHash[32];
uint64_t counter = 0;
const double start = MonotonicSeconds();
double now = start;
do {
memcpy(input, &counter, sizeof(counter));
RandomX_CalculateHash(input, sizeof(input), outHash);
counter++;
now = MonotonicSeconds();
} while ((now - start) < 0.75); // short local benchmark window
const double elapsed = now - start;
if (elapsed <= 0.0 || counter == 0) {
return 0.0;
}
return (double)counter / elapsed;
}
static uint32_t CompactTargetForExpectedHashes(double expectedHashes) {
if (expectedHashes < 1.0) {
expectedHashes = 1.0;
}
// For exponent 0x1f: target = mantissa * 2^(8*(0x1f-3)) = mantissa * 2^224
// So expected hashes ~= 2^256 / target = 2^32 / mantissa.
double mantissaF = 4294967296.0 / expectedHashes;
if (mantissaF < 1.0) {
mantissaF = 1.0;
}
if (mantissaF > 8388607.0) {
mantissaF = 8388607.0; // 0x007fffff
}
const uint32_t mantissa = (uint32_t)mantissaF;
return (0x1fU << 24) | (mantissa & 0x007fffffU);
}
static bool MineBlock(block_t* block) { static bool MineBlock(block_t* block) {
if (!block) { if (!block) {
@@ -91,24 +45,18 @@ int main(int argc, char* argv[]) {
signal(SIGINT, handle_sigint); signal(SIGINT, handle_sigint);
const char* chainDataDir = CHAIN_DATA_DIR; const char* chainDataDir = CHAIN_DATA_DIR;
const uint64_t blocksToMine = 10; const uint64_t blocksToMine = 1000;
const double targetSeconds = TARGET_BLOCK_TIME; const double targetSeconds = TARGET_BLOCK_TIME;
uint256_t currentSupply = uint256_from_u64(0); uint256_t currentSupply = uint256_from_u64(0);
// Init RandomX
if (!RandomX_Init("minicoin", false)) { // TODO: Use a key that is not hardcoded; E.g. hash of the last block, every thousand blocks, difficulty recalibration, etc.
fprintf(stderr, "failed to initialize RandomX\n");
return 1;
}
blockchain_t* chain = Chain_Create(); blockchain_t* chain = Chain_Create();
if (!chain) { if (!chain) {
fprintf(stderr, "failed to create chain\n"); fprintf(stderr, "failed to create chain\n");
return 1; return 1;
} }
if (!Chain_LoadFromFile(chain, chainDataDir, &currentSupply)) { if (!Chain_LoadFromFile(chain, chainDataDir, &currentSupply, &difficultyTarget)) {
printf("No existing chain loaded from %s\n", chainDataDir); printf("No existing chain loaded from %s\n", chainDataDir);
} }
@@ -138,17 +86,6 @@ int main(int argc, char* argv[]) {
if (argc > 1 && strcmp(argv[1], "-mine") == 0) { if (argc > 1 && strcmp(argv[1], "-mine") == 0) {
printf("Mining %llu blocks with target time %.0fs...\n", (unsigned long long)blocksToMine, targetSeconds); printf("Mining %llu blocks with target time %.0fs...\n", (unsigned long long)blocksToMine, targetSeconds);
const double hps = MeasureRandomXHashrate();
const double expectedHashes = (hps > 0.0) ? (hps * targetSeconds) : 65536.0;
const uint32_t calibratedBits = CompactTargetForExpectedHashes(expectedHashes);
//const uint32_t calibratedBits = 0xffffffff; // Absurdly low diff for testing
printf("RandomX benchmark: %.2f H/s, target %.0fs, nBits=0x%08x, diff=%.2f\n",
hps,
targetSeconds,
calibratedBits,
(double)(1.f / calibratedBits) * 4294967296.0); // Basic representation as a big number for now
uint8_t minerAddress[32]; uint8_t minerAddress[32];
SHA256((const unsigned char*)"minicoin-miner-1", strlen("minicoin-miner-1"), minerAddress); SHA256((const unsigned char*)"minicoin-miner-1", strlen("minicoin-miner-1"), minerAddress);
@@ -157,7 +94,7 @@ int main(int argc, char* argv[]) {
if (!block) { if (!block) {
fprintf(stderr, "failed to create block\n"); fprintf(stderr, "failed to create block\n");
Chain_Destroy(chain); Chain_Destroy(chain);
RandomX_Destroy(); Block_ShutdownPowContext();
return 1; return 1;
} }
@@ -174,7 +111,7 @@ int main(int argc, char* argv[]) {
memset(block->header.prevHash, 0, sizeof(block->header.prevHash)); memset(block->header.prevHash, 0, sizeof(block->header.prevHash));
} }
block->header.timestamp = (uint64_t)time(NULL); block->header.timestamp = (uint64_t)time(NULL);
block->header.difficultyTarget = calibratedBits; block->header.difficultyTarget = difficultyTarget;
block->header.nonce = 0; block->header.nonce = 0;
signed_transaction_t coinbaseTx; signed_transaction_t coinbaseTx;
@@ -195,7 +132,7 @@ int main(int argc, char* argv[]) {
fprintf(stderr, "failed to mine block within nonce range\n"); fprintf(stderr, "failed to mine block within nonce range\n");
Block_Destroy(block); Block_Destroy(block);
Chain_Destroy(chain); Chain_Destroy(chain);
RandomX_Destroy(); Block_ShutdownPowContext();
return 1; return 1;
} }
@@ -203,28 +140,36 @@ int main(int argc, char* argv[]) {
fprintf(stderr, "failed to append block to chain\n"); fprintf(stderr, "failed to append block to chain\n");
Block_Destroy(block); Block_Destroy(block);
Chain_Destroy(chain); Chain_Destroy(chain);
RandomX_Destroy(); Block_ShutdownPowContext();
return 1; return 1;
} }
(void)uint256_add_u64(&currentSupply, coinbaseTx.transaction.amount); (void)uint256_add_u64(&currentSupply, coinbaseTx.transaction.amount);
uint8_t blockHash[32]; uint8_t canonicalHash[32];
Block_CalculateHash(block, blockHash); uint8_t powHash[32];
printf("Mined block %llu/%llu (height=%llu) nonce=%llu reward=%llu supply=%llu merkle=%02x%02x%02x%02x... hash=%02x%02x%02x%02x...\n", Block_CalculateHash(block, canonicalHash);
Block_CalculateAutolykos2Hash(block, powHash);
printf("Mined block %llu/%llu (height=%llu) nonce=%llu reward=%llu supply=%llu diff=%#x merkle=%02x%02x%02x%02x... pow=%02x%02x%02x%02x... canonical=%02x%02x%02x%02x...\n",
(unsigned long long)(mined + 1), (unsigned long long)(mined + 1),
(unsigned long long)blocksToMine, (unsigned long long)blocksToMine,
(unsigned long long)block->header.blockNumber, (unsigned long long)block->header.blockNumber,
(unsigned long long)block->header.nonce, (unsigned long long)block->header.nonce,
(unsigned long long)coinbaseTx.transaction.amount, (unsigned long long)coinbaseTx.transaction.amount,
(unsigned long long)currentSupply.limbs[0], (unsigned long long)currentSupply.limbs[0],
(unsigned int)block->header.difficultyTarget,
block->header.merkleRoot[0], block->header.merkleRoot[1], block->header.merkleRoot[2], block->header.merkleRoot[3], block->header.merkleRoot[0], block->header.merkleRoot[1], block->header.merkleRoot[2], block->header.merkleRoot[3],
blockHash[0], blockHash[1], blockHash[2], blockHash[3]); powHash[0], powHash[1], powHash[2], powHash[3],
canonicalHash[0], canonicalHash[1], canonicalHash[2], canonicalHash[3]);
free(block); // chain stores blocks by value; transactions are owned by chain copy free(block); // chain stores blocks by value; transactions are owned by chain copy
// Save chain after each mined block // Save chain after each mined block
Chain_SaveToFile(chain, chainDataDir, currentSupply); Chain_SaveToFile(chain, chainDataDir, currentSupply);
if (Chain_Size(chain) % DIFFICULTY_ADJUSTMENT_INTERVAL == 0) {
difficultyTarget = Chain_ComputeNextTarget(chain, difficultyTarget);
}
} }
if (!Chain_SaveToFile(chain, chainDataDir, currentSupply)) { if (!Chain_SaveToFile(chain, chainDataDir, currentSupply)) {
@@ -248,6 +193,6 @@ int main(int argc, char* argv[]) {
} }
Chain_Destroy(chain); Chain_Destroy(chain);
RandomX_Destroy(); Block_ShutdownPowContext();
return 0; return 0;
} }

View File

@@ -1,75 +0,0 @@
#include <randomx/librx_wrapper.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static randomx_cache* rxCache = NULL;
static randomx_dataset* rxDataset = NULL;
static randomx_vm* rxVm = NULL;
bool RandomX_Init(const char* key, bool preferFullMemory) {
if (!key || rxCache || rxVm) {
return false;
}
const randomx_flags baseFlags = randomx_get_flags() | RANDOMX_FLAG_JIT;
randomx_flags vmFlags = baseFlags | RANDOMX_FLAG_FULL_MEM;
rxCache = randomx_alloc_cache(baseFlags);
if (!rxCache) {
return false;
}
randomx_init_cache(rxCache, key, strlen(key));
// Prefer full-memory mode. If dataset allocation fails, fall back to light mode.
if (preferFullMemory) {
rxDataset = randomx_alloc_dataset(vmFlags);
if (rxDataset) {
const unsigned long datasetItems = randomx_dataset_item_count();
randomx_init_dataset(rxDataset, rxCache, 0, datasetItems);
rxVm = randomx_create_vm(vmFlags, NULL, rxDataset);
if (rxVm) {
printf("RandomX initialized in full-memory mode\n");
return true;
}
randomx_release_dataset(rxDataset);
rxDataset = NULL;
}
}
vmFlags = baseFlags;
rxVm = randomx_create_vm(vmFlags, rxCache, NULL);
if (!rxVm) {
randomx_release_cache(rxCache);
rxCache = NULL;
return false;
}
printf("RandomX initialized in light mode\n");
return true;
}
void RandomX_Destroy() {
if (rxVm) {
randomx_destroy_vm(rxVm);
rxVm = NULL;
}
if (rxDataset) {
randomx_release_dataset(rxDataset);
rxDataset = NULL;
}
if (rxCache) {
randomx_release_cache(rxCache);
rxCache = NULL;
}
}
void RandomX_CalculateHash(const uint8_t* input, size_t inputLen, uint8_t* output) {
if (!rxVm || !input || !output) {
return;
}
randomx_calculate_hash(rxVm, input, inputLen, output);
}