Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,23 @@ else()
message(FATAL "Unsupported compiler.")
endif()

# Compiled output
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

# Main executable
add_executable(${PROJECT_NAME} src/Qiner.cpp src/keyUtils.cpp)

include_directories(${PROJECT_NAME} ./src)

# Linking
if(WIN32)
target_compile_definitions(${PROJECT_NAME} PRIVATE NOMINMAX)
target_link_libraries(${PROJECT_NAME} wsock32 ws2_32)
else()
target_link_libraries(${PROJECT_NAME} pthread)
endif()

# Other projects
add_subdirectory(test)
43 changes: 43 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
Permission is hereby granted, perpetual, worldwide, non-exclusive, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:



1. The Software cannot be used in any form or in any substantial portions for development, maintenance and for any other purposes, in the military sphere and in relation to military products, including, but not limited to:

a. any kind of armored force vehicles, missile weapons, warships, artillery weapons, air military vehicles (including military aircrafts, combat helicopters, military drones aircrafts), air defense systems, rifle armaments, small arms, firearms and side arms, melee weapons, chemical weapons, weapons of mass destruction;

b. any special software for development technical documentation for military purposes;

c. any special equipment for tests of prototypes of any subjects with military purpose of use;

d. any means of protection for conduction of acts of a military nature;

e. any software or hardware for determining strategies, reconnaissance, troop positioning, conducting military actions, conducting special operations;

f. any dual-use products with possibility to use the product in military purposes;

g. any other products, software or services connected to military activities;

h. any auxiliary means related to abovementioned spheres and products.



2. The Software cannot be used as described herein in any connection to the military activities. A person, a company, or any other entity, which wants to use the Software, shall take all reasonable actions to make sure that the purpose of use of the Software cannot be possibly connected to military purposes.



3. The Software cannot be used by a person, a company, or any other entity, activities of which are connected to military sphere in any means. If a person, a company, or any other entity, during the period of time for the usage of Software, would engage in activities, connected to military purposes, such person, company, or any other entity shall immediately stop the usage of Software and any its modifications or alterations.



4. Abovementioned restrictions should apply to all modification, alteration, merge, and to other actions, related to the Software, regardless of how the Software was changed due to the abovementioned actions.



The above copyright notice and this permission notice shall be included in all copies or substantial portions, modifications and alterations of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

This project is licensed under the Anti-Military License.
12 changes: 12 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
NOTICE: Third-Party Licenses
============================

This project is licensed under the Anti-Military License. However, it incorporates external components that are governed by their own open-source licenses. Full license texts for these components are included in the repository or referenced below.

---

### 1. Boost Software License, Version 1.0 (BSL-1.0)

**Component:** Catch2 (testing framework)
**Module:** test
---
7 changes: 5 additions & 2 deletions Qiner.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
<ItemGroup>
<ClInclude Include="src\K12AndKeyUtil.h" />
<ClInclude Include="src\keyUtils.h" />
<ClInclude Include="src\score_addition.h" />
<ClInclude Include="src\score_common.h" />
<ClInclude Include="src\score_hyperidentity.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
Expand Down Expand Up @@ -110,7 +113,7 @@
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions);NOMINMAX</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile>
Expand All @@ -125,7 +128,7 @@
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions);NOMINMAX</PreprocessorDefinitions>
<ConformanceMode>Default</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
Expand Down
9 changes: 9 additions & 0 deletions Qiner.vcxproj.filters
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,14 @@
<ClInclude Include="src\keyUtils.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\score_addition.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\score_common.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\score_hyperidentity.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
178 changes: 174 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
# Qubic Reference Miner
This Repo contains the reference implementation of the algoritm used in Qubic.

## Licensing

This project is licensed under the **Anti-Military License**—see the `LICENSE` file for details.

### Third-Party Licenses

This project incorporates code from third-party sources which are governed by different licenses. Full compliance information, including the original copyright notices and terms for these dependencies, can be found in the **`NOTICE`** file in the repository root.

## File structure
- score_hyperidentity.h: Implements the mining and scoring logic using hyperidentity algorithm.
- score_addition.h: Implements the mining and scoring logic using addition algorithm.
- score_common.h: shared functions using for scoring
- Qiner.cpp: Contains the main process logic/functionality. Mainly show how to communicate with the node.
- K12AndKeyUtill.h, keyUtils.h, keyUtils.cpp: Provide K12 and key conversion utilities/functions.

# Requirement
- CPU: support at least AVX2 instruction set
- OS: Windows, Linux
Expand Down Expand Up @@ -74,11 +89,16 @@ CC=clang CXX=clang++ cmake .. -DCMAKE_BUILD_TYPE=Release -DENABLE_AVX512=1

# Run
```
Qiner <IP> <Identity> [<number of threads>]
./Qiner <Node IP> <Node Port> <MiningID> <Signing Seed> <Mining Seed> <Number of threads>
```
- number of threads: Optional, if not parse default number of cores will be used

# Algorithm 2025-05-15
Example:
```
./Qiner 192.168.1.2 31841 BZBQFLLBNCXEMGLOBHUVFTLUPLVCPQUASSILFABOFFBCADQSSUPNWLZBQEXK aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 8
```

# Algorithm 2025-05-15 (hyperidentity)

## Definitions and precondition
- The `random2` generator will be used consistently across the entire pipeline.
Expand Down Expand Up @@ -143,4 +163,154 @@ Given `nonce` and `pubkey` as seeds, and constants `K`, `L`, `N`, `2M`:
5. Run **Tick Simulation** again.
6. Compute the new `R` value:
- If `R > R_best`, discard the mutation.
- If `R ≤ R_best`, accept the mutation and update `R_best = R`.
- If `R ≤ R_best`, accept the mutation and update `R_best = R`.

# Algorithm 2025-12-10 (addition)

## Overview
Focused on implementing an Addition function. The core changes involve the training data set size, input/output representation, and the scoring mechanism.

## Key Changes from Original Algorithm

| Aspect | Original | New |
| ----- | -------- |-----|
| Input neurons | Random, value can be changed in tick simulation | Load from training data, value unchanged in tick simulation|
| Tick simulation | Run once per inference | Run 2^Input pairs|
| Score | Matching bits for 1 pattern | Total matching bits across ALL training pairs|
| Neighbor count | Fixed (always maxNeighbors) | Dynamic (min(maxNeighbors, population-1))|

## Pseudo code
```
// ========== CONSTANTS ==========
// Can be adjusted
K = NUMBER_OF_INPUT_NEURONS // 14 (7 bits for A + 7 bits for B)
L = NUMBER_OF_OUTPUT_NEURONS // 8 (8 bits for result C)
N = NUMBER_OF_TICKS // 120
M = MAX_NEIGHBOR_NEURONS / 2 // 364 (half of 728)
S = NUMBER_OF_MUTATIONS // 100
P = POPULATION_THRESHOLD // K + L + S = 122

TRAINING_SET_SIZE = 2^K // 16,384
MAX_SCORE = TRAINING_SET_SIZE × L // 131,072
SOLUTION_THRESHOLD = MAX_SCORE × 4/5 // 104,857

// ========== I. NEW DATA STRUCTURES ==========
STRUCT Pair:
char input[K] // K/2 bits of A, K/2 bits of B (values: -1 or +1)
char output[L] // L bits of C (values: -1 or +1)

Pair allPairs[ALL_PAIRS_SIZE] // All possible (A, B, C) combinations
Pair selected[SELECTED_SIZE] // Randomly selected training pairs

// ========== II. INITIALIZATION ==========
FUNCTION initialize(publicKey, nonce):
// 1. Generate random2 pool
hash = KangarooTwelve(publicKey || nonce)
initValue = Random2(hash)

// 2. Generate all 2^K possible (A, B, C) pairs
boundValue = 2^(K/2) / 2 // 64 for 7-bit signed [-64, 63]
index = 0
FOR A = -boundValue TO boundValue-1:
FOR B = -boundValue TO boundValue-1:
C = A + B // C in range [-128, 126]
allPairs[index].input[0..K/2-1] = toTernaryBits(A, K/2) // 7 bits
allPairs[index].input[K/2..K-1] = toTernaryBits(B, K/2) // 7 bits
allPairs[index].output = toTernaryBits(C, L) // 8 bits
index++

// 3. Initialize ANN structure
population = K + L
// Randomize location of input neurons and output neurons
randomizeNeuronTypes(initValue) // K inputs, L outputs
// Random weights of synapses
initializeSynapseWeights(initValue)

// 4. Fist inference for init best score
inferANN()

// ========== III. SCORING ==========
FUNCTION inferANN():
totalScore = 0

// Evaluate ANN on all 2^K pairs
FOR i = 0 TO ALL_PAIRS-1:
// Load input values (these stay CONSTANT during ticks)
setInputNeurons(selected[i].input)

// Reset output neurons to 0
resetOutputNeurons()

// Run tick simulation
runTickSimulation()

// Count matching output bits
FOR j = 0 TO L-1:
IF outputNeuron[j].value == selected[i].output[j]:
totalScore++

RETURN totalScore

// ========== IV. TICK SIMULATION ==========
// Same as before, but:
// - Runs on K input neurons and L output neurons
// - Input neuron values are PRESERVED (not updated during ticks)
// - Uses dynamic neighbor count: min(MAX_NEIGHBOR_NEURONS, population - 1)

FUNCTION runTickSimulation():
FOR tick = 0 TO N-1:
// Calculate weighted sums for all neurons
actualNeighbors = min(MAX_NEIGHBOR_NEURONS, population - 1)
FOR each neuron n in population:
sum = 0
FOR each neighbor m within actualNeighbors:
sum += neurons[m].value × synapses[n→m].weight
neuronValueBuffer[n] = sum

// Update only NON-INPUT neurons
FOR each neuron n in population:
IF neurons[n].type != INPUT:
neurons[n].value = clamp(neuronValueBuffer[n], -1, +1)

// Early exit conditions
IF allNeuronsUnchanged() OR allOutputsNonZero():
BREAK

// ========== V. MUTATION ==========
// Same as before
FUNCTION mutate(step):
actualNeighbors = min(MAX_NEIGHBOR_NEURONS, population - 1)
synapseIdx = random(initValue.synapseMutation[step]) % (population × actualNeighbors)

IF currentWeight + mutation is valid (-1, 0, +1):
synapse[synapseIdx].weight += mutation
ELSE:
// Weight overflow → INSERT new neuron
insertNeuron(synapseIdx)
population++

// Remove redundant neurons (all-zero incoming OR outgoing synapses)
WHILE hasRedundantNeurons():
removeRedundantNeurons()

// ========== MAIN LOOP ==========
FUNCTION computeScore(publicKey, nonce):
bestScore = initialize(publicKey, nonce)
bestANN = copy(currentANN)

FOR s = 0 TO S-1:
mutate(s)

IF population >= P:
BREAK

newScore = inferANN()

IF newScore > bestScore:
bestScore = newScore
bestANN = copy(currentANN)
ELSE:
currentANN = copy(bestANN) // Rollback

RETURN bestScore
```
Loading