├── .gitignore ├── CMakeLists-static.txt ├── CMakeLists.txt ├── License ├── README.md ├── bench.go ├── benchmark ├── benchmark_20231002_122250_1660ti.csv ├── benchmark_20231002_170212_teslak80.csv ├── benchmark_20231002_171413_a2000.csv ├── benchmark_20231002_171927_a16.csv ├── benchmark_20231002_174801_a800.c1sv ├── benchmark_20231002_175358_h800.c1sv ├── benchmark_20231002_180438_3060ti.csv ├── benchmark_20231002_180936_3070ti.csv ├── benchmark_20231002_181723_3080.csv ├── benchmark_20231002_182058_titanx.csv ├── benchmark_20231002_182412_rtx5000.csv ├── benchmark_20231002_233711_rtx1650.csv ├── benchmark_20231002_234523_rtx3080ti.csv ├── benchmark_20231002_234830_rtx4090.csv ├── benchmark_20231002_235303_rtx3090.csv ├── benchmark_20231002_235629_v100SXM2.csv ├── benchmark_20231003_000101_rtx2080ti.csv ├── benchmark_20231003_000545_a4000.csv ├── benchmark_20231003_000919_a5000.csv ├── benchmark_20231003_001406_rtx3060.csv ├── benchmark_20231003_002716_a100SXM4.csv ├── benchmark_20231003_003030_a40.csv ├── benchmark_20231003_003544_titanxp.csv ├── benchmark_20231003_004204_A100PCIE.csv ├── benchmark_20231003_004243_teslat4.csv ├── benchmark_stat.py ├── benchmark_stat_divideprice.py └── prices.txt ├── build.sh ├── config.conf ├── dev ├── bench_mempool.go ├── bench_mempool_multi.go ├── ptrie_db_rlp.py ├── ptrie_db_tests.py └── ptrie_db_zlib.py ├── docs ├── Concurrency_in_world_state.pdf ├── XENIUM_BLOCKCHAIN.pdf ├── xenblocks_whitepaper.v0.1.pdf └── xone_tokenomics.pdf ├── getblocks2.py ├── go ├── go.mod └── merkle_test.go ├── gpage.py ├── gpuMiner ├── LICENSE-argon2-gpu ├── data │ └── kernels │ │ └── argon2_kernel.cl ├── ext │ └── argon2 │ │ ├── .gitattributes │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── CMakeLists.txt │ │ ├── LICENSE │ │ ├── Makefile.am │ │ ├── README.md │ │ ├── arch │ │ ├── generic │ │ │ └── lib │ │ │ │ └── argon2-arch.c │ │ └── x86_64 │ │ │ ├── lib │ │ │ ├── argon2-arch.c │ │ │ ├── argon2-avx2.c │ │ │ ├── argon2-avx2.h │ │ │ ├── argon2-avx512f.c │ │ │ ├── argon2-avx512f.h │ │ │ ├── argon2-sse2.c │ │ │ ├── argon2-sse2.h │ │ │ ├── argon2-ssse3.c │ │ │ ├── argon2-ssse3.h │ │ │ ├── argon2-template-128.h │ │ │ ├── argon2-xop.c │ │ │ ├── argon2-xop.h │ │ │ ├── cpu-flags.c │ │ │ └── cpu-flags.h │ │ │ └── src │ │ │ ├── test-feature-avx2.c │ │ │ ├── test-feature-avx512f.c │ │ │ ├── test-feature-sse2.c │ │ │ ├── test-feature-ssse3.c │ │ │ └── test-feature-xop.c │ │ ├── configure.ac │ │ ├── include │ │ └── argon2.h │ │ ├── lib │ │ ├── argon2-template-64.h │ │ ├── argon2.c │ │ ├── blake2 │ │ │ ├── blake2-impl.h │ │ │ ├── blake2.c │ │ │ └── blake2.h │ │ ├── core.c │ │ ├── core.h │ │ ├── encoding.c │ │ ├── encoding.h │ │ ├── genkat.c │ │ ├── genkat.h │ │ ├── impl-select.c │ │ ├── impl-select.h │ │ ├── thread.c │ │ └── thread.h │ │ ├── m4 │ │ ├── ax_check_compile_flag.m4 │ │ └── ax_pthread.m4 │ │ ├── qmake │ │ ├── arch │ │ │ ├── arch.pro │ │ │ ├── generic │ │ │ │ └── generic.pro │ │ │ └── x86_64 │ │ │ │ ├── libargon2-avx2 │ │ │ │ └── libargon2-avx2.pro │ │ │ │ ├── libargon2-avx512f │ │ │ │ └── libargon2-avx512f.pro │ │ │ │ ├── libargon2-sse2 │ │ │ │ └── libargon2-sse2.pro │ │ │ │ ├── libargon2-ssse3 │ │ │ │ └── libargon2-ssse3.pro │ │ │ │ ├── libargon2-xop │ │ │ │ └── libargon2-xop.pro │ │ │ │ └── x86_64.pro │ │ ├── argon2-bench2 │ │ │ └── argon2-bench2.pro │ │ ├── argon2-genkat │ │ │ └── argon2-genkat.pro │ │ ├── argon2-test │ │ │ └── argon2-test.pro │ │ ├── argon2.pro │ │ ├── argon2 │ │ │ └── argon2.pro │ │ └── libargon2 │ │ │ └── libargon2.pro │ │ ├── scripts │ │ ├── metacentrum │ │ │ ├── start-all-benchmarks.sh │ │ │ └── start-benchmark.sh │ │ └── run-benchmark.sh │ │ ├── src │ │ ├── bench2.c │ │ ├── genkat.c │ │ ├── run.c │ │ └── timing.h │ │ └── tests │ │ └── test.c ├── include │ ├── argon2-cuda │ │ ├── cudaexception.h │ │ ├── device.h │ │ ├── globalcontext.h │ │ ├── kernelrunner.h │ │ ├── processingunit.h │ │ └── programcontext.h │ ├── argon2-gpu-common │ │ ├── argon2-common.h │ │ └── argon2params.h │ ├── argon2-opencl │ │ ├── cl.hpp │ │ ├── device.h │ │ ├── globalcontext.h │ │ ├── kernelrunner.h │ │ ├── opencl.h │ │ ├── processingunit.h │ │ └── programcontext.h │ └── commandline │ │ ├── argumenthandlers.h │ │ ├── commandlineoption.h │ │ └── commandlineparser.h ├── lib │ ├── argon2-cuda │ │ ├── cudaexception.cpp │ │ ├── device.cpp │ │ ├── globalcontext.cpp │ │ ├── kernelrunner.cu │ │ ├── nocuda.cpp │ │ ├── processingunit.cpp │ │ └── programcontext.cpp │ ├── argon2-gpu-common │ │ ├── argon2params.cpp │ │ ├── blake2b.cpp │ │ └── blake2b.h │ └── argon2-opencl │ │ ├── device.cpp │ │ ├── globalcontext.cpp │ │ ├── kernelloader.cpp │ │ ├── kernelloader.h │ │ ├── kernelrunner.cpp │ │ ├── processingunit.cpp │ │ └── programcontext.cpp └── src │ └── argon2-gpu-bench │ ├── benchmark.cpp │ ├── benchmark.h │ ├── cpuexecutive.cpp │ ├── cpuexecutive.h │ ├── cudaexecutive.cpp │ ├── cudaexecutive.h │ ├── main.cpp │ ├── openclexecutive.cpp │ ├── openclexecutive.h │ ├── pwgen.h │ ├── runtimestatistics.h │ └── shared.h ├── index_builder.py ├── indexing ├── block_rate_per_account.py ├── check_rate.py ├── check_seq.py ├── count_consensus.py ├── count_miners.py ├── getblocks.py ├── make_superblocks.py ├── manage_difficulty.py ├── merkleroot.py └── rate_daemon.py ├── make_cache.py ├── make_superblocks.py ├── matrix.py ├── merkleroot.py ├── miner.py ├── miner.sh ├── miner_test.py ├── node_verify.py ├── p2pnode ├── db.go ├── mtree.go ├── node.go ├── rpc.go ├── setup.go ├── sql.go ├── tools.go └── xenp2p.go ├── ptrie_unittest.py ├── readme └── README_ZH.md ├── requirements.txt ├── rpc2.py ├── rpc_server.py ├── syncnode.py ├── test_miner.py ├── tests └── merkle_unittest.py ├── utils ├── account_manager.py ├── bench.py ├── block_rate_per_account.py ├── broadcaster.py ├── engine.sol ├── gen_balances.py ├── get_super_blocks.py ├── go │ ├── main.go │ └── utils.go ├── go_listener │ ├── main.go │ └── utils.go ├── listener.py ├── listener2.py ├── listener3.py ├── make_index.py ├── make_state.py ├── make_state3.py ├── manage_difficulty.py ├── manage_difficulty2.py ├── run_node.go ├── salt_unittest.py ├── verify_proofs.py └── voter.py └── vast └── vash.sh /.gitignore: -------------------------------------------------------------------------------- 1 | xengpuminer 2 | difficulty.txt 3 | build/ 4 | blockchain.db 5 | blockchain.db-journal 6 | hash_rates/ 7 | .idea 8 | logs/ 9 | dist/ 10 | miner.spec 11 | # Byte-compiled / optimized / DLL files 12 | __pycache__/ 13 | *.py[cod] 14 | *$py.class 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Distribution / packaging 20 | .Python 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib/ 28 | lib64/ 29 | parts/ 30 | sdist/ 31 | var/ 32 | wheels/ 33 | share/python-wheels/ 34 | *.egg-info/ 35 | .installed.cfg 36 | *.egg 37 | MANIFEST 38 | 39 | # PyInstaller 40 | # Usually these files are written by a python script from a template 41 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 42 | *.manifest 43 | *.spec 44 | 45 | # Installer logs 46 | pip-log.txt 47 | pip-delete-this-directory.txt 48 | 49 | # Unit test / coverage reports 50 | htmlcov/ 51 | .tox/ 52 | .nox/ 53 | .coverage 54 | .coverage.* 55 | .cache 56 | nosetests.xml 57 | coverage.xml 58 | *.cover 59 | *.py,cover 60 | .hypothesis/ 61 | .pytest_cache/ 62 | cover/ 63 | 64 | # Translations 65 | *.mo 66 | *.pot 67 | 68 | # Django stuff: 69 | *.log 70 | local_settings.py 71 | db.sqlite3 72 | db.sqlite3-journal 73 | 74 | # Flask stuff: 75 | instance/ 76 | .webassets-cache 77 | 78 | # Scrapy stuff: 79 | .scrapy 80 | 81 | # Sphinx documentation 82 | docs/_build/ 83 | 84 | # PyBuilder 85 | .pybuilder/ 86 | target/ 87 | 88 | # Jupyter Notebook 89 | .ipynb_checkpoints 90 | 91 | # IPython 92 | profile_default/ 93 | ipython_config.py 94 | 95 | # pyenv 96 | # For a library or package, you might want to ignore these files since the code is 97 | # intended to run in multiple environments; otherwise, check them in: 98 | # .python-version 99 | 100 | # pipenv 101 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 102 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 103 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 104 | # install all needed dependencies. 105 | #Pipfile.lock 106 | 107 | # poetry 108 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 109 | # This is especially recommended for binary packages to ensure reproducibility, and is more 110 | # commonly ignored for libraries. 111 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 112 | #poetry.lock 113 | 114 | # pdm 115 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 116 | #pdm.lock 117 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 118 | # in version control. 119 | # https://pdm.fming.dev/#use-with-ide 120 | .pdm.toml 121 | 122 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 123 | __pypackages__/ 124 | 125 | # Celery stuff 126 | celerybeat-schedule 127 | celerybeat.pid 128 | 129 | # SageMath parsed files 130 | *.sage.py 131 | 132 | # Environments 133 | .env 134 | .venv 135 | env/ 136 | venv/ 137 | ENV/ 138 | env.bak/ 139 | venv.bak/ 140 | 141 | # Spyder project settings 142 | .spyderproject 143 | .spyproject 144 | 145 | # Rope project settings 146 | .ropeproject 147 | 148 | # mkdocs documentation 149 | /site 150 | 151 | # mypy 152 | .mypy_cache/ 153 | .dmypy.json 154 | dmypy.json 155 | 156 | # Pyre type checker 157 | .pyre/ 158 | 159 | # pytype static type analyzer 160 | .pytype/ 161 | 162 | # Cython debug symbols 163 | cython_debug/ 164 | 165 | # PyCharm 166 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 167 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 168 | # and can be added to the global gitignore or merged into this file. For a more nuclear 169 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 170 | .idea/ 171 | 172 | # dev databases 173 | /*.db 174 | -------------------------------------------------------------------------------- /bench.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "log" 7 | "time" 8 | 9 | "github.com/ethereum/go-ethereum/core/types" 10 | "github.com/ethereum/go-ethereum/common" 11 | "github.com/ethereum/go-ethereum/crypto" 12 | "github.com/ethereum/go-ethereum/rlp" 13 | ) 14 | 15 | func getRecoveredAddress(rawTx string) *string { 16 | // Decode the input string to bytes 17 | rawTxBytes, err := hex.DecodeString(rawTx[2:]) // remove 0x prefix 18 | if err != nil { 19 | log.Fatalf("Invalid transaction hex: %v", err) 20 | } 21 | 22 | // Parse the transaction 23 | tx := new(types.Transaction) 24 | err = rlp.DecodeBytes(rawTxBytes, tx) // Use RLP to decode bytes into the transaction structure 25 | if err != nil { 26 | log.Fatalf("Error unmarshalling transaction: %v", err) 27 | } 28 | 29 | // Get chain ID and create a signer 30 | chainID := tx.ChainId() 31 | signer := types.NewEIP155Signer(chainID) 32 | 33 | // Get the transaction hash using the signer 34 | sigHash := signer.Hash(tx) 35 | 36 | // Extract the signature and recover the sender's address 37 | V, R, S := tx.RawSignatureValues() 38 | 39 | // Adjust V for EIP-155 40 | var V_dec uint64 41 | if chainID.Sign() != 0 { 42 | V_dec = V.Uint64() - uint64(2*chainID.Uint64()+8) // for EIP-155 43 | } else { 44 | V_dec = V.Uint64() // for non-EIP-155, no adjustment needed 45 | } 46 | 47 | // Check if V is 27 or 28, adjust to 0 or 1 for compatibility with Ecrecover 48 | if V_dec == 27 || V_dec == 28 { 49 | V_dec -= 27 50 | } 51 | 52 | if V_dec > 1 { 53 | log.Fatalf("Invalid V value: %v", V_dec) 54 | } 55 | 56 | // Construct the public key from the signature 57 | sig := append(R.Bytes(), S.Bytes()...) // R || S 58 | sig = append(sig, byte(V_dec)) // R || S || V_dec 59 | pubKey, err := crypto.Ecrecover(sigHash[:], sig) 60 | if err != nil { 61 | log.Fatalf("Error recovering public key: %v", err) 62 | } 63 | 64 | var addr common.Address 65 | copy(addr[:], crypto.Keccak256(pubKey[1:])[12:]) // take the last 20 bytes 66 | 67 | address := addr.Hex() 68 | return &address 69 | } 70 | 71 | func benchmarkDecode(rawTx string, numTrials int) []time.Duration { 72 | executionTimes := make([]time.Duration, 0, numTrials) 73 | 74 | for i := 0; i < numTrials; i++ { 75 | startTime := time.Now() 76 | 77 | address := getRecoveredAddress(rawTx) 78 | if address == nil { 79 | log.Println("Error getting recovered address") 80 | continue 81 | } 82 | 83 | endTime := time.Now() 84 | executionTimes = append(executionTimes, endTime.Sub(startTime)) 85 | } 86 | 87 | return executionTimes 88 | } 89 | 90 | func computeMetrics(executionTimes []time.Duration) (avgTime time.Duration, txPerSecond float64) { 91 | var total time.Duration 92 | for _, execTime := range executionTimes { 93 | total += execTime 94 | } 95 | 96 | avgTime = total / time.Duration(len(executionTimes)) 97 | txPerSecond = float64(time.Second) / float64(avgTime) 98 | return 99 | } 100 | 101 | func main() { 102 | // This is your raw Ethereum transaction. 103 | rawTx := "0xf8ab80843b9aca00827b0c94999999cf1046e68e36e1aa2e0e07105eddd0000280b844a9059cbb000000000000000000000000f9b8dd0565b1fac5e9a142c3553f663e09444b9c000000000000000000000000000000000000000000000001236efcbcbb34000083030e2da0919b7300531a90a5e36a54d12e59cb33c2f77a3ea340f92bad063030c209bff1a059ca1d78f3ed0b017e07a6214263fb8a4433a7feff7ac4f0dbe771c1130beaf5" 104 | numTrials := 100000 105 | 106 | executionTimes := benchmarkDecode(rawTx, numTrials) 107 | avgTime, txPerSecond := computeMetrics(executionTimes) 108 | 109 | // Output the metrics 110 | fmt.Printf("\nMetrics over %d trials:\n", numTrials) 111 | fmt.Printf("Average Time: %v\n", avgTime) 112 | fmt.Printf("Transactions per Second: %.2f\n", txPerSecond) 113 | // Recover and print the address 114 | recoveredAddress := getRecoveredAddress(rawTx) 115 | fmt.Printf("Recovered Address: %s\n", *recoveredAddress) 116 | } 117 | -------------------------------------------------------------------------------- /benchmark/benchmark_20231002_174801_a800.c1sv: -------------------------------------------------------------------------------- 1 | # GPU Model: a800 2 | # Date: 2023-10-02 17:48:01 3 | # Difficulty: 10000 to 1000000 step 1000 4 | # Samples: 3 5 | # Total Memory: 84987740160 6 | # Using Memory: 84539604992 7 | Difficulty,BatchSize,HashSpeed 8 | 10000,8174,30845 9 | 11000,7430,27316 10 | 21000,3892,17744 11 | 31000,2636,13268 12 | 41000,1993,11031 13 | 51000,1602,9085 14 | 61000,1340,7065 15 | 71000,1151,6122 16 | 81000,1009,4970 17 | 91000,898,4106 18 | 101000,809,3682 19 | 201000,406,1091 20 | 301000,271,501 21 | 401000,203,287 22 | 501000,163,185 23 | 601000,136,129 24 | 701000,116,95 25 | 801000,102,73 26 | 901000,90,57 27 | -------------------------------------------------------------------------------- /benchmark/benchmark_20231002_175358_h800.c1sv: -------------------------------------------------------------------------------- 1 | # GPU Model: h800 2 | # Date: 2023-10-02 17:53:58 3 | # Difficulty: 10000 to 1000000 step 10000 4 | # Samples: 3 5 | # Total Memory: 84943110144 6 | # Using Memory: 84387954688 7 | Difficulty,BatchSize,HashSpeed 8 | 10000,8159,37369 9 | 20000,4079,27623 10 | 30000,2719,21023 11 | 40000,2039,17230 12 | 50000,1631,13153 13 | 60000,1359,10901 14 | 70000,1165,8715 15 | 80000,1019,7474 16 | 90000,906,6177 17 | 100000,815,5191 18 | 110000,741,4410 19 | 210000,388,1447 20 | 310000,263,689 21 | 410000,199,400 22 | 510000,159,259 23 | 610000,133,182 24 | 710000,114,134 25 | 810000,100,103 26 | 910000,89,82 27 | -------------------------------------------------------------------------------- /benchmark/benchmark_stat.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pandas as pd 3 | import plotly.graph_objects as go 4 | 5 | # Get all CSV files in the current directory 6 | folder_path = os.getcwd() 7 | csv_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.csv')] 8 | 9 | dfs = {f: pd.read_csv(f, comment='#') for f in csv_files} 10 | 11 | # Specify the reference curve and difficulty 12 | reference_curve = 'teslak80' 13 | reference_difficulty = 90010 14 | 15 | # Initialize figure 16 | fig = go.Figure() 17 | 18 | hash_speeds_at_difficulty = {} 19 | 20 | for file, data in dfs.items(): 21 | base_name = os.path.basename(file) 22 | label = base_name.rsplit('_', 1)[1].rstrip('.csv') 23 | 24 | # Store hash speed at the reference difficulty for sorting 25 | hash_speeds_at_difficulty[label] = data.loc[data['Difficulty'] == reference_difficulty, 'HashSpeed'].values[0] 26 | 27 | # Sort labels 28 | sorted_labels = sorted(hash_speeds_at_difficulty.keys(), key=lambda x: hash_speeds_at_difficulty[x], reverse=True) 29 | 30 | # Plot the curves in the sorted order 31 | for label in sorted_labels: 32 | data = dfs[[f for f in csv_files if label in f][0]] 33 | 34 | fig.add_scatter(x=data['Difficulty'], y=data['HashSpeed'], mode='lines', name=label) 35 | 36 | # Add text annotation 37 | if reference_difficulty in data['Difficulty'].values: 38 | fig.add_annotation( 39 | x=reference_difficulty, 40 | y=data.loc[data['Difficulty'] == reference_difficulty, 'HashSpeed'].values[0], 41 | text=f"{label}:{round(data.loc[data['Difficulty'] == reference_difficulty, 'HashSpeed'].values[0],2)}", 42 | showarrow=False, 43 | ) 44 | 45 | # Update layout 46 | fig.update_layout(title='Benchmark Results', 47 | xaxis_title='Difficulty', 48 | yaxis_title='HashSpeed') 49 | 50 | fig.show() -------------------------------------------------------------------------------- /benchmark/benchmark_stat_divideprice.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pandas as pd 3 | import plotly.graph_objects as go 4 | 5 | # Get all CSV files in the current directory 6 | folder_path = os.getcwd() 7 | csv_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.csv')] 8 | 9 | dfs = {f: pd.read_csv(f, comment='#') for f in csv_files} 10 | 11 | price_file = os.path.join(folder_path, 'prices.txt') 12 | prices = {} 13 | if os.path.exists(price_file): 14 | with open(price_file, 'r') as f: 15 | for line in f: 16 | label, price = line.strip().split(':') 17 | prices[label] = float(price) 18 | else: 19 | for f in csv_files: 20 | label = os.path.basename(f).rsplit('_', 1)[1].rstrip('.csv') 21 | prices[label] = 1.0 22 | with open(price_file, 'w') as f: 23 | for label, price in prices.items(): 24 | f.write(f"{label}:{price}\n") 25 | 26 | # Specify the reference curve and difficulty 27 | reference_curve = 'teslak80' 28 | reference_difficulty = 90010 29 | 30 | 31 | # Initialize figure 32 | fig = go.Figure() 33 | 34 | # Step 1: Adjust hash speed by price and find reference values 35 | reference_values = None 36 | for file, data in dfs.items(): 37 | base_name = os.path.basename(file) 38 | label = base_name.rsplit('_', 1)[1].rstrip('.csv') 39 | data['AdjustedHashSpeed'] = data['HashSpeed'] / prices[label] 40 | 41 | if label == reference_curve: 42 | reference_values = data['AdjustedHashSpeed'].values 43 | 44 | # Step 2: Normalize by reference values and plot 45 | hash_speeds_at_difficulty = {} 46 | 47 | for file, data in dfs.items(): 48 | base_name = os.path.basename(file) 49 | label = base_name.rsplit('_', 1)[1].rstrip('.csv') 50 | 51 | # Normalize 52 | data['NormalizedHashSpeed'] = data['AdjustedHashSpeed'] / reference_values 53 | 54 | # Store hash speed at the reference difficulty for sorting 55 | hash_speeds_at_difficulty[label] = data.loc[data['Difficulty'] == reference_difficulty, 'NormalizedHashSpeed'].values[0] 56 | 57 | # Sort labels 58 | sorted_labels = sorted(hash_speeds_at_difficulty.keys(), key=lambda x: hash_speeds_at_difficulty[x], reverse=True) 59 | 60 | # Plot the curves in the sorted order 61 | for label in sorted_labels: 62 | data = dfs[[f for f in csv_files if label in f][0]] 63 | 64 | fig.add_scatter(x=data['Difficulty'], y=data['NormalizedHashSpeed'], mode='lines', name=label) 65 | 66 | # Add text annotation 67 | if reference_difficulty in data['Difficulty'].values: 68 | fig.add_annotation( 69 | x=reference_difficulty, 70 | y=data.loc[data['Difficulty'] == reference_difficulty, 'NormalizedHashSpeed'].values[0], 71 | text=f"{label}:{round(data.loc[data['Difficulty'] == reference_difficulty, 'NormalizedHashSpeed'].values[0],2)}", 72 | showarrow=False, 73 | ) 74 | 75 | # Update layout 76 | fig.update_layout(title='Benchmark Results Normalized by Price and Reference Curve', 77 | xaxis_title='Difficulty', 78 | yaxis_title='Normalized HashSpeed') 79 | 80 | fig.show() -------------------------------------------------------------------------------- /benchmark/prices.txt: -------------------------------------------------------------------------------- 1 | 1660ti:0.6 2 | teslak80:0.5 3 | a2000:1.0 4 | a16:1.0 5 | 3060ti:0.52 6 | 3070ti:0.63 7 | 3080:0.88 8 | titanx:0.79 9 | rtx5000:1.5 10 | rtx1650:0.6 11 | rtx3080ti:1.8 12 | rtx4090:2.58 13 | rtx3090:1.46 14 | v100SXM2:1.88 15 | rtx2080ti:0.88 16 | a4000:0.92 17 | a5000:1.18 18 | rtx3060:0.6 19 | a100SXM4:7.98 20 | a40:2.68 21 | titanxp:0.49 22 | A100PCIE:3.28 23 | teslat4:0.78 24 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Save the current working directory 4 | original_dir=$(pwd) 5 | 6 | # Default values 7 | COMPUTE_TYPE="CUDA" 8 | 9 | # Read parameters 10 | while [[ "$#" -gt 0 ]]; do 11 | case $1 in 12 | -compute_type) COMPUTE_TYPE="$2"; shift ;; 13 | -cuda_arch) CUDA_ARCH="$2"; shift ;; 14 | *) echo "Unknown parameter passed: $1"; exit 1 ;; 15 | esac 16 | shift 17 | done 18 | 19 | 20 | # Create and navigate to the build directory 21 | mkdir -p build 22 | cd build || exit 23 | 24 | # Check if CUDA_ARCH is set, if not, perform a different action 25 | if [ -z "$CUDA_ARCH" ]; then 26 | # Run CMake and pass the arguments 27 | cmake .. 28 | 29 | make 30 | else 31 | cmake -DCUDA_ARCH=$CUDA_ARCH .. 32 | # Compile the project 33 | make 34 | fi 35 | 36 | # Return to the original working directory 37 | cd "$original_dir" || exit 38 | 39 | if [ -e miner.sh ]; then 40 | chmod +x miner.sh 41 | else 42 | echo "miner.sh does not exist." 43 | fi -------------------------------------------------------------------------------- /config.conf: -------------------------------------------------------------------------------- 1 | [Settings] 2 | difficulty = 1 3 | memory_cost = 1500 4 | cores = 1 5 | account = 0x24691e54afafe2416a8252097c9ca67557271475 6 | last_block_url = http://xenminer.mooo.com:4445/getblocks/lastblock 7 | gpu_mode = true 8 | 9 | # dev_fee_on: This setting allows the user to enable or disable the developer fee. 10 | # If set to true, a small percentage of the mining reward will be contributed to the developer 11 | # as a fee to support ongoing development, maintenance, and improvements of the project. 12 | # If set to false, no developer fee will be contributed. 13 | # Possible values: true or false. 14 | dev_fee_on = false 15 | -------------------------------------------------------------------------------- /dev/bench_mempool.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/hex" 7 | "fmt" 8 | "log" 9 | "time" 10 | 11 | "github.com/ethereum/go-ethereum/core/types" 12 | "github.com/ethereum/go-ethereum/rlp" 13 | "github.com/go-redis/redis/v8" 14 | ) 15 | 16 | var ctx = context.Background() 17 | 18 | func getRecoveredAddress(rawTx string) *string { 19 | rawTxBytes, err := hex.DecodeString(rawTx) 20 | if err != nil { 21 | log.Fatalf("Invalid transaction hex: %v", err) 22 | } 23 | 24 | tx := new(types.Transaction) 25 | 26 | r := bytes.NewReader(rawTxBytes) 27 | if err := rlp.Decode(r, tx); err != nil { 28 | log.Fatalf("Error decoding transaction: %v", err) 29 | } 30 | 31 | chainID := tx.ChainId() 32 | signer := types.NewEIP155Signer(chainID) 33 | senderAddr, err := types.Sender(signer, tx) 34 | if err != nil { 35 | log.Fatalf("Error extracting sender address from transaction: %v", err) 36 | } 37 | 38 | senderHex := senderAddr.Hex() 39 | return &senderHex 40 | } 41 | 42 | func writeAndProcessTransactions(rdb *redis.Client, key string, rawTxHex string, count int) { 43 | start := time.Now() 44 | 45 | rawTxBytes, err := hex.DecodeString(rawTxHex) // remove 0x prefix 46 | if err != nil { 47 | log.Fatalf("Invalid transaction hex: %v", err) 48 | } 49 | 50 | for i := 0; i < count; i++ { 51 | err := rdb.RPush(ctx, key, rawTxBytes).Err() // storing bytes 52 | if err != nil { 53 | log.Fatalf("Error writing to Redis: %v", err) 54 | } 55 | 56 | // Simulate processing by immediately popping and decoding 57 | result, err := rdb.LPop(ctx, key).Bytes() 58 | if err != nil { 59 | log.Fatalf("Error reading from Redis: %v", err) 60 | } 61 | 62 | rawTx := hex.EncodeToString(result) 63 | recoveredAddress := getRecoveredAddress(rawTx) 64 | if recoveredAddress == nil { 65 | log.Println("Error getting recovered address") 66 | continue 67 | } 68 | } 69 | 70 | end := time.Now() 71 | elapsed := end.Sub(start) 72 | 73 | fmt.Printf("Wrote and processed %d transactions in %v\n", count, elapsed) 74 | 75 | if count > 0 { 76 | avgTimePerTx := elapsed / time.Duration(count) 77 | txPerSecond := float64(count) / elapsed.Seconds() 78 | 79 | fmt.Printf("Average time per transaction: %v\n", avgTimePerTx) 80 | fmt.Printf("Transactions per second: %v\n", txPerSecond) 81 | } 82 | } 83 | 84 | func main() { 85 | rdb := redis.NewClient(&redis.Options{ 86 | Addr: "127.0.0.1:6379", 87 | DB: 0, // use default DB 88 | }) 89 | 90 | key := "transactions" // the key where transactions are stored in Redis 91 | rawTx := "f8ab80843b9aca00827b0c94999999cf1046e68e36e1aa2e0e07105eddd0000280b844a9059cbb000000000000000000000000f9b8dd0565b1fac5e9a142c3553f663e09444b9c000000000000000000000000000000000000000000000001236efcbcbb34000083030e2da0919b7300531a90a5e36a54d12e59cb33c2f77a3ea340f92bad063030c209bff1a059ca1d78f3ed0b017e07a6214263fb8a4433a7feff7ac4f0dbe771c1130beaf5" 92 | numberOfTransactions := 500000 // This is a large number, adjust accordingly 93 | 94 | // Simulate write and process transactions 95 | writeAndProcessTransactions(rdb, key, rawTx, numberOfTransactions) 96 | } 97 | -------------------------------------------------------------------------------- /dev/bench_mempool_multi.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/hex" 7 | "fmt" 8 | "log" 9 | "runtime" 10 | "sync" 11 | "time" 12 | 13 | "github.com/ethereum/go-ethereum/core/types" 14 | "github.com/ethereum/go-ethereum/rlp" 15 | "github.com/go-redis/redis/v8" 16 | ) 17 | 18 | var ctx = context.Background() 19 | 20 | func getRecoveredAddress(rawTx string) *string { 21 | rawTxBytes, err := hex.DecodeString(rawTx) 22 | if err != nil { 23 | log.Printf("Invalid transaction hex: %v", err) 24 | return nil 25 | } 26 | 27 | tx := new(types.Transaction) 28 | 29 | r := bytes.NewReader(rawTxBytes) 30 | if err := rlp.Decode(r, tx); err != nil { 31 | log.Printf("Error decoding transaction: %v", err) 32 | return nil 33 | } 34 | 35 | chainID := tx.ChainId() 36 | signer := types.NewEIP155Signer(chainID) 37 | senderAddr, err := types.Sender(signer, tx) 38 | if err != nil { 39 | log.Printf("Error extracting sender address from transaction: %v", err) 40 | return nil 41 | } 42 | 43 | senderHex := senderAddr.Hex() 44 | return &senderHex 45 | } 46 | 47 | func worker(wg *sync.WaitGroup, semaphore chan struct{}, rdb *redis.Client, key string, rawTxHex string) { 48 | defer wg.Done() 49 | 50 | rawTxBytes, err := hex.DecodeString(rawTxHex) // remove 0x prefix 51 | if err != nil { 52 | log.Printf("Invalid transaction hex: %v", err) 53 | return 54 | } 55 | 56 | err = rdb.RPush(ctx, key, rawTxBytes).Err() // storing bytes 57 | if err != nil { 58 | log.Printf("Error writing to Redis: %v", err) 59 | return 60 | } 61 | 62 | // Simulate processing by immediately popping and decoding 63 | result, err := rdb.LPop(ctx, key).Bytes() 64 | if err != nil { 65 | log.Printf("Error reading from Redis: %v", err) 66 | return 67 | } 68 | 69 | rawTx := hex.EncodeToString(result) 70 | recoveredAddress := getRecoveredAddress(rawTx) 71 | if recoveredAddress == nil { 72 | log.Println("Error getting recovered address") 73 | return 74 | } 75 | 76 | // Release the semaphore 77 | <-semaphore 78 | } 79 | 80 | func writeAndProcessTransactions(rdb *redis.Client, key string, rawTxHex string, count int) { 81 | start := time.Now() 82 | 83 | numCores := runtime.NumCPU() 84 | semaphore := make(chan struct{}, numCores) 85 | var wg sync.WaitGroup 86 | 87 | for i := 0; i < count; i++ { 88 | wg.Add(1) 89 | 90 | // Acquire the semaphore 91 | semaphore <- struct{}{} 92 | 93 | go worker(&wg, semaphore, rdb, key, rawTxHex) 94 | } 95 | 96 | // Wait for all goroutines to complete 97 | wg.Wait() 98 | 99 | end := time.Now() 100 | elapsed := end.Sub(start) 101 | 102 | fmt.Printf("Wrote and processed %d transactions in %v\n", count, elapsed) 103 | 104 | if count > 0 { 105 | avgTimePerTx := elapsed / time.Duration(count) 106 | txPerSecond := float64(count) / elapsed.Seconds() 107 | 108 | fmt.Printf("Average time per transaction: %v\n", avgTimePerTx) 109 | fmt.Printf("Transactions per second: %v\n", txPerSecond) 110 | } 111 | } 112 | 113 | func main() { 114 | numCores := runtime.NumCPU() 115 | rdb := redis.NewClient(&redis.Options{ 116 | Addr: "127.0.0.1:6379", 117 | DB: 0, // use default DB 118 | }) 119 | 120 | key := "transactions" // the key where transactions are stored in Redis 121 | rawTx := "f8ab80843b9aca00827b0c94999999cf1046e68e36e1aa2e0e07105eddd0000280b844a9059cbb000000000000000000000000f9b8dd0565b1fac5e9a142c3553f663e09444b9c000000000000000000000000000000000000000000000001236efcbcbb34000083030e2da0919b7300531a90a5e36a54d12e59cb33c2f77a3ea340f92bad063030c209bff1a059ca1d78f3ed0b017e07a6214263fb8a4433a7feff7ac4f0dbe771c1130beaf5" 122 | numberOfTransactions := 1000000 // This is a large number, adjust accordingly 123 | 124 | // Ensure maximum parallelism 125 | runtime.GOMAXPROCS(numCores*2) 126 | 127 | // Simulate write and process transactions 128 | writeAndProcessTransactions(rdb, key, rawTx, numberOfTransactions) 129 | } 130 | -------------------------------------------------------------------------------- /docs/Concurrency_in_world_state.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shanhaicoder/XENGPUMiner/e6a3f0ee8df765f03a64c497190e74f3cb8263da/docs/Concurrency_in_world_state.pdf -------------------------------------------------------------------------------- /docs/XENIUM_BLOCKCHAIN.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shanhaicoder/XENGPUMiner/e6a3f0ee8df765f03a64c497190e74f3cb8263da/docs/XENIUM_BLOCKCHAIN.pdf -------------------------------------------------------------------------------- /docs/xenblocks_whitepaper.v0.1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shanhaicoder/XENGPUMiner/e6a3f0ee8df765f03a64c497190e74f3cb8263da/docs/xenblocks_whitepaper.v0.1.pdf -------------------------------------------------------------------------------- /docs/xone_tokenomics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shanhaicoder/XENGPUMiner/e6a3f0ee8df765f03a64c497190e74f3cb8263da/docs/xone_tokenomics.pdf -------------------------------------------------------------------------------- /go/go.mod: -------------------------------------------------------------------------------- 1 | module example.com/xenminer 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /go/merkle_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | "fmt" 7 | "testing" 8 | ) 9 | 10 | func hashValue(value string) string { 11 | hash := sha256.Sum256([]byte(value)) 12 | return hex.EncodeToString(hash[:]) 13 | } 14 | 15 | func buildMerkleTree(elements []string, merkleTree map[string][2]string) string { 16 | if len(elements) == 1 { 17 | return elements[0] 18 | } 19 | 20 | var newElements []string 21 | for i := 0; i < len(elements); i += 2 { 22 | left := elements[i] 23 | var right string 24 | if i+1 < len(elements) { 25 | right = elements[i+1] 26 | } else { 27 | right = left 28 | } 29 | combined := left + right 30 | newHash := hashValue(combined) 31 | merkleTree[newHash] = [2]string{left, right} 32 | newElements = append(newElements, newHash) 33 | } 34 | return buildMerkleTree(newElements, merkleTree) 35 | } 36 | 37 | func TestHashValue(t *testing.T) { 38 | expected := sha256.Sum256([]byte("hello")) 39 | if hashValue("hello") != hex.EncodeToString(expected[:]) { 40 | t.Errorf("hashValue function not working properly") 41 | } 42 | } 43 | 44 | func TestBuildMerkleTree(t *testing.T) { 45 | elements := []string{"a", "b", "c", "d"} 46 | merkleTree := make(map[string][2]string) 47 | root := buildMerkleTree(elements, merkleTree) 48 | fmt.Printf("Merkle Root: %s\n", root) 49 | 50 | expectedRoot := hashValue(hashValue("a"+"b") + hashValue("c"+"d")) 51 | if root != expectedRoot { 52 | t.Errorf("buildMerkleTree function not working properly") 53 | } 54 | // Add more tests to validate the structure of merkleTree if necessary. 55 | } 56 | 57 | -------------------------------------------------------------------------------- /gpuMiner/LICENSE-argon2-gpu: -------------------------------------------------------------------------------- 1 | This software includes code derived from argon2-gpu https://gitlab.com/omos/argon2-gpu, 2 | which is licensed under the MIT License. Copyright [2019] [Ondrej Mosnáček]. 3 | 4 | MIT License 5 | 6 | Copyright (c) 2016 Ondrej Mosnáček 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in all 16 | copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/.gitattributes: -------------------------------------------------------------------------------- 1 | *.h linguist-language=C 2 | *.pro linguist-language=QMake 3 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | 30 | # Autotools + Libtool 31 | /aclocal.m4 32 | /config.status 33 | /config 34 | /install-sh 35 | **/Makefile 36 | **/Makefile.in 37 | /autom4te.cache/ 38 | /compile 39 | /config.guess 40 | /config.log 41 | /config.sub 42 | /configure 43 | /depcomp 44 | /libtool 45 | /ltmain.sh 46 | /m4/libtool.m4 47 | /m4/lt*.m4 48 | /missing 49 | /test-driver 50 | **/.deps/ 51 | **/.dirstamp 52 | **/.libs/ 53 | 54 | # Qt Creator 55 | **/*.user 56 | **/*.user.* 57 | **/build-*/ 58 | 59 | # KDE 60 | **/.directory 61 | 62 | # Vim 63 | *.swp 64 | 65 | # CMake 66 | CMakeFiles/ 67 | *.cmake 68 | CMakeCache.txt 69 | Makefile 70 | 71 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | 3 | dist: trusty 4 | sudo: false 5 | 6 | compiler: 7 | - clang 8 | - gcc 9 | 10 | env: 11 | - BUILD=cmake BUILD_TYPE=Debug 12 | - BUILD=cmake BUILD_TYPE=Release 13 | - BUILD=autotools 14 | 15 | script: | 16 | case $BUILD in 17 | cmake) 18 | cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE . && make && make test 19 | ;; 20 | autotools) 21 | autoreconf -i && ./configure && make && make check 22 | ;; 23 | esac 24 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.6) 2 | 3 | project(Argon2 C) 4 | set(ARGON2_VERSION 1.0) 5 | set(BINARY_INSTALL_DIR /usr/local/bin) 6 | set(LIBRARY_INSTALL_DIR /usr/local/lib) 7 | set(INCLUDE_INSTALL_DIR /usr/local/include) 8 | set(CMAKE_C_STANDARD 90) 9 | set(CMAKE_C_STANDARD_REQUIRED ON) 10 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) 11 | 12 | enable_testing() 13 | 14 | include(CheckCSourceCompiles) 15 | find_package(Threads REQUIRED) 16 | 17 | add_library(argon2-interface INTERFACE) 18 | target_include_directories(argon2-interface INTERFACE 19 | $ 20 | $ 21 | ) 22 | 23 | add_library(argon2-internal INTERFACE) 24 | target_include_directories(argon2-internal INTERFACE lib lib/blake2) 25 | target_link_libraries(argon2-internal INTERFACE argon2-interface) 26 | 27 | add_library(argon2 STATIC 28 | lib/argon2.c 29 | lib/core.c 30 | lib/encoding.c 31 | lib/genkat.c 32 | lib/impl-select.c 33 | lib/thread.c 34 | lib/blake2/blake2.c 35 | ) 36 | 37 | set_property(TARGET argon2 PROPERTY VERSION ${Upstream_VERSION}) 38 | set_property(TARGET argon2 PROPERTY SOVERSION 1) 39 | set_property(TARGET argon2 PROPERTY INTERFACE_ARGON2_MAJOR_VERSION 1) 40 | set_property(TARGET argon2 APPEND PROPERTY 41 | COMPATIBLE_INTERFACE_STRING ARGON2_MAJOR_VERSION 42 | ) 43 | 44 | if(CMAKE_SYSTEM_PROCESSOR STREQUAL x86_64) 45 | function(add_feature_impl FEATURE GCC_FLAG DEF) 46 | add_library(argon2-${FEATURE} STATIC 47 | arch/x86_64/lib/argon2-${FEATURE}.c 48 | ) 49 | target_link_libraries(argon2-${FEATURE} PRIVATE argon2-internal) 50 | set_target_properties(argon2-${FEATURE} 51 | PROPERTIES POSITION_INDEPENDENT_CODE True 52 | ) 53 | 54 | message("-- Detecting feature '${FEATURE}'...") 55 | file(READ arch/x86_64/src/test-feature-${FEATURE}.c SOURCE_CODE) 56 | 57 | # try without flag: 58 | check_c_source_compiles("${SOURCE_CODE}" FEATURE_${FEATURE}_NOFLAG) 59 | set(HAS_FEATURE ${FEATURE_${FEATURE}_NOFLAG}) 60 | if(NOT "${HAS_FEATURE}") 61 | # try with -m flag: 62 | set(CMAKE_REQUIRED_FLAGS ${GCC_FLAG}) 63 | check_c_source_compiles("${SOURCE_CODE}" FEATURE_${FEATURE}_FLAG) 64 | set(CMAKE_REQUIRED_FLAGS "") 65 | 66 | set(HAS_FEATURE ${FEATURE_${FEATURE}_FLAG}) 67 | if(${HAS_FEATURE}) 68 | target_compile_options(argon2-${FEATURE} PRIVATE ${GCC_FLAG}) 69 | endif() 70 | endif() 71 | 72 | if(${HAS_FEATURE}) 73 | message("-- Feature '${FEATURE}' detected!") 74 | target_compile_definitions(argon2-${FEATURE} PRIVATE ${DEF}) 75 | endif() 76 | target_link_libraries(argon2 PUBLIC argon2-${FEATURE}) 77 | endfunction() 78 | 79 | target_include_directories(argon2-internal INTERFACE arch/x86_64/lib) 80 | 81 | add_feature_impl(sse2 -msse2 HAVE_SSE2) 82 | add_feature_impl(ssse3 -mssse3 HAVE_SSSE3) 83 | add_feature_impl(xop -mxop HAVE_XOP) 84 | add_feature_impl(avx2 -mavx2 HAVE_AVX2) 85 | add_feature_impl(avx512f -mavx512f HAVE_AVX512F) 86 | 87 | target_sources(argon2 PRIVATE 88 | arch/x86_64/lib/argon2-arch.c 89 | arch/x86_64/lib/cpu-flags.c 90 | ) 91 | else() 92 | target_sources(argon2 PRIVATE 93 | arch/generic/lib/argon2-arch.c 94 | ) 95 | endif() 96 | 97 | install(TARGETS argon2 DESTINATION ${LIBRARY_INSTALL_DIR}) 98 | install(FILES 99 | include/argon2.h 100 | DESTINATION ${INCLUDE_INSTALL_DIR} 101 | ) 102 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Ondrej Mosnáček 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/Makefile.am: -------------------------------------------------------------------------------- 1 | ACLOCAL_AMFLAGS = -I m4 2 | 3 | include_HEADERS = include/argon2.h 4 | lib_LTLIBRARIES = libargon2.la 5 | noinst_LTLIBRARIES = 6 | 7 | bin_PROGRAMS = argon2 8 | noinst_PROGRAMS = argon2-genkat argon2-bench2 argon2-test 9 | 10 | TESTS = argon2-test 11 | 12 | AM_CPPFLAGS = \ 13 | -I$(srcdir)/include \ 14 | -I$(srcdir)/lib \ 15 | -I$(srcdir)/arch/@ARCH@/include \ 16 | -I$(srcdir)/arch/@ARCH@/lib 17 | 18 | libargon2_la_CFLAGS = @PTHREAD_CFLAGS@ 19 | libargon2_la_LIBADD = @PTHREAD_LIBS@ 20 | libargon2_la_SOURCES = \ 21 | lib/argon2.c \ 22 | lib/core.c \ 23 | lib/encoding.c \ 24 | lib/genkat.c \ 25 | lib/impl-select.c \ 26 | lib/thread.c \ 27 | lib/blake2/blake2.c \ 28 | lib/argon2-template-64.h \ 29 | lib/core.h \ 30 | lib/encoding.h \ 31 | lib/genkat.h \ 32 | lib/impl-select.h \ 33 | lib/thread.h \ 34 | lib/blake2/blake2.h \ 35 | lib/blake2/blake2-impl.h 36 | 37 | if ARCH_X86_64 38 | noinst_LTLIBRARIES += \ 39 | libargon2-sse2.la \ 40 | libargon2-ssse3.la \ 41 | libargon2-xop.la \ 42 | libargon2-avx2.la \ 43 | libargon2-avx512f.la 44 | libargon2_la_LIBADD += \ 45 | libargon2-sse2.la \ 46 | libargon2-ssse3.la \ 47 | libargon2-xop.la \ 48 | libargon2-avx2.la \ 49 | libargon2-avx512f.la 50 | 51 | libargon2_sse2_la_SOURCES = \ 52 | arch/@ARCH@/lib/argon2-sse2.c \ 53 | arch/@ARCH@/lib/argon2-sse2.h \ 54 | arch/@ARCH@/lib/argon2-template-128.h 55 | libargon2_sse2_la_CPPFLAGS = $(AM_CPPFLAGS) 56 | libargon2_sse2_la_CFLAGS = $(AM_CFLAGS) 57 | if HAVE_SSE2 58 | libargon2_sse2_la_CPPFLAGS += -DHAVE_SSE2 59 | libargon2_sse2_la_CFLAGS += -msse2 60 | endif # HAVE_SSE2 61 | 62 | libargon2_ssse3_la_SOURCES = \ 63 | arch/@ARCH@/lib/argon2-ssse3.c \ 64 | arch/@ARCH@/lib/argon2-ssse3.h \ 65 | arch/@ARCH@/lib/argon2-template-128.h 66 | libargon2_ssse3_la_CPPFLAGS = $(AM_CPPFLAGS) 67 | libargon2_ssse3_la_CFLAGS = $(AM_CFLAGS) 68 | if HAVE_SSSE3 69 | libargon2_ssse3_la_CPPFLAGS += -DHAVE_SSSE3 70 | libargon2_ssse3_la_CFLAGS += -mssse3 71 | endif # HAVE_SSSE3 72 | 73 | libargon2_xop_la_SOURCES = \ 74 | arch/@ARCH@/lib/argon2-xop.c \ 75 | arch/@ARCH@/lib/argon2-xop.h \ 76 | arch/@ARCH@/lib/argon2-template-128.h 77 | libargon2_xop_la_CPPFLAGS = $(AM_CPPFLAGS) 78 | libargon2_xop_la_CFLAGS = $(AM_CFLAGS) 79 | if HAVE_XOP 80 | libargon2_xop_la_CPPFLAGS += -DHAVE_XOP 81 | libargon2_xop_la_CFLAGS += -mxop 82 | endif # HAVE_XOP 83 | 84 | libargon2_avx2_la_SOURCES = \ 85 | arch/@ARCH@/lib/argon2-avx2.c \ 86 | arch/@ARCH@/lib/argon2-avx2.h 87 | libargon2_avx2_la_CPPFLAGS = $(AM_CPPFLAGS) 88 | libargon2_avx2_la_CFLAGS = $(AM_CFLAGS) 89 | if HAVE_AVX2 90 | libargon2_avx2_la_CPPFLAGS += -DHAVE_AVX2 91 | libargon2_avx2_la_CFLAGS += -mavx2 92 | endif # HAVE_AVX2 93 | 94 | libargon2_avx512f_la_SOURCES = \ 95 | arch/@ARCH@/lib/argon2-avx512f.c \ 96 | arch/@ARCH@/lib/argon2-avx512f.h 97 | libargon2_avx512f_la_CPPFLAGS = $(AM_CPPFLAGS) 98 | libargon2_avx512f_la_CFLAGS = $(AM_CFLAGS) 99 | if HAVE_AVX512F 100 | libargon2_avx512f_la_CPPFLAGS += -DHAVE_AVX512F 101 | libargon2_avx512f_la_CFLAGS += -mavx512f 102 | endif # HAVE_AVX512F 103 | 104 | libargon2_la_SOURCES += \ 105 | arch/@ARCH@/lib/argon2-arch.c \ 106 | arch/@ARCH@/lib/cpu-flags.c \ 107 | arch/@ARCH@/lib/cpu-flags.h 108 | endif # ARCH_X86_64 109 | 110 | if ARCH_GENERIC 111 | libargon2_la_SOURCES += \ 112 | arch/@ARCH@/lib/argon2-arch.c 113 | endif # ARCH_GENERIC 114 | 115 | argon2_LDADD = libargon2.la 116 | argon2_SOURCES = src/run.c lib/core.h 117 | 118 | argon2_genkat_LDADD = libargon2.la 119 | argon2_genkat_SOURCES = src/genkat.c 120 | 121 | argon2_bench2_LDADD = libargon2.la -lrt 122 | argon2_bench2_SOURCES = src/bench2.c src/timing.h 123 | 124 | argon2_test_LDADD = libargon2.la 125 | argon2_test_SOURCES = tests/test.c 126 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/README.md: -------------------------------------------------------------------------------- 1 | # Argon2 [![Build Status](https://travis-ci.org/WOnder93/argon2.svg?branch=master)](https://travis-ci.org/WOnder93/argon2) 2 | A multi-arch library implementing the Argon2 password hashing algorithm. 3 | 4 | This project is based on the [original source code](https://github.com/P-H-C/phc-winner-argon2) by the Argon2 authors. The goal of this project is to provide efficient Argon2 implementations for various HW architectures (x86, SSE, ARM, PowerPC, ...). 5 | 6 | For the x86_64 architecture, the library implements a simple CPU dispatch which automatically selects the best implementation based on CPU flags and quick benchmarks. 7 | 8 | # Building 9 | ## Using GNU autotools 10 | 11 | To prepare the build environment, run: 12 | ```bash 13 | autoreconf -i 14 | ./configure 15 | ``` 16 | 17 | After that, just run `make` to build the library. 18 | 19 | ### Running tests 20 | After configuring the build environment, run `make check` to run the tests. 21 | 22 | ### Architecture options 23 | You can specify the target architecture by passing the `--host=...` flag to `./configure`. 24 | 25 | Supported architectures: 26 | * `x86_64` – 64-bit x86 architecture 27 | * `generic` – use generic C impementation 28 | 29 | ## Using CMake 30 | 31 | To prepare the build environment, run: 32 | ```bash 33 | cmake -DCMAKE_BUILD_TYPE=Release . 34 | ``` 35 | 36 | Then you can run `make` to build the library. 37 | 38 | ## Using QMake/Qt Creator 39 | A [QMake](http://doc.qt.io/qt-4.8/qmake-manual.html) project is also available in the `qmake` directory. You can open it in the [Qt Creator IDE](http://wiki.qt.io/Category:Tools::QtCreator) or build it from terminal: 40 | ```bash 41 | cd qmake 42 | # see table below for the list of possible ARCH and CONFIG values 43 | qmake ARCH=... CONFIG+=... 44 | make 45 | ``` 46 | 47 | ### Architecture options 48 | For QMake builds you can configure support for different architectures. Use the `ARCH` variable to choose the architecture and the `CONFIG` variable to set additional options. 49 | 50 | Supported architectures: 51 | * `x86_64` – 64-bit x86 architecture 52 | * QMake config flags: 53 | * `USE_SSE2` – use SSE2 instructions 54 | * `USE_SSSE3` – use SSSE3 instructions 55 | * `USE_XOP` – use XOP instructions 56 | * `USE_AVX2` – use AVX2 instructions 57 | * `USE_AVX512F` – use AVX-512F instructions 58 | * `generic` – use generic C impementation 59 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/generic/lib/argon2-arch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "impl-select.h" 6 | 7 | #define rotr64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) 8 | 9 | #include "argon2-template-64.h" 10 | 11 | void fill_segment_default(const argon2_instance_t *instance, 12 | argon2_position_t position) 13 | { 14 | fill_segment_64(instance, position); 15 | } 16 | 17 | void argon2_get_impl_list(argon2_impl_list *list) 18 | { 19 | list->count = 0; 20 | } 21 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-arch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "impl-select.h" 6 | 7 | #include "cpu-flags.h" 8 | #include "argon2-sse2.h" 9 | #include "argon2-ssse3.h" 10 | #include "argon2-xop.h" 11 | #include "argon2-avx2.h" 12 | #include "argon2-avx512f.h" 13 | 14 | /* NOTE: there is no portable intrinsic for 64-bit rotate, but any 15 | * sane compiler should be able to compile this into a ROR instruction: */ 16 | #define rotr64(x, n) ((x) >> (n)) | ((x) << (64 - (n))) 17 | 18 | #include "argon2-template-64.h" 19 | 20 | void fill_segment_default(const argon2_instance_t *instance, 21 | argon2_position_t position) 22 | { 23 | fill_segment_64(instance, position); 24 | } 25 | 26 | void argon2_get_impl_list(argon2_impl_list *list) 27 | { 28 | static const argon2_impl IMPLS[] = { 29 | { "x86_64", NULL, fill_segment_default }, 30 | { "SSE2", check_sse2, fill_segment_sse2 }, 31 | { "SSSE3", check_ssse3, fill_segment_ssse3 }, 32 | { "XOP", check_xop, fill_segment_xop }, 33 | { "AVX2", check_avx2, fill_segment_avx2 }, 34 | { "AVX-512F", check_avx512f, fill_segment_avx512f }, 35 | }; 36 | 37 | cpu_flags_get(); 38 | 39 | list->count = sizeof(IMPLS) / sizeof(IMPLS[0]); 40 | list->entries = IMPLS; 41 | } 42 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-avx2.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_AVX2_H 2 | #define ARGON2_AVX2_H 3 | 4 | #include "core.h" 5 | 6 | void fill_segment_avx2(const argon2_instance_t *instance, 7 | argon2_position_t position); 8 | 9 | int check_avx2(void); 10 | 11 | #endif // ARGON2_AVX2_H 12 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-avx512f.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_AVX512F_H 2 | #define ARGON2_AVX512F_H 3 | 4 | #include "core.h" 5 | 6 | void fill_segment_avx512f(const argon2_instance_t *instance, 7 | argon2_position_t position); 8 | 9 | int check_avx512f(void); 10 | 11 | #endif // ARGON2_AVX512F_H 12 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-sse2.c: -------------------------------------------------------------------------------- 1 | #include "argon2-sse2.h" 2 | 3 | #ifdef HAVE_SSE2 4 | #include 5 | 6 | #include "cpu-flags.h" 7 | 8 | #define ror64_16(x) \ 9 | _mm_shufflehi_epi16( \ 10 | _mm_shufflelo_epi16((x), _MM_SHUFFLE(0, 3, 2, 1)), \ 11 | _MM_SHUFFLE(0, 3, 2, 1)) 12 | #define ror64_24(x) \ 13 | _mm_xor_si128(_mm_srli_epi64((x), 24), _mm_slli_epi64((x), 40)) 14 | #define ror64_32(x) _mm_shuffle_epi32((x), _MM_SHUFFLE(2, 3, 0, 1)) 15 | #define ror64_63(x) \ 16 | _mm_xor_si128(_mm_srli_epi64((x), 63), _mm_add_epi64((x), (x))) 17 | 18 | static __m128i f(__m128i x, __m128i y) 19 | { 20 | __m128i z = _mm_mul_epu32(x, y); 21 | return _mm_add_epi64(_mm_add_epi64(x, y), _mm_add_epi64(z, z)); 22 | } 23 | 24 | #define G1(A0, B0, C0, D0, A1, B1, C1, D1) \ 25 | do { \ 26 | A0 = f(A0, B0); \ 27 | A1 = f(A1, B1); \ 28 | \ 29 | D0 = _mm_xor_si128(D0, A0); \ 30 | D1 = _mm_xor_si128(D1, A1); \ 31 | \ 32 | D0 = ror64_32(D0); \ 33 | D1 = ror64_32(D1); \ 34 | \ 35 | C0 = f(C0, D0); \ 36 | C1 = f(C1, D1); \ 37 | \ 38 | B0 = _mm_xor_si128(B0, C0); \ 39 | B1 = _mm_xor_si128(B1, C1); \ 40 | \ 41 | B0 = ror64_24(B0); \ 42 | B1 = ror64_24(B1); \ 43 | } while ((void)0, 0) 44 | 45 | #define G2(A0, B0, C0, D0, A1, B1, C1, D1) \ 46 | do { \ 47 | A0 = f(A0, B0); \ 48 | A1 = f(A1, B1); \ 49 | \ 50 | D0 = _mm_xor_si128(D0, A0); \ 51 | D1 = _mm_xor_si128(D1, A1); \ 52 | \ 53 | D0 = ror64_16(D0); \ 54 | D1 = ror64_16(D1); \ 55 | \ 56 | C0 = f(C0, D0); \ 57 | C1 = f(C1, D1); \ 58 | \ 59 | B0 = _mm_xor_si128(B0, C0); \ 60 | B1 = _mm_xor_si128(B1, C1); \ 61 | \ 62 | B0 = ror64_63(B0); \ 63 | B1 = ror64_63(B1); \ 64 | } while ((void)0, 0) 65 | 66 | #define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 67 | do { \ 68 | __m128i t0 = D0; \ 69 | __m128i t1 = B0; \ 70 | D0 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t0, t0)); \ 71 | D1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(D1, D1)); \ 72 | B0 = _mm_unpackhi_epi64(B0, _mm_unpacklo_epi64(B1, B1)); \ 73 | B1 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(t1, t1)); \ 74 | } while ((void)0, 0) 75 | 76 | #define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 77 | do { \ 78 | __m128i t0 = B0; \ 79 | __m128i t1 = D0; \ 80 | B0 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(B0, B0)); \ 81 | B1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(B1, B1)); \ 82 | D0 = _mm_unpackhi_epi64(D0, _mm_unpacklo_epi64(D1, D1)); \ 83 | D1 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t1, t1)); \ 84 | } while ((void)0, 0) 85 | 86 | #define BLAKE2_ROUND(A0, A1, B0, B1, C0, C1, D0, D1) \ 87 | do { \ 88 | G1(A0, B0, C0, D0, A1, B1, C1, D1); \ 89 | G2(A0, B0, C0, D0, A1, B1, C1, D1); \ 90 | \ 91 | DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 92 | \ 93 | G1(A0, B0, C1, D0, A1, B1, C0, D1); \ 94 | G2(A0, B0, C1, D0, A1, B1, C0, D1); \ 95 | \ 96 | UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 97 | } while ((void)0, 0) 98 | 99 | #include "argon2-template-128.h" 100 | 101 | void fill_segment_sse2(const argon2_instance_t *instance, 102 | argon2_position_t position) 103 | { 104 | fill_segment_128(instance, position); 105 | } 106 | 107 | int check_sse2(void) 108 | { 109 | return cpu_flags_have_sse2(); 110 | } 111 | 112 | #else 113 | 114 | void fill_segment_sse2(const argon2_instance_t *instance, 115 | argon2_position_t position) 116 | { 117 | } 118 | 119 | int check_sse2(void) 120 | { 121 | return 0; 122 | } 123 | 124 | #endif 125 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-sse2.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_SSE2_H 2 | #define ARGON2_SSE2_H 3 | 4 | #include "core.h" 5 | 6 | void fill_segment_sse2(const argon2_instance_t *instance, 7 | argon2_position_t position); 8 | 9 | int check_sse2(void); 10 | 11 | #endif // ARGON2_SSE2_H 12 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-ssse3.c: -------------------------------------------------------------------------------- 1 | #include "argon2-ssse3.h" 2 | 3 | #ifdef HAVE_SSSE3 4 | #include 5 | 6 | #include 7 | 8 | #include "cpu-flags.h" 9 | 10 | #define r16 (_mm_setr_epi8( \ 11 | 2, 3, 4, 5, 6, 7, 0, 1, \ 12 | 10, 11, 12, 13, 14, 15, 8, 9)) 13 | 14 | #define r24 (_mm_setr_epi8( \ 15 | 3, 4, 5, 6, 7, 0, 1, 2, \ 16 | 11, 12, 13, 14, 15, 8, 9, 10)) 17 | 18 | #define ror64_16(x) _mm_shuffle_epi8((x), r16) 19 | #define ror64_24(x) _mm_shuffle_epi8((x), r24) 20 | #define ror64_32(x) _mm_shuffle_epi32((x), _MM_SHUFFLE(2, 3, 0, 1)) 21 | #define ror64_63(x) \ 22 | _mm_xor_si128(_mm_srli_epi64((x), 63), _mm_add_epi64((x), (x))) 23 | 24 | static __m128i f(__m128i x, __m128i y) 25 | { 26 | __m128i z = _mm_mul_epu32(x, y); 27 | return _mm_add_epi64(_mm_add_epi64(x, y), _mm_add_epi64(z, z)); 28 | } 29 | 30 | #define G1(A0, B0, C0, D0, A1, B1, C1, D1) \ 31 | do { \ 32 | A0 = f(A0, B0); \ 33 | A1 = f(A1, B1); \ 34 | \ 35 | D0 = _mm_xor_si128(D0, A0); \ 36 | D1 = _mm_xor_si128(D1, A1); \ 37 | \ 38 | D0 = ror64_32(D0); \ 39 | D1 = ror64_32(D1); \ 40 | \ 41 | C0 = f(C0, D0); \ 42 | C1 = f(C1, D1); \ 43 | \ 44 | B0 = _mm_xor_si128(B0, C0); \ 45 | B1 = _mm_xor_si128(B1, C1); \ 46 | \ 47 | B0 = ror64_24(B0); \ 48 | B1 = ror64_24(B1); \ 49 | } while ((void)0, 0) 50 | 51 | #define G2(A0, B0, C0, D0, A1, B1, C1, D1) \ 52 | do { \ 53 | A0 = f(A0, B0); \ 54 | A1 = f(A1, B1); \ 55 | \ 56 | D0 = _mm_xor_si128(D0, A0); \ 57 | D1 = _mm_xor_si128(D1, A1); \ 58 | \ 59 | D0 = ror64_16(D0); \ 60 | D1 = ror64_16(D1); \ 61 | \ 62 | C0 = f(C0, D0); \ 63 | C1 = f(C1, D1); \ 64 | \ 65 | B0 = _mm_xor_si128(B0, C0); \ 66 | B1 = _mm_xor_si128(B1, C1); \ 67 | \ 68 | B0 = ror64_63(B0); \ 69 | B1 = ror64_63(B1); \ 70 | } while ((void)0, 0) 71 | 72 | #define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 73 | do { \ 74 | __m128i t0 = _mm_alignr_epi8(B1, B0, 8); \ 75 | __m128i t1 = _mm_alignr_epi8(B0, B1, 8); \ 76 | B0 = t0; \ 77 | B1 = t1; \ 78 | \ 79 | t0 = _mm_alignr_epi8(D1, D0, 8); \ 80 | t1 = _mm_alignr_epi8(D0, D1, 8); \ 81 | D0 = t1; \ 82 | D1 = t0; \ 83 | } while ((void)0, 0) 84 | 85 | #define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 86 | do { \ 87 | __m128i t0 = _mm_alignr_epi8(B0, B1, 8); \ 88 | __m128i t1 = _mm_alignr_epi8(B1, B0, 8); \ 89 | B0 = t0; \ 90 | B1 = t1; \ 91 | \ 92 | t0 = _mm_alignr_epi8(D0, D1, 8); \ 93 | t1 = _mm_alignr_epi8(D1, D0, 8); \ 94 | D0 = t1; \ 95 | D1 = t0; \ 96 | } while ((void)0, 0) 97 | 98 | #define BLAKE2_ROUND(A0, A1, B0, B1, C0, C1, D0, D1) \ 99 | do { \ 100 | G1(A0, B0, C0, D0, A1, B1, C1, D1); \ 101 | G2(A0, B0, C0, D0, A1, B1, C1, D1); \ 102 | \ 103 | DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 104 | \ 105 | G1(A0, B0, C1, D0, A1, B1, C0, D1); \ 106 | G2(A0, B0, C1, D0, A1, B1, C0, D1); \ 107 | \ 108 | UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 109 | } while ((void)0, 0) 110 | 111 | #include "argon2-template-128.h" 112 | 113 | void fill_segment_ssse3(const argon2_instance_t *instance, 114 | argon2_position_t position) 115 | { 116 | fill_segment_128(instance, position); 117 | } 118 | 119 | int check_ssse3(void) 120 | { 121 | return cpu_flags_have_ssse3(); 122 | } 123 | 124 | #else 125 | 126 | void fill_segment_ssse3(const argon2_instance_t *instance, 127 | argon2_position_t position) 128 | { 129 | } 130 | 131 | int check_ssse3(void) 132 | { 133 | return 0; 134 | } 135 | 136 | #endif 137 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-ssse3.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_SSSE3_H 2 | #define ARGON2_SSSE3_H 3 | 4 | #include "core.h" 5 | 6 | void fill_segment_ssse3(const argon2_instance_t *instance, 7 | argon2_position_t position); 8 | 9 | int check_ssse3(void); 10 | 11 | #endif // ARGON2_SSSE3_H 12 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-xop.c: -------------------------------------------------------------------------------- 1 | #include "argon2-xop.h" 2 | 3 | #ifdef HAVE_XOP 4 | #include 5 | 6 | #include 7 | 8 | #include "cpu-flags.h" 9 | 10 | #define ror64(x, c) _mm_roti_epi64((x), -(c)) 11 | 12 | static __m128i f(__m128i x, __m128i y) 13 | { 14 | __m128i z = _mm_mul_epu32(x, y); 15 | return _mm_add_epi64(_mm_add_epi64(x, y), _mm_add_epi64(z, z)); 16 | } 17 | 18 | #define G1(A0, B0, C0, D0, A1, B1, C1, D1) \ 19 | do { \ 20 | A0 = f(A0, B0); \ 21 | A1 = f(A1, B1); \ 22 | \ 23 | D0 = _mm_xor_si128(D0, A0); \ 24 | D1 = _mm_xor_si128(D1, A1); \ 25 | \ 26 | D0 = ror64(D0, 32); \ 27 | D1 = ror64(D1, 32); \ 28 | \ 29 | C0 = f(C0, D0); \ 30 | C1 = f(C1, D1); \ 31 | \ 32 | B0 = _mm_xor_si128(B0, C0); \ 33 | B1 = _mm_xor_si128(B1, C1); \ 34 | \ 35 | B0 = ror64(B0, 24); \ 36 | B1 = ror64(B1, 24); \ 37 | } while ((void)0, 0) 38 | 39 | #define G2(A0, B0, C0, D0, A1, B1, C1, D1) \ 40 | do { \ 41 | A0 = f(A0, B0); \ 42 | A1 = f(A1, B1); \ 43 | \ 44 | D0 = _mm_xor_si128(D0, A0); \ 45 | D1 = _mm_xor_si128(D1, A1); \ 46 | \ 47 | D0 = ror64(D0, 16); \ 48 | D1 = ror64(D1, 16); \ 49 | \ 50 | C0 = f(C0, D0); \ 51 | C1 = f(C1, D1); \ 52 | \ 53 | B0 = _mm_xor_si128(B0, C0); \ 54 | B1 = _mm_xor_si128(B1, C1); \ 55 | \ 56 | B0 = ror64(B0, 63); \ 57 | B1 = ror64(B1, 63); \ 58 | } while ((void)0, 0) 59 | 60 | #define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 61 | do { \ 62 | __m128i t0 = _mm_alignr_epi8(B1, B0, 8); \ 63 | __m128i t1 = _mm_alignr_epi8(B0, B1, 8); \ 64 | B0 = t0; \ 65 | B1 = t1; \ 66 | \ 67 | t0 = _mm_alignr_epi8(D1, D0, 8); \ 68 | t1 = _mm_alignr_epi8(D0, D1, 8); \ 69 | D0 = t1; \ 70 | D1 = t0; \ 71 | } while ((void)0, 0) 72 | 73 | #define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ 74 | do { \ 75 | __m128i t0 = _mm_alignr_epi8(B0, B1, 8); \ 76 | __m128i t1 = _mm_alignr_epi8(B1, B0, 8); \ 77 | B0 = t0; \ 78 | B1 = t1; \ 79 | \ 80 | t0 = _mm_alignr_epi8(D0, D1, 8); \ 81 | t1 = _mm_alignr_epi8(D1, D0, 8); \ 82 | D0 = t1; \ 83 | D1 = t0; \ 84 | } while ((void)0, 0) 85 | 86 | #define BLAKE2_ROUND(A0, A1, B0, B1, C0, C1, D0, D1) \ 87 | do { \ 88 | G1(A0, B0, C0, D0, A1, B1, C1, D1); \ 89 | G2(A0, B0, C0, D0, A1, B1, C1, D1); \ 90 | \ 91 | DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 92 | \ 93 | G1(A0, B0, C1, D0, A1, B1, C0, D1); \ 94 | G2(A0, B0, C1, D0, A1, B1, C0, D1); \ 95 | \ 96 | UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ 97 | } while ((void)0, 0) 98 | 99 | #include "argon2-template-128.h" 100 | 101 | void fill_segment_xop(const argon2_instance_t *instance, 102 | argon2_position_t position) 103 | { 104 | fill_segment_128(instance, position); 105 | } 106 | 107 | int check_xop(void) 108 | { 109 | return cpu_flags_have_xop(); 110 | } 111 | 112 | #else 113 | 114 | void fill_segment_xop(const argon2_instance_t *instance, 115 | argon2_position_t position) 116 | { 117 | } 118 | 119 | int check_xop(void) 120 | { 121 | return 0; 122 | } 123 | 124 | #endif 125 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/argon2-xop.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_XOP_H 2 | #define ARGON2_XOP_H 3 | 4 | #include "core.h" 5 | 6 | void fill_segment_xop(const argon2_instance_t *instance, 7 | argon2_position_t position); 8 | 9 | int check_xop(void); 10 | 11 | #endif // ARGON2_XOP_H 12 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/cpu-flags.c: -------------------------------------------------------------------------------- 1 | #include "cpu-flags.h" 2 | 3 | #include 4 | 5 | enum { 6 | X86_64_FEATURE_SSE2 = (1 << 0), 7 | X86_64_FEATURE_SSSE3 = (1 << 1), 8 | X86_64_FEATURE_XOP = (1 << 2), 9 | X86_64_FEATURE_AVX2 = (1 << 3), 10 | X86_64_FEATURE_AVX512F = (1 << 4), 11 | }; 12 | 13 | static unsigned int cpu_flags; 14 | 15 | static unsigned int get_cpuid(int ext, unsigned int level, unsigned int *ebx, 16 | unsigned int *ecx, unsigned int *edx) 17 | { 18 | unsigned int eax; 19 | __cpuid(ext ? (0x80000000 | level) : level, 20 | eax, *ebx, *ecx, *edx); 21 | return eax; 22 | } 23 | 24 | static unsigned int get_cpuid_count(int ext, unsigned int level, 25 | unsigned int count, unsigned int *ebx, 26 | unsigned int *ecx, unsigned int *edx) 27 | { 28 | unsigned int eax; 29 | __cpuid_count(ext ? (0x80000000 | level) : level, 30 | count, eax, *ebx, *ecx, *edx); 31 | return 1; 32 | } 33 | 34 | void cpu_flags_get(void) 35 | { 36 | unsigned int ebx, ecx, edx; 37 | unsigned int level, level_ext; 38 | 39 | cpu_flags = 0; 40 | level = get_cpuid(0, 0, &ebx, &ecx, &edx); 41 | level_ext = get_cpuid(1, 0, &ebx, &ecx, &edx); 42 | 43 | if (level >= 1 && get_cpuid(0, 1, &ebx, &ecx, &edx)) { 44 | if (edx & (1 << 26)) { 45 | cpu_flags |= X86_64_FEATURE_SSE2; 46 | } 47 | if (ecx & (1 << 9)) { 48 | cpu_flags |= X86_64_FEATURE_SSSE3; 49 | } 50 | } 51 | if (level >= 7 && get_cpuid_count(0, 7, 0, &ebx, &ecx, &edx)) { 52 | if (ebx & (1 << 5)) { 53 | cpu_flags |= X86_64_FEATURE_AVX2; 54 | } 55 | if (ebx & (1 << 16)) { 56 | cpu_flags |= X86_64_FEATURE_AVX512F; 57 | } 58 | } 59 | if (level_ext >= 1 && get_cpuid(1, 1, &ebx, &ecx, &edx)) { 60 | if (ecx & (1 << 11)) { 61 | cpu_flags |= X86_64_FEATURE_XOP; 62 | } 63 | } 64 | /* FIXME: check also OS support! */ 65 | } 66 | 67 | int cpu_flags_have_sse2(void) 68 | { 69 | return cpu_flags & X86_64_FEATURE_SSE2; 70 | } 71 | 72 | int cpu_flags_have_ssse3(void) 73 | { 74 | return cpu_flags & X86_64_FEATURE_SSSE3; 75 | } 76 | 77 | int cpu_flags_have_xop(void) 78 | { 79 | return cpu_flags & X86_64_FEATURE_XOP; 80 | } 81 | 82 | int cpu_flags_have_avx2(void) 83 | { 84 | return cpu_flags & X86_64_FEATURE_AVX2; 85 | } 86 | 87 | int cpu_flags_have_avx512f(void) 88 | { 89 | return cpu_flags & X86_64_FEATURE_AVX512F; 90 | } 91 | 92 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/lib/cpu-flags.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_CPU_FLAGS_H 2 | #define ARGON2_CPU_FLAGS_H 3 | 4 | void cpu_flags_get(void); 5 | 6 | int cpu_flags_have_sse2(void); 7 | int cpu_flags_have_ssse3(void); 8 | int cpu_flags_have_xop(void); 9 | int cpu_flags_have_avx2(void); 10 | int cpu_flags_have_avx512f(void); 11 | 12 | #endif // ARGON2_CPU_FLAGS_H 13 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/src/test-feature-avx2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void function_avx2(__m256i *dst, const __m256i *a, const __m256i *b) 4 | { 5 | *dst = _mm256_xor_si256(*a, *b); 6 | } 7 | 8 | int main(void) { return 0; } 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/src/test-feature-avx512f.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void function_avx512f(__m512i *dst, const __m512i *a) 4 | { 5 | *dst = _mm512_ror_epi64(*a, 57); 6 | } 7 | 8 | int main(void) { return 0; } 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/src/test-feature-sse2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void function_sse2(__m128i *dst, const __m128i *a, const __m128i *b) 4 | { 5 | *dst = _mm_xor_si128(*a, *b); 6 | } 7 | 8 | int main(void) { return 0; } 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/src/test-feature-ssse3.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void function_ssse3(__m128i *dst, const __m128i *a, const __m128i *b) 4 | { 5 | *dst = _mm_shuffle_epi8(*a, *b); 6 | } 7 | 8 | int main(void) { return 0; } 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/arch/x86_64/src/test-feature-xop.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void function_xop(__m128i *dst, const __m128i *a, int b) 4 | { 5 | *dst = _mm_roti_epi64(*a, b); 6 | } 7 | 8 | int main(void) { return 0; } 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/configure.ac: -------------------------------------------------------------------------------- 1 | dnl --------------------------------------------------------------------- 2 | dnl Copyright (C) 2015, Ondrej Mosnacek 3 | dnl 4 | dnl This program is free software: you can redistribute it and/or 5 | dnl modify it under the terms of the GNU General Public License 6 | dnl as published by the Free Software Foundation: either version 2 7 | dnl of the License, or (at your option) any later version. 8 | dnl 9 | dnl This program is distributed in the hope that it will be useful, 10 | dnl but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | dnl GNU General Public License for more details. 13 | dnl 14 | dnl You should have received a copy of the GNU General Public License 15 | dnl along with this program. If not, see . 16 | dnl --------------------------------------------------------------------- 17 | 18 | AC_CONFIG_MACRO_DIR([m4]) 19 | 20 | AC_INIT([argon2], [0.1], []) 21 | LT_INIT 22 | AM_INIT_AUTOMAKE([foreign subdir-objects]) 23 | AM_SILENT_RULES([yes]) 24 | 25 | AC_PROG_CC 26 | AC_PROG_CC_C89 27 | AM_PROG_AS 28 | AX_PTHREAD 29 | 30 | AC_CANONICAL_HOST 31 | 32 | AS_CASE([$host_cpu], 33 | dnl [i?86], [ARCH=i386], 34 | [x86_64], [ARCH=x86_64], 35 | [ARCH=generic 36 | AC_MSG_WARN("No code for architecture $host_cpu; using generic implementation")] 37 | ) 38 | AC_SUBST([ARCH]) 39 | 40 | AM_CONDITIONAL([ARCH_X86_64], [test "$ARCH" = 'x86_64']) 41 | AM_CONDITIONAL([ARCH_GENERIC], [test "$ARCH" = 'generic']) 42 | 43 | # AX_CHECK_COMPILER_FEATURE(NAME, FLAG, TEST_SOURCE) 44 | # -------------------------- 45 | AC_DEFUN([AX_CHECK_COMPILER_FEATURE], [{ 46 | AX_CHECK_COMPILE_FLAG([-m$2], [HAVE_FLAG=1], [HAVE_FLAG=0]) 47 | HAVE_FEATURE=0 48 | AS_IF([test "$HAVE_FLAG" = '1'], [{ 49 | AC_MSG_CHECKING("whether C compiler supports $1 with -m$2...") 50 | 51 | CFLAGS_BACKUP="$CFLAGS" 52 | CFLAGS="-m$2" 53 | 54 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([$3])], [HAVE_FEATURE=1]) 55 | 56 | CFLAGS="$CFLAGS_BACKUP" 57 | AS_IF([test "$HAVE_FEATURE" = '1'], [RESULT='yes'], [RESULT='no']) 58 | AC_MSG_RESULT([$RESULT]) 59 | 60 | }]) 61 | HAVE_$1=HAVE_FEATURE 62 | AM_CONDITIONAL([HAVE_$1], [test "$HAVE_FEATURE" = '1']) 63 | }]) 64 | 65 | AX_CHECK_COMPILER_FEATURE([SSE2], [sse2], [[ 66 | #include 67 | 68 | void function_sse2(__m128i *dst, const __m128i *a, const __m128i *b) 69 | { 70 | *dst = _mm_xor_si128(*a, *b); 71 | } 72 | ]]) 73 | AX_CHECK_COMPILER_FEATURE([SSSE3], [ssse3], [[ 74 | #include 75 | 76 | void function_ssse3(__m128i *dst, const __m128i *a, const __m128i *b) 77 | { 78 | *dst = _mm_shuffle_epi8(*a, *b); 79 | } 80 | ]]) 81 | AX_CHECK_COMPILER_FEATURE([XOP], [xop], [[ 82 | #include 83 | 84 | void function_xop(__m128i *dst, const __m128i *a, int b) 85 | { 86 | *dst = _mm_roti_epi64(*a, b); 87 | } 88 | ]]) 89 | AX_CHECK_COMPILER_FEATURE([AVX2], [avx2], [[ 90 | #include 91 | 92 | void function_avx2(__m256i *dst, const __m256i *a, const __m256i *b) 93 | { 94 | *dst = _mm256_xor_si256(*a, *b); 95 | } 96 | ]]) 97 | AX_CHECK_COMPILER_FEATURE([AVX512F], [avx512f], [[ 98 | #include 99 | 100 | void function_avx512f(__m512i *dst, const __m512i *a) 101 | { 102 | *dst = _mm512_ror_epi64(*a, 57); 103 | } 104 | ]]) 105 | 106 | AC_CONFIG_FILES([Makefile]) 107 | 108 | AC_OUTPUT 109 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/blake2/blake2-impl.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_BLAKE2_IMPL_H 2 | #define ARGON2_BLAKE2_IMPL_H 3 | 4 | #include 5 | 6 | /* Argon2 Team - Begin Code */ 7 | /* 8 | Not an exhaustive list, but should cover the majority of modern platforms 9 | Additionally, the code will always be correct---this is only a performance 10 | tweak. 11 | */ 12 | #if (defined(__BYTE_ORDER__) && \ 13 | (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ 14 | defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || defined(__MIPSEL__) || \ 15 | defined(__AARCH64EL__) || defined(__amd64__) || defined(__i386__) || \ 16 | defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || \ 17 | defined(_M_ARM) 18 | #define NATIVE_LITTLE_ENDIAN 19 | #endif 20 | /* Argon2 Team - End Code */ 21 | 22 | static inline uint32_t load32(const void *src) { 23 | #if defined(NATIVE_LITTLE_ENDIAN) 24 | return *(const uint32_t *)src; 25 | #else 26 | const uint8_t *p = (const uint8_t *)src; 27 | uint32_t w = *p++; 28 | w |= (uint32_t)(*p++) << 8; 29 | w |= (uint32_t)(*p++) << 16; 30 | w |= (uint32_t)(*p++) << 24; 31 | return w; 32 | #endif 33 | } 34 | 35 | static inline uint64_t load64(const void *src) { 36 | #if defined(NATIVE_LITTLE_ENDIAN) 37 | return *(const uint64_t *)src; 38 | #else 39 | const uint8_t *p = (const uint8_t *)src; 40 | uint64_t w = *p++; 41 | w |= (uint64_t)(*p++) << 8; 42 | w |= (uint64_t)(*p++) << 16; 43 | w |= (uint64_t)(*p++) << 24; 44 | w |= (uint64_t)(*p++) << 32; 45 | w |= (uint64_t)(*p++) << 40; 46 | w |= (uint64_t)(*p++) << 48; 47 | w |= (uint64_t)(*p++) << 56; 48 | return w; 49 | #endif 50 | } 51 | 52 | static inline void store32(void *dst, uint32_t w) { 53 | #if defined(NATIVE_LITTLE_ENDIAN) 54 | *(uint32_t *)dst = w; 55 | #else 56 | uint8_t *p = (uint8_t *)dst; 57 | *p++ = (uint8_t)w; 58 | w >>= 8; 59 | *p++ = (uint8_t)w; 60 | w >>= 8; 61 | *p++ = (uint8_t)w; 62 | w >>= 8; 63 | *p++ = (uint8_t)w; 64 | #endif 65 | } 66 | 67 | static inline void store64(void *dst, uint64_t w) { 68 | #if defined(NATIVE_LITTLE_ENDIAN) 69 | *(uint64_t *)dst = w; 70 | #else 71 | uint8_t *p = (uint8_t *)dst; 72 | *p++ = (uint8_t)w; 73 | w >>= 8; 74 | *p++ = (uint8_t)w; 75 | w >>= 8; 76 | *p++ = (uint8_t)w; 77 | w >>= 8; 78 | *p++ = (uint8_t)w; 79 | w >>= 8; 80 | *p++ = (uint8_t)w; 81 | w >>= 8; 82 | *p++ = (uint8_t)w; 83 | w >>= 8; 84 | *p++ = (uint8_t)w; 85 | w >>= 8; 86 | *p++ = (uint8_t)w; 87 | #endif 88 | } 89 | 90 | #endif // ARGON2_BLAKE2_IMPL_H 91 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/blake2/blake2.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_BLAKE2_H 2 | #define ARGON2_BLAKE2_H 3 | 4 | #include 5 | #include 6 | 7 | enum blake2b_constant { 8 | BLAKE2B_BLOCKBYTES = 128, 9 | BLAKE2B_OUTBYTES = 64, 10 | BLAKE2B_KEYBYTES = 64, 11 | BLAKE2B_SALTBYTES = 16, 12 | BLAKE2B_PERSONALBYTES = 16 13 | }; 14 | 15 | typedef struct __blake2b_state { 16 | uint64_t h[8]; 17 | uint64_t t[2]; 18 | uint8_t buf[BLAKE2B_BLOCKBYTES]; 19 | size_t buflen; 20 | } blake2b_state; 21 | 22 | /* Streaming API */ 23 | void blake2b_init(blake2b_state *S, size_t outlen); 24 | void blake2b_update(blake2b_state *S, const void *in, size_t inlen); 25 | void blake2b_final(blake2b_state *S, void *out, size_t outlen); 26 | 27 | void blake2b_long(void *out, size_t outlen, const void *in, size_t inlen); 28 | 29 | #endif // ARGON2_BLAKE2_H 30 | 31 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/encoding.h: -------------------------------------------------------------------------------- 1 | #ifndef ENCODING_H 2 | #define ENCODING_H 3 | #include "argon2.h" 4 | 5 | #define ARGON2_MAX_DECODED_LANES UINT32_C(255) 6 | #define ARGON2_MIN_DECODED_SALT_LEN UINT32_C(8) 7 | #define ARGON2_MIN_DECODED_OUT_LEN UINT32_C(12) 8 | 9 | /* 10 | * encode an Argon2 hash string into the provided buffer. 'dst_len' 11 | * contains the size, in characters, of the 'dst' buffer; if 'dst_len' 12 | * is less than the number of required characters (including the 13 | * terminating 0), then this function returns ARGON2_ENCODING_ERROR. 14 | * 15 | * on success, ARGON2_OK is returned. 16 | */ 17 | int encode_string(char *dst, size_t dst_len, argon2_context *ctx, 18 | argon2_type type); 19 | 20 | /* 21 | * Decodes an Argon2 hash string into the provided structure 'ctx'. 22 | * The only fields that must be set prior to this call are ctx.saltlen and 23 | * ctx.outlen (which must be the maximal salt and out length values that are 24 | * allowed), ctx.salt and ctx.out (which must be buffers of the specified 25 | * length), and ctx.pwd and ctx.pwdlen which must hold a valid password. 26 | * 27 | * Invalid input string causes an error. On success, the ctx is valid and all 28 | * fields have been initialized. 29 | * 30 | * Returned value is ARGON2_OK on success, other ARGON2_ codes on error. 31 | */ 32 | int decode_string(argon2_context *ctx, const char *str, argon2_type type); 33 | 34 | /* Returns the length of the encoded byte stream with length len */ 35 | size_t b64len(uint32_t len); 36 | 37 | /* Returns the length of the encoded number num */ 38 | size_t numlen(uint32_t num); 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/genkat.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Argon2 source code package 3 | * 4 | * Written by Daniel Dinu and Dmitry Khovratovich, 2015 5 | * 6 | * This work is licensed under a Creative Commons CC0 1.0 License/Waiver. 7 | * 8 | * You should have received a copy of the CC0 Public Domain Dedication along 9 | * with 10 | * this software. If not, see 11 | * . 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | #include "genkat.h" 18 | 19 | void initial_kat(const uint8_t *blockhash, const argon2_context *context, 20 | argon2_type type) { 21 | unsigned i; 22 | 23 | if (blockhash != NULL && context != NULL) { 24 | printf("=======================================\n"); 25 | 26 | printf("%s version number %d\n", argon2_type2string(type, 1), 27 | context->version); 28 | 29 | printf("=======================================\n"); 30 | 31 | 32 | printf("Memory: %u KiB, Iterations: %u, Parallelism: %u lanes, Tag " 33 | "length: %u bytes\n", 34 | context->m_cost, context->t_cost, context->lanes, 35 | context->outlen); 36 | 37 | printf("Password[%u]: ", context->pwdlen); 38 | 39 | if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) { 40 | printf("CLEARED\n"); 41 | } else { 42 | for (i = 0; i < context->pwdlen; ++i) { 43 | printf("%2.2x ", ((unsigned char *)context->pwd)[i]); 44 | } 45 | 46 | printf("\n"); 47 | } 48 | 49 | printf("Salt[%u]: ", context->saltlen); 50 | 51 | for (i = 0; i < context->saltlen; ++i) { 52 | printf("%2.2x ", ((unsigned char *)context->salt)[i]); 53 | } 54 | 55 | printf("\n"); 56 | 57 | printf("Secret[%u]: ", context->secretlen); 58 | 59 | if (context->flags & ARGON2_FLAG_CLEAR_SECRET) { 60 | printf("CLEARED\n"); 61 | } else { 62 | for (i = 0; i < context->secretlen; ++i) { 63 | printf("%2.2x ", ((unsigned char *)context->secret)[i]); 64 | } 65 | 66 | printf("\n"); 67 | } 68 | 69 | printf("Associated data[%u]: ", context->adlen); 70 | 71 | for (i = 0; i < context->adlen; ++i) { 72 | printf("%2.2x ", ((unsigned char *)context->ad)[i]); 73 | } 74 | 75 | printf("\n"); 76 | 77 | printf("Pre-hashing digest: "); 78 | 79 | for (i = 0; i < ARGON2_PREHASH_DIGEST_LENGTH; ++i) { 80 | printf("%2.2x ", ((unsigned char *)blockhash)[i]); 81 | } 82 | 83 | printf("\n"); 84 | } 85 | } 86 | 87 | void print_tag(const void *out, uint32_t outlen) { 88 | unsigned i; 89 | if (out != NULL) { 90 | printf("Tag: "); 91 | 92 | for (i = 0; i < outlen; ++i) { 93 | printf("%2.2x ", ((uint8_t *)out)[i]); 94 | } 95 | 96 | printf("\n"); 97 | } 98 | } 99 | 100 | void internal_kat(const argon2_instance_t *instance, uint32_t pass) { 101 | 102 | if (instance != NULL) { 103 | uint32_t i, j; 104 | printf("\n After pass %u:\n", pass); 105 | 106 | for (i = 0; i < instance->memory_blocks; ++i) { 107 | uint32_t how_many_words = 108 | (instance->memory_blocks > ARGON2_QWORDS_IN_BLOCK) 109 | ? 1 110 | : ARGON2_QWORDS_IN_BLOCK; 111 | 112 | for (j = 0; j < how_many_words; ++j) 113 | printf("Block %.4u [%3u]: %016" PRIx64 "\n", i, j, 114 | instance->memory[i].v[j]); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/genkat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Argon2 source code package 3 | * 4 | * Written by Daniel Dinu and Dmitry Khovratovich, 2015 5 | * 6 | * This work is licensed under a Creative Commons CC0 1.0 License/Waiver. 7 | * 8 | * You should have received a copy of the CC0 Public Domain Dedication along 9 | * with 10 | * this software. If not, see 11 | * . 12 | */ 13 | 14 | #ifndef ARGON2_KAT_H 15 | #define ARGON2_KAT_H 16 | 17 | #include "core.h" 18 | 19 | /* 20 | * Initial KAT function that prints the inputs to the file 21 | * @param blockhash Array that contains pre-hashing digest 22 | * @param context Holds inputs 23 | * @param type Argon2 type 24 | * @pre blockhash must point to INPUT_INITIAL_HASH_LENGTH bytes 25 | * @pre context member pointers must point to allocated memory of size according 26 | * to the length values 27 | */ 28 | void initial_kat(const uint8_t *blockhash, const argon2_context *context, 29 | argon2_type type); 30 | 31 | /* 32 | * Function that prints the output tag 33 | * @param out output array pointer 34 | * @param outlen digest length 35 | * @pre out must point to @a outlen bytes 36 | **/ 37 | void print_tag(const void *out, uint32_t outlen); 38 | 39 | /* 40 | * Function that prints the internal state at given moment 41 | * @param instance pointer to the current instance 42 | * @param pass current pass number 43 | * @pre instance must have necessary memory allocated 44 | **/ 45 | void internal_kat(const argon2_instance_t *instance, uint32_t pass); 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/impl-select.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "impl-select.h" 5 | 6 | #include "argon2.h" 7 | 8 | #define log_maybe(file, ...) \ 9 | do { \ 10 | if (file) { \ 11 | fprintf(file, __VA_ARGS__); \ 12 | } \ 13 | } while(0) 14 | 15 | #define BENCH_SAMPLES 512 16 | #define BENCH_MEM_BLOCKS 512 17 | 18 | static argon2_impl selected_argon_impl = { 19 | "(default)", NULL, fill_segment_default 20 | }; 21 | 22 | /* the benchmark routine is not thread-safe, so we can use a global var here: */ 23 | static block memory[BENCH_MEM_BLOCKS]; 24 | 25 | static uint64_t benchmark_impl(const argon2_impl *impl) { 26 | clock_t time; 27 | unsigned int i; 28 | uint64_t bench; 29 | argon2_instance_t instance; 30 | argon2_position_t pos; 31 | 32 | memset(memory, 0, sizeof(memory)); 33 | 34 | instance.version = ARGON2_VERSION_NUMBER; 35 | instance.memory = memory; 36 | instance.passes = 1; 37 | instance.memory_blocks = BENCH_MEM_BLOCKS; 38 | instance.segment_length = BENCH_MEM_BLOCKS / ARGON2_SYNC_POINTS; 39 | instance.lane_length = instance.segment_length * ARGON2_SYNC_POINTS; 40 | instance.lanes = 1; 41 | instance.threads = 1; 42 | instance.type = Argon2_i; 43 | 44 | pos.lane = 0; 45 | pos.pass = 0; 46 | pos.slice = 0; 47 | pos.index = 0; 48 | 49 | /* warm-up cache: */ 50 | impl->fill_segment(&instance, pos); 51 | 52 | /* OK, now measure: */ 53 | bench = 0; 54 | time = clock(); 55 | for (i = 0; i < BENCH_SAMPLES; i++) { 56 | impl->fill_segment(&instance, pos); 57 | } 58 | time = clock() - time; 59 | bench = (uint64_t)time; 60 | return bench; 61 | } 62 | 63 | static void select_impl(FILE *out, const char *prefix) 64 | { 65 | argon2_impl_list impls; 66 | unsigned int i; 67 | const argon2_impl *best_impl = NULL; 68 | uint64_t best_bench = UINT_MAX; 69 | 70 | log_maybe(out, "%sSelecting best fill_segment implementation...\n", prefix); 71 | 72 | argon2_get_impl_list(&impls); 73 | 74 | for (i = 0; i < impls.count; i++) { 75 | const argon2_impl *impl = &impls.entries[i]; 76 | uint64_t bench; 77 | 78 | log_maybe(out, "%s%s: Checking availability... ", prefix, impl->name); 79 | if (impl->check != NULL && !impl->check()) { 80 | log_maybe(out, "FAILED!\n"); 81 | continue; 82 | } 83 | log_maybe(out, "OK!\n"); 84 | 85 | log_maybe(out, "%s%s: Benchmarking...\n", prefix, impl->name); 86 | bench = benchmark_impl(impl); 87 | log_maybe(out, "%s%s: Benchmark result: %llu\n", prefix, impl->name, 88 | (unsigned long long)bench); 89 | 90 | if (bench < best_bench) { 91 | best_bench = bench; 92 | best_impl = impl; 93 | } 94 | } 95 | 96 | if (best_impl != NULL) { 97 | log_maybe(out, 98 | "%sBest implementation: '%s' (bench %llu)\n", prefix, 99 | best_impl->name, (unsigned long long)best_bench); 100 | 101 | selected_argon_impl = *best_impl; 102 | } else { 103 | log_maybe(out, 104 | "%sNo optimized implementation available, using default!\n", 105 | prefix); 106 | } 107 | } 108 | 109 | void fill_segment(const argon2_instance_t *instance, argon2_position_t position) 110 | { 111 | selected_argon_impl.fill_segment(instance, position); 112 | } 113 | 114 | void argon2_select_impl(FILE *out, const char *prefix) 115 | { 116 | if (prefix == NULL) { 117 | prefix = ""; 118 | } 119 | select_impl(out, prefix); 120 | } 121 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/impl-select.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_IMPL_SELECT_H 2 | #define ARGON2_IMPL_SELECT_H 3 | 4 | #include "core.h" 5 | 6 | typedef struct Argon2_impl { 7 | const char *name; 8 | int (*check)(void); 9 | void (*fill_segment)(const argon2_instance_t *instance, 10 | argon2_position_t position); 11 | } argon2_impl; 12 | 13 | typedef struct Argon2_impl_list { 14 | const argon2_impl *entries; 15 | size_t count; 16 | } argon2_impl_list; 17 | 18 | void argon2_get_impl_list(argon2_impl_list *list); 19 | void fill_segment_default(const argon2_instance_t *instance, 20 | argon2_position_t position); 21 | 22 | #endif // ARGON2_IMPL_SELECT_H 23 | 24 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/thread.c: -------------------------------------------------------------------------------- 1 | #include "thread.h" 2 | #if defined(_WIN32) 3 | #include 4 | #endif 5 | 6 | int argon2_thread_create(argon2_thread_handle_t *handle, 7 | argon2_thread_func_t func, void *args) { 8 | if (NULL == handle || func == NULL) { 9 | return -1; 10 | } 11 | #if defined(_WIN32) 12 | *handle = _beginthreadex(NULL, 0, func, args, 0, NULL); 13 | return *handle != 0 ? 0 : -1; 14 | #else 15 | return pthread_create(handle, NULL, func, args); 16 | #endif 17 | } 18 | 19 | int argon2_thread_join(argon2_thread_handle_t handle) { 20 | #if defined(_WIN32) 21 | if (WaitForSingleObject((HANDLE)handle, INFINITE) == WAIT_OBJECT_0) { 22 | return CloseHandle((HANDLE)handle) != 0 ? 0 : -1; 23 | } 24 | return -1; 25 | #else 26 | return pthread_join(handle, NULL); 27 | #endif 28 | } 29 | 30 | void argon2_thread_exit(void) { 31 | #if defined(_WIN32) 32 | _endthreadex(0); 33 | #else 34 | pthread_exit(NULL); 35 | #endif 36 | } 37 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/lib/thread.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_THREAD_H 2 | #define ARGON2_THREAD_H 3 | /* 4 | Here we implement an abstraction layer for the simpĺe requirements 5 | of the Argon2 code. We only require 3 primitives---thread creation, 6 | joining, and termination---so full emulation of the pthreads API 7 | is unwarranted. Currently we wrap pthreads and Win32 threads. 8 | 9 | The API defines 2 types: the function pointer type, 10 | argon2_thread_func_t, 11 | and the type of the thread handle---argon2_thread_handle_t. 12 | */ 13 | #if defined(_WIN32) 14 | #include 15 | #include 16 | typedef unsigned(__stdcall *argon2_thread_func_t)(void *); 17 | typedef uintptr_t argon2_thread_handle_t; 18 | #else 19 | #include 20 | typedef void *(*argon2_thread_func_t)(void *); 21 | typedef pthread_t argon2_thread_handle_t; 22 | #endif 23 | 24 | /* Creates a thread 25 | * @param handle pointer to a thread handle, which is the output of this 26 | * function. Must not be NULL. 27 | * @param func A function pointer for the thread's entry point. Must not be 28 | * NULL. 29 | * @param args Pointer that is passed as an argument to @func. May be NULL. 30 | * @return 0 if @handle and @func are valid pointers and a thread is successfuly 31 | * created. 32 | */ 33 | int argon2_thread_create(argon2_thread_handle_t *handle, 34 | argon2_thread_func_t func, void *args); 35 | 36 | /* Waits for a thread to terminate 37 | * @param handle Handle to a thread created with argon2_thread_create. 38 | * @return 0 if @handle is a valid handle, and joining completed successfully. 39 | */ 40 | int argon2_thread_join(argon2_thread_handle_t handle); 41 | 42 | /* Terminate the current thread. Must be run inside a thread created by 43 | * argon2_thread_create. 44 | */ 45 | void argon2_thread_exit(void); 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/m4/ax_check_compile_flag.m4: -------------------------------------------------------------------------------- 1 | # =========================================================================== 2 | # http://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html 3 | # =========================================================================== 4 | # 5 | # SYNOPSIS 6 | # 7 | # AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) 8 | # 9 | # DESCRIPTION 10 | # 11 | # Check whether the given FLAG works with the current language's compiler 12 | # or gives an error. (Warnings, however, are ignored) 13 | # 14 | # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on 15 | # success/failure. 16 | # 17 | # If EXTRA-FLAGS is defined, it is added to the current language's default 18 | # flags (e.g. CFLAGS) when the check is done. The check is thus made with 19 | # the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to 20 | # force the compiler to issue an error when a bad flag is given. 21 | # 22 | # INPUT gives an alternative input source to AC_COMPILE_IFELSE. 23 | # 24 | # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this 25 | # macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG. 26 | # 27 | # LICENSE 28 | # 29 | # Copyright (c) 2008 Guido U. Draheim 30 | # Copyright (c) 2011 Maarten Bosmans 31 | # 32 | # This program is free software: you can redistribute it and/or modify it 33 | # under the terms of the GNU General Public License as published by the 34 | # Free Software Foundation, either version 3 of the License, or (at your 35 | # option) any later version. 36 | # 37 | # This program is distributed in the hope that it will be useful, but 38 | # WITHOUT ANY WARRANTY; without even the implied warranty of 39 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 40 | # Public License for more details. 41 | # 42 | # You should have received a copy of the GNU General Public License along 43 | # with this program. If not, see . 44 | # 45 | # As a special exception, the respective Autoconf Macro's copyright owner 46 | # gives unlimited permission to copy, distribute and modify the configure 47 | # scripts that are the output of Autoconf when processing the Macro. You 48 | # need not follow the terms of the GNU General Public License when using 49 | # or distributing such scripts, even though portions of the text of the 50 | # Macro appear in them. The GNU General Public License (GPL) does govern 51 | # all other use of the material that constitutes the Autoconf Macro. 52 | # 53 | # This special exception to the GPL applies to versions of the Autoconf 54 | # Macro released by the Autoconf Archive. When you make and distribute a 55 | # modified version of the Autoconf Macro, you may extend this special 56 | # exception to the GPL to apply to your modified version as well. 57 | 58 | #serial 4 59 | 60 | AC_DEFUN([AX_CHECK_COMPILE_FLAG], 61 | [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF 62 | AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl 63 | AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [ 64 | ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS 65 | _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1" 66 | AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], 67 | [AS_VAR_SET(CACHEVAR,[yes])], 68 | [AS_VAR_SET(CACHEVAR,[no])]) 69 | _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags]) 70 | AS_VAR_IF(CACHEVAR,yes, 71 | [m4_default([$2], :)], 72 | [m4_default([$3], :)]) 73 | AS_VAR_POPDEF([CACHEVAR])dnl 74 | ])dnl AX_CHECK_COMPILE_FLAGS 75 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/arch.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = subdirs 2 | 3 | SUBDIRS += $$ARCH 4 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/generic/generic.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = subdirs 2 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/libargon2-avx2/libargon2-avx2.pro: -------------------------------------------------------------------------------- 1 | QT -= core gui 2 | 3 | TARGET = argon2-avx2 4 | TEMPLATE = lib 5 | CONFIG += staticlib 6 | 7 | ARGON2_ROOT = ../../../.. 8 | 9 | INCLUDEPATH += \ 10 | $$ARGON2_ROOT/include \ 11 | $$ARGON2_ROOT/lib \ 12 | $$ARGON2_ROOT/arch/$$ARCH/lib 13 | 14 | USE_AVX2 { 15 | DEFINES += HAVE_AVX2 16 | QMAKE_CFLAGS += -mavx2 17 | } 18 | 19 | SOURCES += \ 20 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-avx2.c 21 | 22 | HEADERS += \ 23 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-avx2.h 24 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/libargon2-avx512f/libargon2-avx512f.pro: -------------------------------------------------------------------------------- 1 | QT -= core gui 2 | 3 | TARGET = argon2-avx512f 4 | TEMPLATE = lib 5 | CONFIG += staticlib 6 | 7 | ARGON2_ROOT = ../../../.. 8 | 9 | INCLUDEPATH += \ 10 | $$ARGON2_ROOT/include \ 11 | $$ARGON2_ROOT/lib \ 12 | $$ARGON2_ROOT/arch/$$ARCH/lib 13 | 14 | USE_AVX512F { 15 | DEFINES += HAVE_AVX512F 16 | QMAKE_CFLAGS += -mavx512f 17 | } 18 | 19 | SOURCES += \ 20 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-avx512f.c 21 | 22 | HEADERS += \ 23 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-avx512f.h 24 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/libargon2-sse2/libargon2-sse2.pro: -------------------------------------------------------------------------------- 1 | QT -= core gui 2 | 3 | TARGET = argon2-sse2 4 | TEMPLATE = lib 5 | CONFIG += staticlib 6 | 7 | ARGON2_ROOT = ../../../.. 8 | 9 | INCLUDEPATH += \ 10 | $$ARGON2_ROOT/include \ 11 | $$ARGON2_ROOT/lib \ 12 | $$ARGON2_ROOT/arch/$$ARCH/lib 13 | 14 | USE_SSE2 | USE_SSSE3 | USE_XOP | USE_AVX2 { 15 | DEFINES += HAVE_SSE2 16 | QMAKE_CFLAGS += -msse2 17 | } 18 | 19 | SOURCES += \ 20 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-sse2.c 21 | 22 | HEADERS += \ 23 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-sse2.h \ 24 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-template-128.h 25 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/libargon2-ssse3/libargon2-ssse3.pro: -------------------------------------------------------------------------------- 1 | QT -= core gui 2 | 3 | TARGET = argon2-ssse3 4 | TEMPLATE = lib 5 | CONFIG += staticlib 6 | 7 | ARGON2_ROOT = ../../../.. 8 | 9 | INCLUDEPATH += \ 10 | $$ARGON2_ROOT/include \ 11 | $$ARGON2_ROOT/lib \ 12 | $$ARGON2_ROOT/arch/$$ARCH/lib 13 | 14 | USE_SSSE3 | USE_XOP | USE_AVX2 { 15 | DEFINES += HAVE_SSSE3 16 | QMAKE_CFLAGS += -mssse3 17 | } 18 | 19 | SOURCES += \ 20 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-ssse3.c 21 | 22 | HEADERS += \ 23 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-ssse3.h \ 24 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-template-128.h 25 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/libargon2-xop/libargon2-xop.pro: -------------------------------------------------------------------------------- 1 | QT -= core gui 2 | 3 | TARGET = argon2-xop 4 | TEMPLATE = lib 5 | CONFIG += staticlib 6 | 7 | ARGON2_ROOT = ../../../.. 8 | 9 | INCLUDEPATH += \ 10 | $$ARGON2_ROOT/include \ 11 | $$ARGON2_ROOT/lib \ 12 | $$ARGON2_ROOT/arch/$$ARCH/lib 13 | 14 | USE_XOP { 15 | DEFINES += HAVE_XOP 16 | QMAKE_CFLAGS += -mxop 17 | } 18 | 19 | SOURCES += \ 20 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-xop.c 21 | 22 | HEADERS += \ 23 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-xop.h \ 24 | $$ARGON2_ROOT/arch/x86_64/lib/argon2-template-128.h 25 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/arch/x86_64/x86_64.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = subdirs 2 | 3 | SUBDIRS += \ 4 | libargon2-sse2 \ 5 | libargon2-ssse3 \ 6 | libargon2-xop \ 7 | libargon2-avx2 \ 8 | libargon2-avx512f 9 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/argon2-bench2/argon2-bench2.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = app 2 | CONFIG += console c++11 3 | CONFIG -= app_bundle 4 | CONFIG -= qt 5 | 6 | ARGON2_ROOT = ../.. 7 | 8 | SOURCES += \ 9 | $$ARGON2_ROOT/src/bench2.c 10 | 11 | HEADERS += \ 12 | $$ARGON2_ROOT/src/timing.h 13 | 14 | win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../libargon2/release/ -largon2 15 | else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../libargon2/debug/ -largon2 16 | else:unix: LIBS += -L$$OUT_PWD/../libargon2/ -largon2 17 | 18 | INCLUDEPATH += $$PWD/../../include 19 | DEPENDPATH += $$PWD/../../include 20 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/argon2-genkat/argon2-genkat.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = app 2 | CONFIG += console c++11 3 | CONFIG -= app_bundle 4 | CONFIG -= qt 5 | 6 | ARGON2_ROOT = ../.. 7 | 8 | SOURCES += \ 9 | $$ARGON2_ROOT/src/genkat.c 10 | 11 | win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../libargon2/release/ -largon2 12 | else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../libargon2/debug/ -largon2 13 | else:unix: LIBS += -L$$OUT_PWD/../libargon2/ -largon2 14 | 15 | INCLUDEPATH += $$PWD/../../include 16 | DEPENDPATH += $$PWD/../../include 17 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/argon2-test/argon2-test.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = app 2 | CONFIG += console c++11 3 | CONFIG -= app_bundle 4 | CONFIG -= qt 5 | 6 | ARGON2_ROOT = ../.. 7 | 8 | SOURCES += \ 9 | $$ARGON2_ROOT/tests/test.c 10 | 11 | win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../libargon2/release/ -largon2 12 | else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../libargon2/debug/ -largon2 13 | else:unix: LIBS += -L$$OUT_PWD/../libargon2/ -largon2 14 | 15 | INCLUDEPATH += $$PWD/../../include 16 | DEPENDPATH += $$PWD/../../include 17 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/argon2.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = subdirs 2 | 3 | SUBDIRS += \ 4 | arch \ 5 | libargon2 \ 6 | argon2 \ 7 | argon2-genkat \ 8 | argon2-bench2 \ 9 | argon2-test 10 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/qmake/argon2/argon2.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = app 2 | CONFIG += console c++11 3 | CONFIG -= app_bundle 4 | CONFIG -= qt 5 | 6 | ARGON2_ROOT = ../.. 7 | 8 | SOURCES += \ 9 | $$ARGON2_ROOT/src/run.c 10 | 11 | win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../libargon2/release/ -largon2 12 | else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../libargon2/debug/ -largon2 13 | else:unix: LIBS += -L$$OUT_PWD/../libargon2/ -largon2 14 | 15 | INCLUDEPATH += $$PWD/../../include $$PWD/../../lib 16 | DEPENDPATH += $$PWD/../../include $$PWD/../../lib 17 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/scripts/metacentrum/start-all-benchmarks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | dirname="$(dirname "$0")" 4 | 5 | cd "$dirname" || exit 1 6 | 7 | ./start-benchmark.sh luna 8 | ./start-benchmark.sh lex '' '' '' '' '' backfill 9 | ./start-benchmark.sh mandos 10 | ./start-benchmark.sh zubat 11 | PBS_SERVER=wagap.cerit-sc.cz \ 12 | ./start-benchmark.sh zapat '' '' '' '' '' default@wagap.cerit-sc.cz 13 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/scripts/metacentrum/start-benchmark.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | machine="$1" 4 | max_t_cost="$2" 5 | max_m_cost="$3" 6 | max_lanes="$4" 7 | branch="$5" 8 | duration="$6" 9 | queue="$7" 10 | run_tests="$8" 11 | 12 | if [ -z "$machine" ]; then 13 | echo "ERROR: Machine must be specified!" 1>&2 14 | exit 1 15 | fi 16 | 17 | if [ -z "$max_t_cost" ]; then 18 | max_t_cost=16 19 | fi 20 | 21 | if [ -z "$max_m_cost" ]; then 22 | max_m_cost=$((8 * 1024 * 1024)) 23 | fi 24 | 25 | if [ -z "$max_lanes" ]; then 26 | max_lanes=16 27 | fi 28 | 29 | if [ -z "$branch" ]; then 30 | branch='master' 31 | fi 32 | 33 | if [ -z "$duration" ]; then 34 | duration=2h 35 | fi 36 | 37 | REPO_URL='https://github.com/WOnder93/argon2.git' 38 | 39 | dest_dir="$(pwd)" 40 | 41 | task_file="$(mktemp)" 42 | 43 | cat >$task_file <"$dest_dir/\$PBS_JOBID/benchmark-$machine-$branch.csv" 71 | EOF 72 | 73 | qsub "$task_file" 74 | 75 | rm -f "$task_file" 76 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/scripts/run-benchmark.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | max_t_cost="$1" 4 | max_m_cost="$2" 5 | max_lanes="$3" 6 | 7 | if [ -z "$max_t_cost" ]; then 8 | echo "ERROR: Maximum time cost must be specified!" 1>&2 9 | exit 1 10 | fi 11 | 12 | if [ -z "$max_m_cost" ]; then 13 | echo "ERROR: Maximum memory cost must be specified!" 1>&2 14 | exit 1 15 | fi 16 | 17 | if [ -z "$max_lanes" ]; then 18 | echo "ERROR: Maximum number of lanes must be specified!" 1>&2 19 | exit 1 20 | fi 21 | 22 | dirname="$(dirname "$0")" 23 | 24 | cd "$dirname/.." || exit 1 25 | 26 | echo "t_cost,m_cost,lanes,ms_i,ms_d,ms_id" 27 | stdbuf -oL ./argon2-bench2 $max_t_cost $max_m_cost $max_lanes | 28 | stdbuf -oL tail -n +2 | 29 | while read line; do 30 | print_comma=0 31 | for x in $line; do 32 | if [ $print_comma -eq 1 ]; then 33 | echo -n "," 34 | else 35 | print_comma=1 36 | fi 37 | echo -n "$x" 38 | done 39 | echo 40 | done 41 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/src/genkat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "argon2.h" 6 | 7 | static void fatal(const char *error) { 8 | fprintf(stderr, "Error: %s\n", error); 9 | exit(1); 10 | } 11 | 12 | static void generate_testvectors(argon2_type type, const uint32_t version) { 13 | #define TEST_OUTLEN 32 14 | #define TEST_PWDLEN 32 15 | #define TEST_SALTLEN 16 16 | #define TEST_SECRETLEN 8 17 | #define TEST_ADLEN 12 18 | argon2_context context; 19 | 20 | unsigned char out[TEST_OUTLEN]; 21 | unsigned char pwd[TEST_PWDLEN]; 22 | unsigned char salt[TEST_SALTLEN]; 23 | unsigned char secret[TEST_SECRETLEN]; 24 | unsigned char ad[TEST_ADLEN]; 25 | const allocate_fptr myown_allocator = NULL; 26 | const deallocate_fptr myown_deallocator = NULL; 27 | 28 | unsigned t_cost = 3; 29 | unsigned m_cost = 32; 30 | unsigned lanes = 4; 31 | 32 | memset(pwd, 1, TEST_OUTLEN); 33 | memset(salt, 2, TEST_SALTLEN); 34 | memset(secret, 3, TEST_SECRETLEN); 35 | memset(ad, 4, TEST_ADLEN); 36 | 37 | context.out = out; 38 | context.outlen = TEST_OUTLEN; 39 | context.version = version; 40 | context.pwd = pwd; 41 | context.pwdlen = TEST_PWDLEN; 42 | context.salt = salt; 43 | context.saltlen = TEST_SALTLEN; 44 | context.secret = secret; 45 | context.secretlen = TEST_SECRETLEN; 46 | context.ad = ad; 47 | context.adlen = TEST_ADLEN; 48 | context.t_cost = t_cost; 49 | context.m_cost = m_cost; 50 | context.lanes = lanes; 51 | context.threads = lanes; 52 | context.allocate_cbk = myown_allocator; 53 | context.free_cbk = myown_deallocator; 54 | context.flags = ARGON2_DEFAULT_FLAGS | ARGON2_FLAG_GENKAT; 55 | 56 | #undef TEST_OUTLEN 57 | #undef TEST_PWDLEN 58 | #undef TEST_SALTLEN 59 | #undef TEST_SECRETLEN 60 | #undef TEST_ADLEN 61 | 62 | argon2_ctx(&context, type); 63 | } 64 | 65 | int main(int argc, char *argv[]) { 66 | /* Get and check Argon2 type */ 67 | const char *type_str = (argc > 1) ? argv[1] : "i"; 68 | argon2_type type = Argon2_i; 69 | uint32_t version = ARGON2_VERSION_NUMBER; 70 | if (!strcmp(type_str, "d")) { 71 | type = Argon2_d; 72 | } else if (!strcmp(type_str, "i")) { 73 | type = Argon2_i; 74 | } else if (!strcmp(type_str, "id")) { 75 | type = Argon2_id; 76 | } else { 77 | fatal("wrong Argon2 type"); 78 | } 79 | 80 | /* Get and check Argon2 version number */ 81 | if(argc > 2) { 82 | version = strtoul(argv[2], NULL, 10); 83 | } 84 | if (ARGON2_VERSION_10 != version && ARGON2_VERSION_NUMBER != version) { 85 | fatal("wrong Argon2 version number"); 86 | } 87 | 88 | generate_testvectors(type, version); 89 | return ARGON2_OK; 90 | } 91 | -------------------------------------------------------------------------------- /gpuMiner/ext/argon2/src/timing.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifdef _POSIX_SOURCE 4 | #include 5 | 6 | struct timestamp { 7 | struct timespec time; 8 | }; 9 | 10 | static inline void timestamp_store(struct timestamp *out) 11 | { 12 | clock_gettime(CLOCK_MONOTONIC, &out->time); 13 | } 14 | 15 | static inline double timestamp_span_ms(const struct timestamp *start, 16 | const struct timestamp *end) 17 | { 18 | double res = 0.0; 19 | res += (end->time.tv_sec - start->time.tv_sec) * 1000.0; 20 | res += (end->time.tv_nsec - start->time.tv_nsec) / 1000000.0; 21 | return res; 22 | } 23 | #else 24 | #include 25 | 26 | struct timestamp { 27 | clock_t time; 28 | }; 29 | 30 | static inline void timestamp_store(struct timestamp *out) 31 | { 32 | out->time = clock(); 33 | } 34 | 35 | static inline double timestamp_span_ms(const struct timestamp *start, 36 | const struct timestamp *end) 37 | { 38 | double res = (end->time - start->time) * 1000; 39 | return res / CLOCKS_PER_SEC; 40 | } 41 | #endif 42 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/cudaexception.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_CUDA_CUDAEXCEPTION_H 2 | #define ARGON2_CUDA_CUDAEXCEPTION_H 3 | 4 | #if HAVE_CUDA 5 | #include 6 | #endif 7 | 8 | #include 9 | 10 | namespace argon2 { 11 | namespace cuda { 12 | 13 | #if HAVE_CUDA 14 | 15 | class CudaException : public std::exception { 16 | private: 17 | cudaError_t res; 18 | 19 | public: 20 | CudaException(cudaError_t res) : res(res) { } 21 | 22 | const char *what() const noexcept override; 23 | 24 | static void check(cudaError_t res) 25 | { 26 | if (res != cudaSuccess) { 27 | throw CudaException(res); 28 | } 29 | } 30 | }; 31 | 32 | #else 33 | 34 | class CudaException : public std::exception { }; 35 | 36 | #endif 37 | 38 | } // namespace cuda 39 | } // namespace argon2 40 | 41 | #endif // ARGON2_CUDA_CUDAEXCEPTION_H 42 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/device.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef ARGON2_CUDA_DEVICE_H 19 | #define ARGON2_CUDA_DEVICE_H 20 | 21 | #include 22 | 23 | namespace argon2 { 24 | namespace cuda { 25 | 26 | #if HAVE_CUDA 27 | 28 | class Device 29 | { 30 | private: 31 | int deviceIndex; 32 | 33 | public: 34 | std::string getName() const; 35 | std::string getInfo() const; 36 | 37 | int getDeviceIndex() const { return deviceIndex; } 38 | 39 | /** 40 | * @brief Empty constructor. 41 | * NOTE: Calling methods other than the destructor on an instance initialized 42 | * with empty constructor results in undefined behavior. 43 | */ 44 | Device() { } 45 | 46 | Device(int deviceIndex) : deviceIndex(deviceIndex) 47 | { 48 | } 49 | 50 | Device(const Device &) = default; 51 | Device(Device &&) = default; 52 | 53 | Device &operator=(const Device &) = default; 54 | }; 55 | 56 | #else 57 | 58 | class Device 59 | { 60 | public: 61 | std::string getName() const { return {}; } 62 | std::string getInfo() const { return {}; } 63 | 64 | int getDeviceIndex() const { return 0; } 65 | 66 | Device() { } 67 | 68 | Device(const Device &) = default; 69 | Device(Device &&) = default; 70 | 71 | Device &operator=(const Device &) = default; 72 | }; 73 | 74 | #endif /* HAVE_CUDA */ 75 | 76 | } // namespace cuda 77 | } // namespace argon2 78 | 79 | #endif // ARGON2_CUDA_DEVICE_H 80 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/globalcontext.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef ARGON2_CUDA_GLOBALCONTEXT_H 19 | #define ARGON2_CUDA_GLOBALCONTEXT_H 20 | 21 | #include "device.h" 22 | 23 | #include 24 | #include 25 | 26 | namespace argon2 { 27 | namespace cuda { 28 | 29 | class GlobalContext 30 | { 31 | private: 32 | std::vector devices; 33 | 34 | public: 35 | const std::vector &getAllDevices() const { return devices; } 36 | 37 | #if HAVE_CUDA 38 | GlobalContext(); 39 | #else 40 | GlobalContext() : devices() {} 41 | #endif /* HAVE_CUDA */ 42 | }; 43 | 44 | } // namespace cuda 45 | } // namespace argon2 46 | 47 | #endif // ARGON2_CUDA_GLOBALCONTEXT_H 48 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/kernelrunner.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_CUDA_KERNELRUNNER_H 2 | #define ARGON2_CUDA_KERNELRUNNER_H 3 | 4 | #if HAVE_CUDA 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | /* workaround weird CMake/CUDA bug: */ 11 | #ifdef argon2 12 | #undef argon2 13 | #endif 14 | 15 | namespace argon2 { 16 | namespace cuda { 17 | 18 | class KernelRunner 19 | { 20 | private: 21 | std::uint32_t type, version; 22 | std::uint32_t passes, lanes, segmentBlocks; 23 | std::size_t batchSize; 24 | bool bySegment; 25 | bool precompute; 26 | 27 | cudaEvent_t start, end, kernelStart, kernelEnd; 28 | cudaStream_t stream; 29 | void *memory; 30 | void *refs; 31 | 32 | std::unique_ptr blocksIn; 33 | std::unique_ptr blocksOut; 34 | 35 | void copyInputBlocks(); 36 | void copyOutputBlocks(); 37 | 38 | void precomputeRefs(); 39 | 40 | void runKernelSegment(std::uint32_t lanesPerBlock, 41 | std::size_t jobsPerBlock, 42 | std::uint32_t pass, std::uint32_t slice); 43 | void runKernelOneshot(std::uint32_t lanesPerBlock, 44 | std::size_t jobsPerBlock); 45 | 46 | public: 47 | std::uint32_t getMinLanesPerBlock() const { return bySegment ? 1 : lanes; } 48 | std::uint32_t getMaxLanesPerBlock() const { return lanes; } 49 | 50 | std::size_t getMinJobsPerBlock() const { return 1; } 51 | std::size_t getMaxJobsPerBlock() const { return batchSize; } 52 | 53 | std::size_t getBatchSize() const { return batchSize; } 54 | 55 | KernelRunner(std::uint32_t type, std::uint32_t version, 56 | std::uint32_t passes, std::uint32_t lanes, 57 | std::uint32_t segmentBlocks, std::size_t batchSize, 58 | bool bySegment, bool precompute); 59 | ~KernelRunner(); 60 | 61 | void *getInputMemory(std::size_t jobId) const; 62 | const void *getOutputMemory(std::size_t jobId) const; 63 | 64 | void run(std::uint32_t lanesPerBlock, std::size_t jobsPerBlock); 65 | float finish(); 66 | }; 67 | 68 | } // cuda 69 | } // argon2 70 | 71 | #endif /* HAVE_CUDA */ 72 | 73 | #endif // ARGON2_CUDA_KERNELRUNNER_H 74 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/processingunit.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_CUDA_PROCESSINGUNIT_H 2 | #define ARGON2_CUDA_PROCESSINGUNIT_H 3 | 4 | #if HAVE_CUDA 5 | 6 | #include 7 | 8 | #include "programcontext.h" 9 | #include "kernelrunner.h" 10 | #include "argon2-gpu-common/argon2params.h" 11 | #include 12 | #include 13 | namespace argon2 { 14 | namespace cuda { 15 | 16 | class ProcessingUnit 17 | { 18 | private: 19 | const ProgramContext *programContext; 20 | const Argon2Params *params; 21 | const Device *device; 22 | std::vector passwordStorage; 23 | 24 | KernelRunner runner; 25 | std::uint32_t bestLanesPerBlock; 26 | std::size_t bestJobsPerBlock; 27 | 28 | public: 29 | std::size_t getBatchSize() const { return runner.getBatchSize(); } 30 | 31 | ProcessingUnit( 32 | const ProgramContext *programContext, const Argon2Params *params, 33 | const Device *device, std::size_t batchSize, 34 | bool bySegment = true, bool precomputeRefs = false); 35 | 36 | /* You can safely call this function after the beginProcessing() call to 37 | * prepare the next batch: */ 38 | void setPassword(std::size_t index, const void *pw, std::size_t pwSize); 39 | /* You can safely call this function after the beginProcessing() call to 40 | * process the previous batch: */ 41 | void getHash(std::size_t index, void *hash); 42 | std::string getPW(std::size_t index); 43 | 44 | void beginProcessing(); 45 | void endProcessing(); 46 | }; 47 | 48 | } // namespace cuda 49 | } // namespace argon2 50 | 51 | #else 52 | 53 | #include 54 | 55 | #include "programcontext.h" 56 | #include "argon2-gpu-common/argon2params.h" 57 | 58 | namespace argon2 { 59 | namespace cuda { 60 | 61 | class ProcessingUnit 62 | { 63 | public: 64 | std::size_t getBatchSize() const { return 0; } 65 | std::vector passwordStorage; 66 | 67 | ProcessingUnit( 68 | const ProgramContext *programContext, const Argon2Params *params, 69 | const Device *device, std::size_t batchSize, 70 | bool bySegment = true, bool precomputeRefs = false) 71 | { 72 | } 73 | 74 | void setPassword(std::size_t index, const void *pw, std::size_t pwSize) { } 75 | 76 | void getHash(std::size_t index, void *hash) { } 77 | std::string getPW(std::size_t index) { return {}; } 78 | 79 | void beginProcessing() { } 80 | void endProcessing() { } 81 | }; 82 | 83 | } // namespace cuda 84 | } // namespace argon2 85 | 86 | #endif /* HAVE_CUDA */ 87 | 88 | #endif // ARGON2_CUDA_PROCESSINGUNIT_H 89 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-cuda/programcontext.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_CUDA_PROGRAMCONTEXT_H 2 | #define ARGON2_CUDA_PROGRAMCONTEXT_H 3 | 4 | #include "globalcontext.h" 5 | #include "argon2-gpu-common/argon2-common.h" 6 | 7 | namespace argon2 { 8 | namespace cuda { 9 | 10 | #if HAVE_CUDA 11 | 12 | class ProgramContext 13 | { 14 | private: 15 | const GlobalContext *globalContext; 16 | 17 | Type type; 18 | Version version; 19 | 20 | public: 21 | const GlobalContext *getGlobalContext() const { return globalContext; } 22 | 23 | Type getArgon2Type() const { return type; } 24 | Version getArgon2Version() const { return version; } 25 | 26 | ProgramContext( 27 | const GlobalContext *globalContext, 28 | const std::vector &devices, 29 | Type type, Version version); 30 | }; 31 | 32 | #else 33 | 34 | class ProgramContext 35 | { 36 | private: 37 | const GlobalContext *globalContext; 38 | 39 | Type type; 40 | Version version; 41 | 42 | public: 43 | const GlobalContext *getGlobalContext() const { return globalContext; } 44 | 45 | Type getArgon2Type() const { return type; } 46 | Version getArgon2Version() const { return version; } 47 | 48 | ProgramContext( 49 | const GlobalContext *globalContext, 50 | const std::vector &devices, 51 | Type type, Version version) 52 | : globalContext(globalContext), type(type), version(version) 53 | { 54 | } 55 | }; 56 | 57 | #endif /* HAVE_CUDA */ 58 | 59 | } // namespace cuda 60 | } // namespace argon2 61 | 62 | #endif // ARGON2_CUDA_PROGRAMCONTEXT_H 63 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-gpu-common/argon2-common.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2COMMON_H 2 | #define ARGON2COMMON_H 3 | 4 | namespace argon2 { 5 | 6 | enum { 7 | ARGON2_BLOCK_SIZE = 1024, 8 | ARGON2_SYNC_POINTS = 4, 9 | ARGON2_PREHASH_DIGEST_LENGTH = 64, 10 | ARGON2_PREHASH_SEED_LENGTH = 72, 11 | }; 12 | 13 | enum Type { 14 | ARGON2_D = 0, 15 | ARGON2_I = 1, 16 | ARGON2_ID = 2, 17 | }; 18 | 19 | enum Version { 20 | ARGON2_VERSION_10 = 0x10, 21 | ARGON2_VERSION_13 = 0x13, 22 | }; 23 | 24 | } // namespace argon2 25 | 26 | 27 | #endif // ARGON2COMMON_H 28 | 29 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-gpu-common/argon2params.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_ARGON2PARAMS_H 2 | #define ARGON2_ARGON2PARAMS_H 3 | 4 | #include 5 | 6 | #if defined(__APPLE__) || defined(__MACOSX) || defined(_WIN32) || defined(_WIN32) 7 | #include // for size_t 8 | #endif 9 | 10 | #include "argon2-common.h" 11 | #include 12 | namespace argon2 { 13 | 14 | class Argon2Params 15 | { 16 | private: 17 | const void *secret, *ad; 18 | std::uint32_t outLen, saltLen, secretLen, adLen; 19 | std::uint32_t t_cost, m_cost, lanes; 20 | std::string salt; 21 | std::uint32_t segmentBlocks; 22 | 23 | static void digestLong(void *out, std::size_t outLen, 24 | const void *in, std::size_t inLen); 25 | 26 | void initialHash(void *out, const void *pwd, std::size_t pwdLen, 27 | Type type, Version version) const; 28 | 29 | public: 30 | std::uint32_t getOutputLength() const { return outLen; } 31 | 32 | std::string getSalt() const { return salt; } 33 | std::uint32_t getSaltLength() const { return saltLen; } 34 | 35 | const void *getSecret() const { return secret; } 36 | std::uint32_t getSecretLength() const { return secretLen; } 37 | 38 | const void *getAssocData() const { return ad; } 39 | std::uint32_t getAssocDataLength() const { return adLen; } 40 | 41 | std::uint32_t getTimeCost() const { return t_cost; } 42 | std::uint32_t getMemoryCost() const { return m_cost; } 43 | std::uint32_t getLanes() const { return lanes; } 44 | 45 | std::uint32_t getSegmentBlocks() const { return segmentBlocks; } 46 | std::uint32_t getLaneBlocks() const { 47 | return segmentBlocks * ARGON2_SYNC_POINTS; 48 | } 49 | std::uint32_t getMemoryBlocks() const { return getLaneBlocks() * lanes; } 50 | std::size_t getMemorySize() const { 51 | return static_cast(getMemoryBlocks()) * ARGON2_BLOCK_SIZE; 52 | } 53 | 54 | Argon2Params( 55 | std::size_t outLen, 56 | std::string salt, std::size_t saltLen, 57 | const void *secret, std::size_t secretLen, 58 | const void *ad, std::size_t adLen, 59 | std::size_t t_cost, std::size_t m_cost, std::size_t lanes); 60 | 61 | void fillFirstBlocks(void *memory, const void *pwd, std::size_t pwdLen, 62 | Type type, Version version) const; 63 | 64 | void finalize(void *out, const void *memory) const; 65 | }; 66 | 67 | } // namespace argon2 68 | 69 | #endif // ARGON2_ARGON2PARAMS_H 70 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/device.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef ARGON2_OPENCL_DEVICE_H 19 | #define ARGON2_OPENCL_DEVICE_H 20 | 21 | #include "opencl.h" 22 | 23 | namespace argon2 { 24 | namespace opencl { 25 | 26 | class Device 27 | { 28 | private: 29 | cl::Device device; 30 | 31 | public: 32 | std::string getName() const; 33 | std::string getInfo() const; 34 | 35 | const cl::Device &getCLDevice() const { return device; } 36 | 37 | /** 38 | * @brief Empty constructor. 39 | * NOTE: Calling methods other than the destructor on an instance initialized 40 | * with empty constructor results in undefined behavior. 41 | */ 42 | Device() { } 43 | 44 | Device(const cl::Device &device) 45 | : device(device) 46 | { 47 | } 48 | 49 | Device(const Device &) = default; 50 | Device(Device &&) = default; 51 | 52 | Device &operator=(const Device &) = default; 53 | }; 54 | 55 | } // namespace opencl 56 | } // namespace argon2 57 | 58 | #endif // ARGON2_OPENCL_DEVICE_H 59 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/globalcontext.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef ARGON2_OPENCL_GLOBALCONTEXT_H 19 | #define ARGON2_OPENCL_GLOBALCONTEXT_H 20 | 21 | #include "device.h" 22 | 23 | #include 24 | #include 25 | 26 | namespace argon2 { 27 | namespace opencl { 28 | 29 | class GlobalContext 30 | { 31 | private: 32 | std::vector devices; 33 | 34 | public: 35 | const std::vector &getAllDevices() const { return devices; } 36 | 37 | GlobalContext(); 38 | }; 39 | 40 | } // namespace opencl 41 | } // namespace argon2 42 | 43 | #endif // ARGON2_OPENCL_GLOBALCONTEXT_H 44 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/kernelrunner.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_OPENCL_KERNELRUNNER_H 2 | #define ARGON2_OPENCL_KERNELRUNNER_H 3 | 4 | #include "programcontext.h" 5 | #include "argon2-gpu-common/argon2params.h" 6 | 7 | #include 8 | 9 | namespace argon2 { 10 | namespace opencl { 11 | 12 | class KernelRunner 13 | { 14 | private: 15 | const ProgramContext *programContext; 16 | const Argon2Params *params; 17 | 18 | std::size_t batchSize; 19 | bool bySegment; 20 | bool precompute; 21 | 22 | cl::CommandQueue queue; 23 | cl::Kernel kernel; 24 | cl::Buffer memoryBuffer, refsBuffer; 25 | cl::Event start, end, kernelStart, kernelEnd; 26 | 27 | std::size_t memorySize; 28 | 29 | std::unique_ptr blocksIn; 30 | std::unique_ptr blocksOut; 31 | 32 | void copyInputBlocks(); 33 | void copyOutputBlocks(); 34 | 35 | void precomputeRefs(); 36 | 37 | public: 38 | std::uint32_t getMinLanesPerBlock() const 39 | { 40 | return bySegment ? 1 : params->getLanes(); 41 | } 42 | std::uint32_t getMaxLanesPerBlock() const { return params->getLanes(); } 43 | 44 | std::size_t getMinJobsPerBlock() const { return 1; } 45 | std::size_t getMaxJobsPerBlock() const { return batchSize; } 46 | 47 | std::size_t getBatchSize() const { return batchSize; } 48 | 49 | void *getInputMemory(std::size_t jobId) const 50 | { 51 | std::size_t copySize = params->getLanes() * 2 * ARGON2_BLOCK_SIZE; 52 | return blocksIn.get() + jobId * copySize; 53 | } 54 | const void *getOutputMemory(std::size_t jobId) const 55 | { 56 | std::size_t copySize = params->getLanes() * ARGON2_BLOCK_SIZE; 57 | return blocksOut.get() + jobId * copySize; 58 | } 59 | 60 | KernelRunner(const ProgramContext *programContext, 61 | const Argon2Params *params, const Device *device, 62 | std::size_t batchSize, bool bySegment, bool precompute); 63 | 64 | void run(std::uint32_t lanesPerBlock, std::size_t jobsPerBlock); 65 | float finish(); 66 | }; 67 | 68 | } // namespace opencl 69 | } // namespace argon2 70 | 71 | #endif // ARGON2_OPENCL_KERNELRUNNER_H 72 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/opencl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef OPENCL_H 19 | #define OPENCL_H 20 | 21 | /* Some compatibility hacks: */ 22 | #define CL_USE_DEPRECATED_OPENCL_1_1_APIS 23 | #define CL_USE_DEPRECATED_OPENCL_1_2_APIS 24 | #if defined(__APPLE__) || defined(__MACOSX) 25 | #include 26 | #else 27 | #include 28 | #endif 29 | #undef CL_VERSION_2_0 30 | 31 | /* Throw exceptions on errors: */ 32 | #define __CL_ENABLE_EXCEPTIONS 33 | /* Include local version of 34 | * because not all platforms ship with it: */ 35 | #include "cl.hpp" 36 | 37 | #endif // OPENCL_H 38 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/processingunit.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_OPENCL_PROCESSINGUNIT_H 2 | #define ARGON2_OPENCL_PROCESSINGUNIT_H 3 | 4 | #include 5 | 6 | #include "kernelrunner.h" 7 | 8 | namespace argon2 { 9 | namespace opencl { 10 | 11 | class ProcessingUnit 12 | { 13 | private: 14 | const ProgramContext *programContext; 15 | const Argon2Params *params; 16 | const Device *device; 17 | std::vector passwordStorage; 18 | 19 | KernelRunner runner; 20 | std::uint32_t bestLanesPerBlock; 21 | std::size_t bestJobsPerBlock; 22 | 23 | public: 24 | std::size_t getBatchSize() const { return runner.getBatchSize(); } 25 | 26 | ProcessingUnit( 27 | const ProgramContext *programContext, const Argon2Params *params, 28 | const Device *device, std::size_t batchSize, 29 | bool bySegment = true, bool precomputeRefs = false); 30 | 31 | /* You can safely call this function after the beginProcessing() call to 32 | * prepare the next batch: */ 33 | void setPassword(std::size_t index, const void *pw, std::size_t pwSize); 34 | /* You can safely call this function after the beginProcessing() call to 35 | * process the previous batch: */ 36 | void getHash(std::size_t index, void *hash); 37 | std::string getPW(std::size_t index); 38 | 39 | void beginProcessing(); 40 | void endProcessing(); 41 | }; 42 | 43 | } // namespace opencl 44 | } // namespace argon2 45 | 46 | #endif // ARGON2_OPENCL_PROCESSINGUNIT_H 47 | -------------------------------------------------------------------------------- /gpuMiner/include/argon2-opencl/programcontext.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_OPENCL_PROGRAMCONTEXT_H 2 | #define ARGON2_OPENCL_PROGRAMCONTEXT_H 3 | 4 | #include "globalcontext.h" 5 | #include "argon2-gpu-common/argon2-common.h" 6 | 7 | namespace argon2 { 8 | namespace opencl { 9 | 10 | class ProgramContext 11 | { 12 | private: 13 | const GlobalContext *globalContext; 14 | 15 | std::vector devices; 16 | cl::Context context; 17 | cl::Program program; 18 | 19 | Type type; 20 | Version version; 21 | 22 | public: 23 | const GlobalContext *getGlobalContext() const { return globalContext; } 24 | 25 | const std::vector &getDevices() const { return devices; } 26 | const cl::Context &getContext() const { return context; } 27 | const cl::Program &getProgram() const { return program; } 28 | 29 | Type getArgon2Type() const { return type; } 30 | Version getArgon2Version() const { return version; } 31 | 32 | ProgramContext( 33 | const GlobalContext *globalContext, 34 | const std::vector &devices, 35 | Type type, Version version); 36 | }; 37 | 38 | } // namespace opencl 39 | } // namespace argon2 40 | 41 | #endif // ARGON2_OPENCL_PROGRAMCONTEXT_H 42 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/cudaexception.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #include "cudaexception.h" 19 | 20 | namespace argon2 { 21 | namespace cuda { 22 | 23 | #if HAVE_CUDA 24 | const char *CudaException::what() const noexcept 25 | { 26 | return cudaGetErrorString(res); 27 | } 28 | #endif 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/device.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #include 19 | 20 | #include "device.h" 21 | #include "cudaexception.h" 22 | 23 | namespace argon2 { 24 | namespace cuda { 25 | 26 | std::string Device::getName() const 27 | { 28 | cudaDeviceProp prop; 29 | CudaException::check(cudaGetDeviceProperties(&prop, deviceIndex)); 30 | return "CUDA Device '" + std::string(prop.name) + "'"; 31 | } 32 | 33 | std::string Device::getInfo() const 34 | { 35 | /* FIXME: show some more stuff here: */ 36 | cudaDeviceProp prop; 37 | CudaException::check(cudaGetDeviceProperties(&prop, deviceIndex)); 38 | return "CUDA Device '" + std::string(prop.name) + "'"; 39 | } 40 | 41 | } // namespace cuda 42 | } // namespace argon2 43 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/globalcontext.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #include "globalcontext.h" 19 | #include "cudaexception.h" 20 | 21 | namespace argon2 { 22 | namespace cuda { 23 | 24 | GlobalContext::GlobalContext() 25 | : devices() 26 | { 27 | int count; 28 | CudaException::check(cudaGetDeviceCount(&count)); 29 | 30 | devices.reserve(count); 31 | for (int i = 0; i < count; i++) { 32 | devices.emplace_back(i); 33 | } 34 | } 35 | 36 | } // namespace cuda 37 | } // namespace argon2 38 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/nocuda.cpp: -------------------------------------------------------------------------------- 1 | /* This file intentionally left empty */ 2 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/processingunit.cpp: -------------------------------------------------------------------------------- 1 | #include "processingunit.h" 2 | 3 | #include "cudaexception.h" 4 | 5 | #include 6 | #include 7 | #ifndef NDEBUG 8 | #include 9 | #endif 10 | 11 | namespace argon2 { 12 | namespace cuda { 13 | 14 | static void setCudaDevice(int deviceIndex) 15 | { 16 | int currentIndex = -1; 17 | CudaException::check(cudaGetDevice(¤tIndex)); 18 | if (currentIndex != deviceIndex) { 19 | CudaException::check(cudaSetDevice(deviceIndex)); 20 | } 21 | } 22 | 23 | static bool isPowerOfTwo(std::size_t x) 24 | { 25 | return (x & (x - 1)) == 0; 26 | } 27 | 28 | ProcessingUnit::ProcessingUnit( 29 | const ProgramContext *programContext, const Argon2Params *params, 30 | const Device *device, std::size_t batchSize, bool bySegment, 31 | bool precomputeRefs) 32 | : programContext(programContext), params(params), device(device), 33 | runner(programContext->getArgon2Type(), 34 | programContext->getArgon2Version(), params->getTimeCost(), 35 | params->getLanes(), params->getSegmentBlocks(), batchSize, 36 | bySegment, precomputeRefs), 37 | bestLanesPerBlock(runner.getMinLanesPerBlock()), 38 | bestJobsPerBlock(runner.getMinJobsPerBlock()) 39 | { 40 | setCudaDevice(device->getDeviceIndex()); 41 | 42 | /* pre-fill first blocks with pseudo-random data: */ 43 | for (std::size_t i = 0; i < batchSize; i++) { 44 | setPassword(i, NULL, 0); 45 | } 46 | 47 | } 48 | 49 | void ProcessingUnit::setPassword(std::size_t index, const void *pw, 50 | std::size_t pwSize) 51 | { 52 | params->fillFirstBlocks(runner.getInputMemory(index), pw, pwSize, 53 | programContext->getArgon2Type(), 54 | programContext->getArgon2Version()); 55 | // Expand the storage if needed 56 | if (passwordStorage.size() <= index) { 57 | passwordStorage.resize(index + 1); 58 | } 59 | 60 | // Store the password at the specified index 61 | passwordStorage[index] = std::string(static_cast(pw), pwSize); 62 | } 63 | 64 | void ProcessingUnit::getHash(std::size_t index, void *hash) 65 | { 66 | params->finalize(hash, runner.getOutputMemory(index)); 67 | } 68 | std::string ProcessingUnit::getPW(std::size_t index){ 69 | if (index < passwordStorage.size()) { 70 | return passwordStorage[index]; 71 | } 72 | return {}; // Return an empty string if the index is out of bounds 73 | 74 | } 75 | void ProcessingUnit::beginProcessing() 76 | { 77 | setCudaDevice(device->getDeviceIndex()); 78 | runner.run(bestLanesPerBlock, bestJobsPerBlock); 79 | } 80 | 81 | void ProcessingUnit::endProcessing() 82 | { 83 | runner.finish(); 84 | } 85 | 86 | } // namespace cuda 87 | } // namespace argon2 88 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-cuda/programcontext.cpp: -------------------------------------------------------------------------------- 1 | #include "programcontext.h" 2 | 3 | #define THREADS_PER_LANE 32 4 | 5 | namespace argon2 { 6 | namespace cuda { 7 | 8 | ProgramContext::ProgramContext( 9 | const GlobalContext *globalContext, 10 | const std::vector &, 11 | Type type, Version version) 12 | : globalContext(globalContext), type(type), version(version) 13 | { 14 | } 15 | 16 | } // namespace cuda 17 | } // namespace argon2 18 | 19 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-gpu-common/blake2b.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_BLAKE2B_H 2 | #define ARGON2_BLAKE2B_H 3 | 4 | #include 5 | 6 | #if defined(__APPLE__) || defined(__MACOSX) || defined(_WIN32) 7 | #include 8 | #endif 9 | 10 | #ifdef _WIN32 11 | # define EXPORT_SYMBOL1 __declspec(dllexport) 12 | #else 13 | # define EXPORT_SYMBOL1 14 | #endif 15 | 16 | namespace argon2 { 17 | 18 | class EXPORT_SYMBOL1 Blake2b 19 | { 20 | public: 21 | enum { 22 | BLOCK_BYTES = 128, 23 | OUT_BYTES = 64, 24 | }; 25 | 26 | private: 27 | std::uint64_t h[8]; 28 | std::uint64_t t[2]; 29 | std::uint8_t buf[BLOCK_BYTES]; 30 | std::size_t bufLen; 31 | 32 | void compress(const void *block, std::uint64_t f0); 33 | void incrementCounter(std::uint64_t inc); 34 | 35 | public: 36 | Blake2b() : h(), t(), buf(), bufLen(0) { } 37 | 38 | void init(std::size_t outlen); 39 | void update(const void *in, std::size_t inLen); 40 | void final(void *out, std::size_t outLen); 41 | }; 42 | 43 | } // namespace argon2 44 | 45 | #endif // ARGON2_BLAKE2B_H 46 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-opencl/globalcontext.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015, Ondrej Mosnacek 3 | * 4 | * This program is free software: you can redistribute it and/or 5 | * modify it under the terms of the GNU General Public License 6 | * as published by the Free Software Foundation: either version 2 7 | * of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #include "globalcontext.h" 19 | 20 | #include 21 | 22 | namespace argon2 { 23 | namespace opencl { 24 | 25 | GlobalContext::GlobalContext() 26 | : devices() 27 | { 28 | std::vector platforms; 29 | cl::Platform::get(&platforms); 30 | 31 | std::vector clDevices; 32 | for (cl::Platform platform : platforms) { 33 | try { 34 | platform.getDevices(CL_DEVICE_TYPE_ALL, &clDevices); 35 | devices.insert(devices.end(), clDevices.begin(), clDevices.end()); 36 | } catch (const cl::Error &err) { 37 | std::cerr << "WARNING: Unable to get devices for platform '" 38 | << platform.getInfo() 39 | << "' - error " << err.err() << std::endl; 40 | } 41 | } 42 | } 43 | 44 | } // namespace opencl 45 | } // namespace argon2 46 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-opencl/kernelloader.cpp: -------------------------------------------------------------------------------- 1 | #include "kernelloader.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | namespace argon2 { 8 | namespace opencl { 9 | 10 | cl::Program KernelLoader::loadArgon2Program( 11 | const cl::Context &context, 12 | const std::string &sourceDirectory, 13 | Type type, Version version, bool debug) 14 | { 15 | std::string sourcePath = sourceDirectory + "/argon2_kernel.cl"; 16 | std::string sourceText; 17 | std::stringstream buildOpts; 18 | { 19 | std::ifstream sourceFile { sourcePath }; 20 | sourceText = { 21 | std::istreambuf_iterator(sourceFile), 22 | std::istreambuf_iterator() 23 | }; 24 | } 25 | 26 | if (debug) { 27 | buildOpts << "-g -s \"" << sourcePath << "\"" << " "; 28 | } 29 | buildOpts << "-DARGON2_TYPE=" << type << " "; 30 | buildOpts << "-DARGON2_VERSION=" << version << " "; 31 | 32 | cl::Program prog(context, sourceText); 33 | try { 34 | std::string opts = buildOpts.str(); 35 | prog.build(opts.c_str()); 36 | } catch (const cl::Error &) { 37 | std::cerr << "ERROR: Failed to build program:" << std::endl; 38 | for (cl::Device &device : context.getInfo()) { 39 | std::cerr << " Build log from device '" << device.getInfo() << "':" << std::endl; 40 | std::cerr << prog.getBuildInfo(device); 41 | } 42 | throw; 43 | } 44 | return prog; 45 | } 46 | 47 | } // namespace opencl 48 | } // namespace argon2 49 | 50 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-opencl/kernelloader.h: -------------------------------------------------------------------------------- 1 | #ifndef ARGON2_OPENCL_KERNELLOADER_H 2 | #define ARGON2_OPENCL_KERNELLOADER_H 3 | 4 | #include "opencl.h" 5 | #include "argon2-gpu-common/argon2-common.h" 6 | 7 | #include 8 | 9 | namespace argon2 { 10 | namespace opencl { 11 | 12 | namespace KernelLoader 13 | { 14 | cl::Program loadArgon2Program( 15 | const cl::Context &context, 16 | const std::string &sourceDirectory, 17 | Type type, Version version, bool debug = false); 18 | }; 19 | 20 | } // namespace opencl 21 | } // namespace argon2 22 | 23 | #endif // ARGON2_OPENCL_KERNELLOADER_H 24 | -------------------------------------------------------------------------------- /gpuMiner/lib/argon2-opencl/programcontext.cpp: -------------------------------------------------------------------------------- 1 | #include "programcontext.h" 2 | 3 | #include "kernelloader.h" 4 | 5 | namespace argon2 { 6 | namespace opencl { 7 | 8 | ProgramContext::ProgramContext( 9 | const GlobalContext *globalContext, 10 | const std::vector &devices, 11 | Type type, Version version) 12 | : globalContext(globalContext), devices(), type(type), version(version) 13 | { 14 | this->devices.reserve(devices.size()); 15 | for (auto &device : devices) { 16 | this->devices.push_back(device.getCLDevice()); 17 | } 18 | context = cl::Context(this->devices); 19 | 20 | program = KernelLoader::loadArgon2Program( 21 | // FIXME path: 22 | context, "./gpuMiner/data/kernels", type, version); 23 | } 24 | 25 | } // namespace opencl 26 | } // namespace argon2 27 | 28 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/benchmark.h: -------------------------------------------------------------------------------- 1 | #ifndef BENCHMARK_H 2 | #define BENCHMARK_H 3 | 4 | #include "pwgen.h" 5 | #include "runtimestatistics.h" 6 | 7 | #include "argon2-gpu-common/argon2-common.h" 8 | 9 | class BenchmarkDirector; 10 | 11 | class Argon2Runner 12 | { 13 | public: 14 | virtual ~Argon2Runner(); 15 | virtual nanosecs runBenchmark(const BenchmarkDirector &director, 16 | PasswordGenerator &pwGen) = 0; 17 | }; 18 | 19 | class BenchmarkDirector 20 | { 21 | private: 22 | std::string progname; 23 | argon2::Type type; 24 | argon2::Version version; 25 | std::size_t t_cost, m_cost, lanes; 26 | std::size_t batchSize, samples; 27 | bool bySegment, precomputeRefs; 28 | std::string outputMode, outputType; 29 | std::string salt; 30 | bool beVerbose; 31 | bool benchmark = false; 32 | std::string benchmarkFileName; 33 | 34 | public: 35 | const std::string &getProgname() const { return progname; } 36 | argon2::Type getType() const { return type; } 37 | argon2::Version getVersion() const { return version; } 38 | std::size_t getTimeCost() const { return t_cost; } 39 | std::size_t getMemoryCost() const { return m_cost; } 40 | std::size_t getLanes() const { return lanes; } 41 | std::size_t getBatchSize() const { return batchSize; } 42 | bool isBySegment() const { return bySegment; } 43 | bool isPrecomputeRefs() const { return precomputeRefs; } 44 | bool isVerbose() const { return beVerbose; } 45 | std::string getSalt() const {return salt;} 46 | 47 | BenchmarkDirector(const std::string &progname, 48 | argon2::Type type, argon2::Version version, std::string salt, 49 | std::size_t t_cost, std::size_t m_cost, std::size_t lanes, 50 | std::size_t batchSize, bool bySegment, 51 | bool precomputeRefs, std::size_t samples, 52 | const std::string &outputMode, 53 | const std::string &outputType, bool benchmark = false) 54 | : progname(progname), type(type), version(version), salt(salt), 55 | t_cost(t_cost), m_cost(m_cost), lanes(lanes), batchSize(batchSize), 56 | samples(samples), bySegment(bySegment), precomputeRefs(precomputeRefs), 57 | outputMode(outputMode), outputType(outputType), 58 | beVerbose(outputMode == "verbose"), benchmark(benchmark) 59 | { 60 | } 61 | 62 | int runBenchmark(Argon2Runner &runner) const; 63 | }; 64 | 65 | class BenchmarkExecutive 66 | { 67 | public: 68 | virtual ~BenchmarkExecutive(); 69 | virtual int runBenchmark(const BenchmarkDirector &director) const = 0; 70 | }; 71 | 72 | #endif // BENCHMARK_H 73 | 74 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/cpuexecutive.h: -------------------------------------------------------------------------------- 1 | #ifndef CPUEXECUTIVE_H 2 | #define CPUEXECUTIVE_H 3 | 4 | #include "benchmark.h" 5 | 6 | class CpuExecutive : public BenchmarkExecutive 7 | { 8 | private: 9 | std::size_t deviceIndex; 10 | bool listDevices; 11 | 12 | public: 13 | CpuExecutive(std::size_t deviceIndex, bool listDevices) 14 | : deviceIndex(deviceIndex), listDevices(listDevices) 15 | { 16 | } 17 | 18 | int runBenchmark(const BenchmarkDirector &director) const override; 19 | }; 20 | 21 | #endif // CPUEXECUTIVE_H 22 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/cudaexecutive.h: -------------------------------------------------------------------------------- 1 | #ifndef CUDAEXECUTIVE_H 2 | #define CUDAEXECUTIVE_H 3 | 4 | #include "benchmark.h" 5 | 6 | class CudaExecutive : public BenchmarkExecutive 7 | { 8 | private: 9 | std::size_t deviceIndex; 10 | bool listDevices; 11 | 12 | public: 13 | CudaExecutive(std::size_t deviceIndex, bool listDevices) 14 | : deviceIndex(deviceIndex), listDevices(listDevices) 15 | { 16 | } 17 | 18 | int runBenchmark(const BenchmarkDirector &director) const override; 19 | }; 20 | 21 | #endif // CUDAEXECUTIVE_H 22 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/openclexecutive.h: -------------------------------------------------------------------------------- 1 | #ifndef OPENCLEXECUTIVE_H 2 | #define OPENCLEXECUTIVE_H 3 | 4 | #include "benchmark.h" 5 | 6 | class OpenCLExecutive : public BenchmarkExecutive 7 | { 8 | private: 9 | std::size_t deviceIndex; 10 | bool listDevices; 11 | 12 | public: 13 | OpenCLExecutive(std::size_t deviceIndex, bool listDevices) 14 | : deviceIndex(deviceIndex), listDevices(listDevices) 15 | { 16 | } 17 | 18 | int runBenchmark(const BenchmarkDirector &director) const override; 19 | }; 20 | 21 | #endif // OPENCLEXECUTIVE_H 22 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/pwgen.h: -------------------------------------------------------------------------------- 1 | #ifndef PWGEN_H 2 | #define PWGEN_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class PasswordGenerator 9 | { 10 | public: 11 | virtual void nextPassword(const void *&pw, std::size_t &pwSize) = 0; 12 | }; 13 | namespace aaa{ 14 | constexpr char hex_chars[] = "0123456789abcdef"; 15 | } 16 | class DummyPasswordGenerator : public PasswordGenerator 17 | { 18 | private: 19 | std::mt19937 gen; 20 | std::string currentPw; 21 | 22 | static constexpr std::size_t PASSWORD_LENGTH = 64; 23 | 24 | public: 25 | DummyPasswordGenerator() 26 | : gen(std::chrono::system_clock::now().time_since_epoch().count()) 27 | { 28 | currentPw.resize(PASSWORD_LENGTH); 29 | // Generate a random hex string 30 | for (std::size_t i = 0; i < PASSWORD_LENGTH; i++) { 31 | currentPw[i] = aaa::hex_chars[gen()&15]; 32 | } 33 | } 34 | 35 | void nextPassword(const void *&pw, std::size_t &pwSize) override 36 | { 37 | // Modify one character randomly 38 | for(char& c : currentPw) 39 | c = aaa::hex_chars[gen() & 15]; 40 | pw = currentPw.data(); 41 | pwSize = currentPw.size(); 42 | } 43 | }; 44 | 45 | #endif // PWGEN_H 46 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/runtimestatistics.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNTIMESTATISTICS_H 2 | #define RUNTIMESTATISTICS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | typedef uintmax_t nanosecs; 11 | 12 | template 13 | static nanosecs toNanoseconds(const duration &d) 14 | { 15 | return d.count() * ((nanosecs)1000 * 1000 * 1000 * duration::period::num / duration::period::den); 16 | } 17 | 18 | class DataSet 19 | { 20 | private: 21 | std::vector samples; 22 | uintmax_t sum; 23 | uintmax_t mean; 24 | uintmax_t devSum; 25 | uintmax_t devMean; 26 | 27 | public: 28 | const std::vector &getSamples() const { return samples; } 29 | uintmax_t getMean() const { return mean; } 30 | uintmax_t getMeanDeviation() const { return devMean; } 31 | 32 | double getMeanDeviationPerMean() const { return (double)devMean / mean; } 33 | 34 | DataSet() 35 | : samples(), sum(0), mean(0), 36 | devSum(0), devMean(0) 37 | { 38 | } 39 | 40 | void addSample(uintmax_t sample) 41 | { 42 | sum += sample; 43 | samples.push_back(sample); 44 | } 45 | 46 | void close() 47 | { 48 | mean = sum / samples.size(); 49 | 50 | devSum = std::accumulate( 51 | samples.begin(), samples.end(), (uintmax_t)0, 52 | [=](uintmax_t s, uintmax_t x) 53 | { 54 | auto dev = (intmax_t)(x - mean); 55 | return s + (dev >= 0 ? dev : -dev); 56 | }); 57 | devMean = devSum / samples.size(); 58 | } 59 | }; 60 | 61 | class RunTimeStats 62 | { 63 | private: 64 | std::uintmax_t batchSize; 65 | DataSet ns; 66 | DataSet nsPerHash; 67 | 68 | public: 69 | const DataSet &getNanoseconds() const { return ns; } 70 | const DataSet &getNanosecsPerHash() const { return nsPerHash; } 71 | 72 | RunTimeStats(std::size_t batchSize) 73 | : batchSize(batchSize), ns(), nsPerHash() 74 | { 75 | } 76 | 77 | void addSample(nanosecs sample) 78 | { 79 | ns.addSample(sample); 80 | nsPerHash.addSample(sample / batchSize); 81 | } 82 | 83 | void close() 84 | { 85 | ns.close(); 86 | nsPerHash.close(); 87 | } 88 | 89 | static double toMinutes(nanosecs ns) 90 | { 91 | return (double)ns / ((nanosecs)60 * 1000 * 1000 * 1000); 92 | } 93 | 94 | static double toSeconds(nanosecs ns) 95 | { 96 | return (double)ns / ((nanosecs)1000 * 1000 * 1000); 97 | } 98 | 99 | static double toMilliSeconds(nanosecs ns) 100 | { 101 | return (double)ns / ((nanosecs)1000 * 1000); 102 | } 103 | 104 | static double toMicroSeconds(nanosecs ns) 105 | { 106 | return (double)ns / (nanosecs)1000; 107 | } 108 | 109 | static std::string repr(nanosecs ns) 110 | { 111 | if (ns < (nanosecs)1000) { 112 | return std::to_string(ns) + " ns"; 113 | } 114 | if (ns < (nanosecs)1000 * 1000) { 115 | return std::to_string(toMicroSeconds(ns)) + " us"; 116 | } 117 | if (ns < (nanosecs)1000 * 1000 * 1000) { 118 | return std::to_string(toMilliSeconds(ns)) + " ms"; 119 | } 120 | if (ns < (nanosecs)60 * 1000 * 1000 * 1000) { 121 | return std::to_string(toSeconds(ns)) + " s"; 122 | } 123 | return std::to_string(toMinutes(ns)) + " min"; 124 | } 125 | }; 126 | 127 | #endif // RUNTIMESTATISTICS_H 128 | -------------------------------------------------------------------------------- /gpuMiner/src/argon2-gpu-bench/shared.h: -------------------------------------------------------------------------------- 1 | // shared.h 2 | 3 | #pragma once 4 | #include 5 | 6 | extern std::mutex mtx; // declare mutex 7 | extern int difficulty; // declare difficulty -------------------------------------------------------------------------------- /index_builder.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import json 3 | from datetime import datetime 4 | 5 | # Connect to the SQLite database 6 | conn = sqlite3.connect("blockchain.db") 7 | cursor = conn.cursor() 8 | 9 | # Create the 'blocks' table if it doesn't exist 10 | cursor.execute(""" 11 | CREATE TABLE IF NOT EXISTS blocks ( 12 | block_id INTEGER PRIMARY KEY AUTOINCREMENT, 13 | hash_to_verify TEXT, 14 | key TEXT UNIQUE, 15 | account TEXT, 16 | created_at DATETIME DEFAULT CURRENT_TIMESTAMP 17 | ) 18 | """) 19 | 20 | # Fetch all records from the 'blockchain' table 21 | cursor.execute("SELECT records_json FROM blockchain") 22 | records = cursor.fetchall() 23 | 24 | # Placeholder for batch inserts 25 | all_values = [] 26 | 27 | # Loop through each record and prepare data for batch insertion into the 'blocks' table 28 | for record in records: 29 | records_json = record[0] 30 | records_list = json.loads(records_json) # Assuming records_json is in JSON format 31 | 32 | for item in records_list: 33 | hash_to_verify = item.get("hash_to_verify") 34 | key = item.get("key") 35 | account = item.get("account") 36 | created_at = item.get("date") 37 | all_values.append((hash_to_verify, key, account, created_at)) 38 | 39 | # Batch insert into 'blocks' table 40 | try: 41 | cursor.executemany(""" 42 | REPLACE INTO blocks (hash_to_verify, key, account, created_at) 43 | VALUES (?, ?, ?, ?) 44 | """, all_values) 45 | conn.commit() 46 | except sqlite3.IntegrityError as e: 47 | print(f"Integrity Error: {e}") 48 | except Exception as e: 49 | print(f"An error occurred: {e}") 50 | 51 | print(f"Processed {len(all_values)} records.") 52 | 53 | # Close the database connection 54 | conn.close() 55 | -------------------------------------------------------------------------------- /indexing/block_rate_per_account.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import time 3 | import threading 4 | 5 | DATABASE_NAME = "blocks.db" # Update this with your SQLite database name 6 | 7 | def populate_account_block_counts(): 8 | # Establish a connection to the SQLite3 database 9 | with sqlite3.connect(DATABASE_NAME) as conn: 10 | c = conn.cursor() 11 | 12 | # Drop the AccountBlockCounts table if it exists 13 | c.execute('DROP TABLE IF EXISTS AccountBlockCounts') 14 | 15 | # Create the AccountBlockCounts table 16 | c.execute(''' 17 | CREATE TABLE AccountBlockCounts ( 18 | account TEXT NOT NULL, 19 | num_blocks INTEGER NOT NULL 20 | ) 21 | ''') 22 | 23 | # Use a temporary table to filter the last 24 hours' records 24 | c.execute(''' 25 | WITH Last24HourBlocks AS ( 26 | SELECT 27 | account, 28 | created_at 29 | FROM 30 | blocks 31 | WHERE 32 | created_at >= datetime('now', '-1 day') 33 | ) 34 | INSERT INTO AccountBlockCounts (account, num_blocks) 35 | SELECT 36 | account, 37 | COUNT(*) as num_blocks 38 | FROM 39 | Last24HourBlocks 40 | GROUP BY 41 | account 42 | ORDER BY 43 | num_blocks DESC 44 | ''') 45 | 46 | # Commit the transaction 47 | conn.commit() 48 | 49 | print("Records successfully inserted into AccountBlockCounts!") 50 | 51 | def continuous_population(): 52 | while True: 53 | print("Populating AccountBlockCounts...") 54 | populate_account_block_counts() 55 | time.sleep(300) # sleep for 5 minutes 56 | 57 | if __name__ == "__main__": 58 | thread = threading.Thread(target=continuous_population) 59 | thread.start() 60 | thread.join() # Optional, if you want the main thread to wait for the spawned thread. 61 | 62 | -------------------------------------------------------------------------------- /indexing/check_rate.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from datetime import datetime 3 | 4 | def compute_avg_rows_per_minute(db_path): 5 | # Connect to the SQLite database 6 | conn = sqlite3.connect(db_path) 7 | cursor = conn.cursor() 8 | 9 | # Fetch the last 600 records sorted by created_at 10 | cursor.execute("SELECT created_at FROM blocks ORDER BY block_id DESC LIMIT 600") 11 | records = cursor.fetchall() 12 | 13 | if len(records) < 2: # Not enough data to calculate average 14 | print("Not enough data to calculate average rows per minute.") 15 | return 16 | 17 | # Convert datetime strings to Python datetime objects 18 | newest_time = datetime.strptime(records[0][0], "%Y-%m-%d %H:%M:%S") 19 | oldest_time = datetime.strptime(records[-1][0], "%Y-%m-%d %H:%M:%S") 20 | 21 | # Calculate time difference in minutes 22 | time_difference = (newest_time - oldest_time).total_seconds() / 60.0 23 | 24 | # Calculate average rows per minute 25 | avg_rows_per_minute = int(len(records) / time_difference) 26 | 27 | print(f"Average rows per minute: {avg_rows_per_minute}") 28 | 29 | # Example usage 30 | db_path = "blocks.db" # Replace with the path to your SQLite database file 31 | compute_avg_rows_per_minute(db_path) 32 | 33 | -------------------------------------------------------------------------------- /indexing/check_seq.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | # Database connection 4 | DATABASE_NAME = "blocks.db" 5 | conn = sqlite3.connect(DATABASE_NAME) 6 | cursor = conn.cursor() 7 | 8 | cursor.execute("SELECT block_id FROM blocks WHERE block_id > 1004217 ORDER BY block_id ASC") 9 | block_ids = [row[0] for row in cursor.fetchall()] 10 | 11 | # Now, verify the sequence 12 | is_sequence_correct = True 13 | for i in range(1, len(block_ids)): 14 | if block_ids[i] - block_ids[i-1] != 1: 15 | print(f"Sequence broken between {block_ids[i-1]} and {block_ids[i]}") 16 | is_sequence_correct = False 17 | break 18 | 19 | if is_sequence_correct: 20 | print("All block_ids are in sequence!") 21 | else: 22 | print("block_ids are not in perfect sequence.") 23 | 24 | conn.close() 25 | 26 | -------------------------------------------------------------------------------- /indexing/count_consensus.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | def get_distinct_eth_addresses_with_same_last_block_id(db_path): 4 | # Connect to the SQLite database 5 | conn = sqlite3.connect(db_path) 6 | cursor = conn.cursor() 7 | 8 | # Execute the SQL query 9 | query = ''' 10 | SELECT my_ethereum_address, last_block_id, COUNT(id) AS m 11 | FROM consensus 12 | GROUP BY my_ethereum_address, last_block_id 13 | HAVING m > 1 14 | ''' 15 | 16 | cursor.execute(query) 17 | 18 | # Fetch all the records 19 | records = cursor.fetchall() 20 | 21 | # Close the database connection 22 | conn.close() 23 | 24 | # Create a set to hold distinct Ethereum addresses 25 | distinct_eth_addresses = set() 26 | 27 | # Extract distinct Ethereum addresses from the records 28 | for record in records: 29 | distinct_eth_addresses.add(record[0]) 30 | 31 | # Report the number of distinct Ethereum addresses 32 | print(f"Number of distinct my_ethereum_address records with the same last_block_id: {len(distinct_eth_addresses)}") 33 | 34 | # Path to your SQLite database 35 | db_path = 'blocks.db' 36 | 37 | # Run the function 38 | get_distinct_eth_addresses_with_same_last_block_id(db_path) 39 | 40 | -------------------------------------------------------------------------------- /indexing/count_miners.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import subprocess 3 | import sqlite3 4 | from datetime import datetime 5 | 6 | def count_miners_and_insert_into_db(): 7 | # Run shell commands to count the number of unique miners 8 | try: 9 | cmd = "tail -500000 access.log | grep verify | cut -d' ' -f1 | sort | uniq | wc -l" 10 | total_miners = subprocess.getoutput(cmd) 11 | total_miners = int(total_miners.strip()) # Convert the output to an integer 12 | 13 | # Connect to the difficulty database 14 | conn = sqlite3.connect('difficulty.db') 15 | cursor = conn.cursor() 16 | 17 | # Create the miners table if it doesn't exist 18 | cursor.execute(''' 19 | CREATE TABLE IF NOT EXISTS miners ( 20 | id INTEGER PRIMARY KEY AUTOINCREMENT, 21 | date DATETIME DEFAULT CURRENT_TIMESTAMP, 22 | total_miners INTEGER 23 | ); 24 | ''') 25 | 26 | # Insert the count into the miners table 27 | cursor.execute("INSERT INTO miners (total_miners) VALUES (?)", (total_miners,)) 28 | conn.commit() 29 | 30 | # Close the database connection 31 | conn.close() 32 | 33 | print(f"Inserted {total_miners} into the database at {datetime.now()}") 34 | except Exception as e: 35 | print(f"An error occurred: {e}") 36 | 37 | # Set up a timer to run the function every 60 seconds 38 | def start_timer(): 39 | threading.Timer(60.0, start_timer).start() 40 | count_miners_and_insert_into_db() 41 | 42 | # Start the timer 43 | start_timer() 44 | 45 | -------------------------------------------------------------------------------- /indexing/getblocks.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify 2 | from flask_caching import Cache 3 | import sqlite3 4 | 5 | app = Flask(__name__) 6 | 7 | @app.route('/getblocks/lastblock', methods=['GET']) 8 | def get_last_block(): 9 | conn = sqlite3.connect('blocks.db', timeout=10) 10 | c = conn.cursor() 11 | 12 | # Get the last ID in the table 13 | c.execute("SELECT MAX(block_id) FROM blocks") 14 | last_id = c.fetchone()[0] 15 | 16 | last_full_page_id = (last_id // 100) * 100 # Last full page of 100 records 17 | 18 | if last_id % 100 == 0: 19 | offset = last_full_page_id # If exactly divisible, get the last full page 20 | else: 21 | offset = last_full_page_id - 100 # Otherwise go to the previous full page 22 | 23 | # Fetch the last or previous 100 records based on the offset 24 | c.execute("SELECT * FROM blocks WHERE block_id > ? ORDER BY block_id ASC LIMIT 100", (offset,)) 25 | rows = c.fetchall() 26 | 27 | conn.close() 28 | 29 | # Convert fetched rows into a list of dictionaries 30 | records = [] 31 | for row in rows: 32 | record = { 33 | 'block_id': row[0], 34 | 'hash_to_verify': row[1], 35 | 'key': row[2], 36 | 'account': row[3], 37 | 'date': row[4] 38 | } 39 | records.append(record) 40 | 41 | return jsonify(records) 42 | 43 | @app.route('/getblocks/all/', methods=['GET']) 44 | def get_combined_records(number): 45 | offset = (number - 1) * 100 # Calculate the offset based on the number input 46 | 47 | conn = sqlite3.connect('blocks.db', timeout=10) 48 | c = conn.cursor() 49 | 50 | # Fetch 100 records from the blocks table based on the offset 51 | c.execute("SELECT * FROM blocks ORDER BY block_id ASC LIMIT 100 OFFSET ?", (offset,)) 52 | block_rows = c.fetchall() 53 | 54 | combined_records = [] 55 | 56 | # Convert fetched rows from blocks table into dictionaries and append to combined_records 57 | for row in block_rows: 58 | record = { 59 | 'block_id': row[0], 60 | 'hash_to_verify': row[1], 61 | 'key': row[2], 62 | 'account': row[3], 63 | 'date': row[4] 64 | } 65 | combined_records.append(record) 66 | 67 | # Only fetch records from the xuni table if the number is 10000 or greater 68 | if number >= 1: 69 | # Fetch 100 records from the xuni table based on the offset 70 | c.execute("SELECT * FROM xuni ORDER BY Id ASC LIMIT 100 OFFSET ?", (offset,)) 71 | xuni_rows = c.fetchall() 72 | 73 | # Convert fetched rows from xuni table into dictionaries and append to combined_records 74 | for row in xuni_rows: 75 | record = { 76 | 'xuni_id': row[0], 77 | 'hash_to_verify': row[1], 78 | 'key': row[2], 79 | 'account': row[3], 80 | 'date': row[4] 81 | } 82 | combined_records.append(record) 83 | 84 | conn.close() 85 | return jsonify(combined_records) 86 | 87 | 88 | @app.route('/getblocks/', methods=['GET']) 89 | def get_records(page): 90 | offset = (page - 1) * 100 # Calculate the offset 91 | 92 | conn = sqlite3.connect('blocks.db', timeout=10) 93 | c = conn.cursor() 94 | 95 | # Fetch 100 records based on the page number 96 | c.execute("SELECT * FROM blocks LIMIT 100 OFFSET ?", (offset,)) 97 | rows = c.fetchall() 98 | 99 | conn.close() 100 | 101 | # Convert fetched rows into a list of dictionaries 102 | records = [] 103 | for row in rows: 104 | record = { 105 | 'block_id': row[0], 106 | 'hash_to_verify': row[1], 107 | 'key': row[2], 108 | 'account': row[3], 109 | 'date': row[4] 110 | } 111 | records.append(record) 112 | 113 | return jsonify(records) 114 | 115 | -------------------------------------------------------------------------------- /indexing/make_superblocks.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sqlite3 3 | import threading 4 | import time 5 | from collections import defaultdict 6 | 7 | def run_db_operations(): 8 | max_retries = 3 9 | for i in range(max_retries): 10 | try: 11 | # Connect to SQLite database 12 | conn = sqlite3.connect('blocks.db', timeout=10) # 10 seconds timeout 13 | cursor = conn.cursor() 14 | 15 | # Drop super_blocks table if it exists 16 | cursor.execute("DROP TABLE IF EXISTS super_blocks") 17 | 18 | # Create the table 19 | cursor.execute(""" 20 | CREATE TABLE super_blocks ( 21 | account TEXT PRIMARY KEY, 22 | super_block_count INTEGER 23 | ); 24 | """) 25 | 26 | # Fetch all hash_to_verify and account records from blocks table 27 | cursor.execute("SELECT hash_to_verify, account FROM blocks;") 28 | rows = cursor.fetchall() 29 | 30 | # Prepare a dictionary to keep counts 31 | super_block_counts = defaultdict(int) 32 | 33 | for row in rows: 34 | hash_to_verify, account_to_update = row 35 | capital_count = sum(1 for char in re.sub('[0-9]', '', hash_to_verify) if char.isupper()) 36 | 37 | if capital_count >= 65: 38 | super_block_counts[account_to_update] += 1 39 | 40 | # Insert all rows in one go 41 | cursor.executemany(""" 42 | INSERT INTO super_blocks (account, super_block_count) 43 | VALUES (?, ?); 44 | """, super_block_counts.items()) 45 | 46 | # Commit the changes to the database 47 | conn.commit() 48 | 49 | # Close the connection 50 | conn.close() 51 | 52 | # If successful, break the retry loop 53 | break 54 | except sqlite3.OperationalError: 55 | print(f"Database is locked, retrying {i+1}/{max_retries}") 56 | time.sleep(1) # wait for 1 second before retrying 57 | 58 | # Schedule the next run 59 | threading.Timer(300, run_db_operations).start() 60 | 61 | # Kick off the first run 62 | run_db_operations() 63 | 64 | -------------------------------------------------------------------------------- /indexing/manage_difficulty.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import threading 3 | 4 | def adjust_difficulty(): 5 | # Connect to the difficulty database 6 | diff_conn = sqlite3.connect('difficulty.db', timeout=10) 7 | diff_c = diff_conn.cursor() 8 | 9 | # Get the latest rate from blockrate table 10 | diff_c.execute("SELECT rate FROM blockrate ORDER BY id DESC LIMIT 1") 11 | latest_rate = diff_c.fetchone() 12 | if latest_rate: 13 | latest_rate = latest_rate[0] 14 | print(f"Latest rate is {latest_rate}") 15 | else: 16 | print("No rate found") 17 | return 18 | 19 | # Get the current level of difficulty 20 | diff_c.execute("SELECT level FROM difficulty WHERE id=1") 21 | current_level = diff_c.fetchone() 22 | if current_level: 23 | current_level = current_level[0] 24 | print(f"Current difficulty level is {current_level}") 25 | else: 26 | print("No difficulty level found") 27 | return 28 | 29 | # Check if the latest rate deviates by 20% from 60 30 | threshold = 60 * 0.2 # 20% of 60 31 | lower_limit = 60 - threshold 32 | upper_limit = 60 + threshold 33 | 34 | if latest_rate < lower_limit or latest_rate > upper_limit: 35 | # Update the level based on the latest rate 36 | new_level = current_level + 100 if latest_rate > upper_limit else current_level - 100 37 | 38 | # Update the difficulty level in the database 39 | diff_c.execute("UPDATE difficulty SET level = ? WHERE id=1", (new_level,)) 40 | diff_conn.commit() 41 | print(f"Difficulty level updated to {new_level}") 42 | 43 | # Close the connection to the database 44 | diff_conn.close() 45 | 46 | # Schedule the next check 47 | threading.Timer(300, adjust_difficulty).start() 48 | 49 | # Initial call to start the loop and reporting 50 | print("Starting the script...") 51 | adjust_difficulty() 52 | 53 | -------------------------------------------------------------------------------- /indexing/merkleroot.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify 2 | import sqlite3 3 | 4 | app = Flask(__name__) 5 | 6 | DATABASE_NAME = "xenminer.db" 7 | 8 | def init_db(): 9 | with sqlite3.connect(DATABASE_NAME) as conn: 10 | c = conn.cursor() 11 | 12 | @app.route('/send_pow', methods=['POST']) 13 | def send_pow(): 14 | data = request.get_json() 15 | 16 | account_address = data.get('account_address') 17 | block_id = data.get('block_id') 18 | merkle_root = data.get('merkle_root') 19 | key = data.get('key') 20 | hash_to_verify = data.get('hash_to_verify') 21 | 22 | if not all([account_address, block_id, merkle_root, key, hash_to_verify]): 23 | return jsonify({"message": "Invalid payload"}), 400 24 | 25 | try: 26 | with sqlite3.connect(DATABASE_NAME) as conn: 27 | c = conn.cursor() 28 | c.execute("REPLACE INTO merkleroot2 (block_id, merkleroot_hash, account, key, hash_to_verify) VALUES (?, ?, ?, ?, ?)", 29 | (block_id, merkle_root, account_address, key, hash_to_verify)) 30 | conn.commit() 31 | return jsonify({"message": "POW Record stored successfully!"}), 200 32 | 33 | except Exception as e: 34 | return jsonify({"message": str(e)}), 500 35 | 36 | if __name__ == '__main__': 37 | init_db() 38 | app.run(debug=True) 39 | 40 | -------------------------------------------------------------------------------- /indexing/rate_daemon.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import threading 3 | from datetime import datetime 4 | 5 | def compute_avg_rows_per_minute_and_store(): 6 | # Connect to the blocks database 7 | conn_blocks = sqlite3.connect('blocks.db') 8 | cursor_blocks = conn_blocks.cursor() 9 | 10 | # Connect to the difficulty database 11 | conn_diff = sqlite3.connect('difficulty.db') 12 | cursor_diff = conn_diff.cursor() 13 | 14 | # Create the blockrate table if it doesn't exist 15 | cursor_diff.execute(''' 16 | CREATE TABLE IF NOT EXISTS blockrate ( 17 | id INTEGER PRIMARY KEY AUTOINCREMENT, 18 | date DATETIME DEFAULT CURRENT_TIMESTAMP, 19 | rate INTEGER 20 | ); 21 | ''') 22 | conn_diff.commit() 23 | 24 | # Fetch the last 600 records from the blocks table 25 | cursor_blocks.execute("SELECT created_at FROM blocks ORDER BY block_id DESC LIMIT 300") 26 | records = cursor_blocks.fetchall() 27 | 28 | if len(records) < 2: 29 | print("Not enough data to calculate average rows per minute.") 30 | return 31 | 32 | # Convert datetime strings to Python datetime objects 33 | newest_time = datetime.strptime(records[0][0], "%Y-%m-%d %H:%M:%S") 34 | oldest_time = datetime.strptime(records[-1][0], "%Y-%m-%d %H:%M:%S") 35 | 36 | # Calculate time difference in minutes 37 | time_difference = (newest_time - oldest_time).total_seconds() / 60.0 38 | 39 | # Calculate average rows per minute and round it to an integer 40 | avg_rows_per_minute = int(round(len(records) / time_difference)) 41 | 42 | # Insert the calculated rate into the blockrate table in the difficulty database 43 | cursor_diff.execute("INSERT INTO blockrate (rate) VALUES (?)", (avg_rows_per_minute,)) 44 | conn_diff.commit() 45 | 46 | # Close database connections 47 | conn_blocks.close() 48 | conn_diff.close() 49 | 50 | # Log the inserted rate 51 | print(f"Inserted rate: {avg_rows_per_minute}") 52 | 53 | # Set up a timer to run the function every minute 54 | def start_timer(): 55 | threading.Timer(60.0, start_timer).start() 56 | compute_avg_rows_per_minute_and_store() 57 | 58 | # Start the timer 59 | start_timer() 60 | 61 | -------------------------------------------------------------------------------- /make_cache.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import os 3 | import shutil 4 | import time 5 | 6 | 7 | def recreate_cache_table(): 8 | while True: # Run indefinitely 9 | try: 10 | # Copy the original database to /tmp directory 11 | original_db_path = "blocks.db" 12 | tmp_db_path = "/tmp/blocks_copy.db" 13 | #shutil.copy(original_db_path, tmp_db_path) 14 | 15 | # Connect to the copied and cache databases 16 | original_conn = sqlite3.connect(original_db_path) 17 | cache_conn = sqlite3.connect("cache.db") 18 | # Connect to the original and cache databases 19 | #original_conn = sqlite3.connect("blocks.db") 20 | #cache_conn = sqlite3.connect("cache.db") 21 | 22 | # Create cursors for each database 23 | original_cursor = original_conn.cursor() 24 | cache_cursor = cache_conn.cursor() 25 | 26 | # Drop the existing cache table if it exists 27 | # cache_cursor.execute("DROP TABLE IF EXISTS cache_table") 28 | 29 | # Create the new cache table 30 | cache_cursor.execute(""" 31 | CREATE TABLE IF NOT EXISTS cache_table ( 32 | account TEXT PRIMARY KEY, 33 | total_blocks INTEGER, 34 | hashes_per_second REAL, 35 | super_blocks INTEGER 36 | )""") 37 | cache_conn.commit() 38 | 39 | # Fetch data from the original database and populate the cache table 40 | original_cursor.execute(""" 41 | SELECT b.account, 42 | COUNT(b.block_id) AS total_blocks, 43 | 100000 AS hashes_per_second, -- static value of 100000 for hashes_per_second 44 | COALESCE(sb.super_block_count, 0) AS super_blocks 45 | FROM blocks b 46 | LEFT JOIN (SELECT account, super_block_count FROM super_blocks) sb ON b.account = sb.account 47 | GROUP BY b.account 48 | ORDER BY total_blocks DESC 49 | """) 50 | 51 | rows = original_cursor.fetchall() 52 | num_rows_fetched = len(rows) # Get the number of rows fetched 53 | 54 | # Insert fetched rows into the cache table 55 | cache_cursor.executemany("REPLACE INTO cache_table (account, total_blocks, hashes_per_second, super_blocks) VALUES (?, ?, ?, ?)", rows) 56 | cache_conn.commit() 57 | 58 | 59 | # Close the database connections 60 | original_conn.close() 61 | cache_conn.close() 62 | print(f"Cache table updated. {num_rows_fetched} rows were fetched and inserted.") 63 | 64 | # Wait for 5 minutes before the next iteration 65 | time.sleep(300) 66 | 67 | except sqlite3.OperationalError as e: 68 | print(f"SQLite error: {e}. Retrying in 5 seconds.") 69 | time.sleep(5) # Wait for 5 seconds before retrying 70 | 71 | if __name__ == "__main__": 72 | recreate_cache_table() 73 | 74 | -------------------------------------------------------------------------------- /make_superblocks.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sqlite3 3 | import threading 4 | import time 5 | from collections import defaultdict 6 | 7 | def run_db_operations(): 8 | max_retries = 3 9 | for i in range(max_retries): 10 | try: 11 | # Connect to SQLite database 12 | conn = sqlite3.connect('blocks.db', timeout=10) # 10 seconds timeout 13 | cursor = conn.cursor() 14 | 15 | # Drop super_blocks table if it exists 16 | cursor.execute("DROP TABLE IF EXISTS super_blocks") 17 | 18 | # Create the table 19 | cursor.execute(""" 20 | CREATE TABLE super_blocks ( 21 | account TEXT PRIMARY KEY, 22 | super_block_count INTEGER 23 | ); 24 | """) 25 | 26 | # Fetch all hash_to_verify and account records from blocks table 27 | cursor.execute("SELECT hash_to_verify, account FROM blocks;") 28 | rows = cursor.fetchall() 29 | 30 | # Prepare a dictionary to keep counts 31 | super_block_counts = defaultdict(int) 32 | 33 | for row in rows: 34 | hash_to_verify, account_to_update = row 35 | last_element = hash_to_verify.split("$")[-1] 36 | hash_uppercase_only = ''.join(filter(str.isupper, last_element)) 37 | capital_count = len(hash_uppercase_only) 38 | #capital_count = sum(1 for char in re.sub('[0-9]', '', hash_to_verify) if char.isupper()) 39 | 40 | if capital_count >= 50: 41 | super_block_counts[account_to_update] += 1 42 | 43 | # Insert all rows in one go 44 | cursor.executemany(""" 45 | INSERT INTO super_blocks (account, super_block_count) 46 | VALUES (?, ?); 47 | """, super_block_counts.items()) 48 | 49 | # Commit the changes to the database 50 | conn.commit() 51 | 52 | # Close the connection 53 | conn.close() 54 | 55 | # If successful, break the retry loop 56 | break 57 | except sqlite3.OperationalError: 58 | print(f"Database is locked, retrying {i+1}/{max_retries}") 59 | time.sleep(1) # wait for 1 second before retrying 60 | 61 | # Schedule the next run 62 | threading.Timer(300, run_db_operations).start() 63 | 64 | # Kick off the first run 65 | run_db_operations() 66 | -------------------------------------------------------------------------------- /merkleroot.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import hashlib 4 | import argparse 5 | from passlib.hash import argon2 6 | 7 | def hash_value(value): 8 | return hashlib.sha256(value.encode()).hexdigest() 9 | 10 | def build_merkle_tree(elements, merkle_tree={}): 11 | if len(elements) == 1: 12 | return elements[0], merkle_tree 13 | 14 | new_elements = [] 15 | for i in range(0, len(elements), 2): 16 | left = elements[i] 17 | right = elements[i + 1] if i + 1 < len(elements) else left 18 | combined = left + right 19 | new_hash = hash_value(combined) 20 | merkle_tree[new_hash] = {'left': left, 'right': right} 21 | new_elements.append(new_hash) 22 | return build_merkle_tree(new_elements, merkle_tree) 23 | 24 | # Argument parser for command line arguments 25 | parser = argparse.ArgumentParser(description='XenMiner PoW submission') 26 | parser.add_argument('account_address', type=str, help='The account address (like 0x...) for submitting the PoW') 27 | args = parser.parse_args() 28 | account_address = args.account_address 29 | 30 | # Download last block record 31 | url = 'http://xenminer.mooo.com:4445/getblocks/lastblock' 32 | response = requests.get(url) 33 | 34 | if response.status_code == 200: 35 | records = json.loads(response.text) 36 | 37 | verified_hashes = [] 38 | for record in records: 39 | block_id = record.get('block_id') 40 | hash_to_verify = record.get('hash_to_verify') 41 | key = record.get('key') 42 | account = record.get('account') 43 | 44 | # Verify each record using Argon2 45 | if argon2.verify(key, hash_to_verify): 46 | verified_hashes.append(hash_value(str(block_id) + hash_to_verify + key + account)) 47 | 48 | # If we have any verified hashes, build the Merkle root 49 | if verified_hashes: 50 | merkle_root, _ = build_merkle_tree(verified_hashes) 51 | 52 | # Calculate block ID for output (using the last record for reference) 53 | output_block_id = int(block_id / 100) 54 | 55 | # Prepare payload for PoW 56 | payload = { 57 | 'account_address': account_address, 58 | 'block_id': output_block_id, 59 | 'merkle_root': merkle_root 60 | } 61 | 62 | # Send POST request 63 | pow_response = requests.post('http://xenminer.mooo.com:4446/send_pow', json=payload) 64 | 65 | if pow_response.status_code == 200: 66 | print(f"Proof of Work successful: {pow_response.json()}") 67 | else: 68 | print(f"Proof of Work failed: {pow_response.json()}") 69 | 70 | print(f"Block ID: {output_block_id}, Merkle Root: {merkle_root}") 71 | 72 | else: 73 | print("Failed to fetch the last block.") 74 | 75 | -------------------------------------------------------------------------------- /miner.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then 4 | echo "Error: Windows is not supported yet." 5 | read 6 | exit -1 7 | fi 8 | 9 | dev_fee_on=false 10 | logging_on=false 11 | opencl=false 12 | silence=false 13 | gpus=0 14 | cpu=false 15 | 16 | function display_help() { 17 | echo "Usage: $0 [OPTIONS]" 18 | echo 19 | echo "Options:" 20 | echo " -g, --gpus Set the number of GPUs to use (Default: 1)" 21 | echo " -c, --cpu Running 1 miner in CPU mode (Default: off)" 22 | echo " -d, --devfee, --dev-fee-on Enable dev fee (Default: off)" 23 | echo " -o, --opencl Enable OpenCL computation (Default: off)" 24 | echo " -s, --silence Run in silence/background mode (Default: off)" 25 | echo " -l, --logging-on Record verified blocks into payload.log file (Default: off)" 26 | echo " -h, --help Display this help message and exit" 27 | echo 28 | echo "Note: Script exits if both GPU and CPU modes are off." 29 | exit 0 30 | } 31 | # Process long options 32 | for arg in "$@"; do 33 | shift 34 | case "$arg" in 35 | "--help") set -- "$@" "-h" ;; 36 | "--opencl") set -- "$@" "-o" ;; 37 | "--dev-fee-on") set -- "$@" "-d" ;; 38 | "--devfee") set -- "$@" "-d" ;; 39 | "--silence") set -- "$@" "-s" ;; 40 | "--gpus") set -- "$@" "-g" ;; 41 | "--cpu") set -- "$@" "-c" ;; 42 | "--logging-on") set -- "$@" "-l" ;; 43 | *) set -- "$@" "$arg" 44 | esac 45 | done 46 | 47 | # Now, process short options with getopts 48 | while getopts "g:c:ldosh" opt; do 49 | case "$opt" in 50 | g) gpus="$OPTARG" ;; 51 | c) cpu="$OPTARG" ;; 52 | d) dev_fee_on=true ;; 53 | o) opencl=true ;; 54 | s) silence=true ;; 55 | l) logging_on=true ;; 56 | h) display_help ;; 57 | *) echo "Invalid option: -$OPTARG" >&2; exit 1 ;; 58 | esac 59 | done 60 | 61 | # cpu mode 62 | if [ $cpu -gt 0 ]; then 63 | echo "Running $cpu miner in CPU mode..." 64 | 65 | command="./xengpuminer -m cpu" 66 | for ((i = 0; i < $cpu; i++)); do 67 | if [ $i -eq 0 ]; then 68 | screen -S "cpuminer" -dm bash -c "$command" 69 | else 70 | screen -S "cpuminer" -X screen bash -c "$command" 71 | fi 72 | done 73 | fi 74 | 75 | # gpu mode 76 | if [[ $gpus -lt 1 && $cpu -lt 1 ]]; then 77 | echo "Error: Neither gpu nor cpu mode is selected." 78 | exit -1 79 | fi 80 | for ((i = 0; i < $gpus; i++)); do 81 | command="./xengpuminer -d $i" 82 | if $opencl; then 83 | command+=" -m opencl" 84 | fi 85 | if [ $i -eq 0 ]; then 86 | screen -S "gpuminer" -dm bash -c "$command" 87 | else 88 | screen -S "gpuminer" -X screen bash -c "$command" 89 | fi 90 | done 91 | if [ $gpus -gt 0 ]; then 92 | echo "Running $gpus miners in GPU mode..." 93 | fi 94 | command="python3 miner.py" 95 | if $dev_fee_on; then 96 | command+=" --dev-fee-on" 97 | fi 98 | if $logging_on; then 99 | command+=" --logging-on" 100 | fi 101 | if $silence; then 102 | screen -S submitminer -dm bash -c "$command" 103 | echo "If you want to stop, run: pkill xengpuminer && pkill -f submitminer. or simply use pkill -f miner" 104 | else 105 | bash -c "$command" 106 | pkill -f "submitminer" 107 | pkill gpuminer 108 | fi 109 | -------------------------------------------------------------------------------- /p2pnode/mtree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | ) 7 | 8 | type MerkleNode struct { 9 | Left string 10 | Right string 11 | } 12 | 13 | func hashValue(data string) string { 14 | hash := sha256.Sum256([]byte(data)) 15 | return hex.EncodeToString(hash[:]) 16 | } 17 | 18 | func buildMerkleTree(elements []string, merkleTree map[string]MerkleNode) (string, map[string]MerkleNode) { 19 | if len(elements) == 1 { 20 | return elements[0], merkleTree 21 | } 22 | 23 | var newElements []string 24 | for i := 0; i < len(elements); i += 2 { 25 | left := elements[i] 26 | right := left 27 | if i+1 < len(elements) { 28 | right = elements[i+1] 29 | } 30 | 31 | combined := left + right 32 | newHash := hashValue(combined) 33 | merkleTree[newHash] = MerkleNode{Left: left, Right: right} 34 | newElements = append(newElements, newHash) 35 | } 36 | return buildMerkleTree(newElements, merkleTree) 37 | } 38 | -------------------------------------------------------------------------------- /p2pnode/node.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "slices" 5 | ) 6 | 7 | const ( 8 | SupernodeRole = "supernode" 9 | RelayRole = "relay" 10 | MinerRole = "miner" 11 | ValidatorRole = "validator" 12 | BootstrapRole = "bootstrap" 13 | RpcRole = "rpc" 14 | ) 15 | 16 | var supportedRoles = []string{ 17 | SupernodeRole, 18 | RelayRole, 19 | MinerRole, 20 | ValidatorRole, 21 | BootstrapRole, 22 | RpcRole, 23 | } 24 | 25 | type Node struct { 26 | roles []string 27 | } 28 | 29 | func (n Node) isSupernode() bool { 30 | return slices.Contains(n.roles, SupernodeRole) 31 | } 32 | 33 | func (n Node) isRelay() bool { 34 | return slices.Contains(n.roles, RelayRole) 35 | } 36 | 37 | func (n Node) isMiner() bool { 38 | return slices.Contains(n.roles, MinerRole) 39 | } 40 | 41 | func (n Node) isValidator() bool { 42 | return slices.Contains(n.roles, ValidatorRole) 43 | } 44 | 45 | func (n Node) isBootstrap() bool { 46 | return slices.Contains(n.roles, BootstrapRole) 47 | } 48 | 49 | func (n Node) isRpc() bool { 50 | return slices.Contains(n.roles, RpcRole) 51 | } 52 | -------------------------------------------------------------------------------- /p2pnode/rpc.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "github.com/gofiber/fiber/v2" 7 | log0 "github.com/ipfs/go-log/v2" 8 | dht "github.com/libp2p/go-libp2p-kad-dht" 9 | "github.com/libp2p/go-libp2p-kbucket" 10 | pubsub "github.com/libp2p/go-libp2p-pubsub" 11 | "github.com/libp2p/go-libp2p/core/host" 12 | "github.com/libp2p/go-libp2p/core/peer" 13 | ) 14 | 15 | func rpcServer(ctx context.Context, peers []*peer.AddrInfo) { 16 | peerId := ctx.Value("peerId").(string) 17 | h := ctx.Value("host").(host.Host) 18 | ps := ctx.Value("pubsub").(*pubsub.PubSub) 19 | dhTable := ctx.Value("dht").(*dht.IpfsDHT) 20 | logger := ctx.Value("logger").(log0.EventLogger) 21 | 22 | app := fiber.New() 23 | 24 | app.Get("/status", func(c *fiber.Ctx) error { 25 | nodes := h.Peerstore().Peers() 26 | res, _ := json.Marshal(nodes) 27 | return c.SendString(string(res[:])) 28 | }) 29 | 30 | app.Get("/pubsub/:topic", func(c *fiber.Ctx) error { 31 | nodes := ps.ListPeers(c.Params("topic")) 32 | res, _ := json.Marshal(nodes) 33 | return c.SendString(string(res[:])) 34 | }) 35 | 36 | /* 37 | app.Get("/dht/crawl", func(c *fiber.Ctx) error { 38 | cr, _ := crawler.NewDefaultCrawler(h) 39 | cr.Run(ctx, peers, 40 | func(p peer.ID, rtPeers []*peer.AddrInfo) { 41 | logger.Info("crawl", p, rtPeers) 42 | res, _ := json.Marshal(rtPeers) 43 | c.SendString(string(res[:])) 44 | }, 45 | func(p peer.ID, err error) { 46 | logger.Warn(err) 47 | c.SendString("error") 48 | }) 49 | time.Sleep(10 * time.Second) 50 | return c.SendString("OK") 51 | }) 52 | 53 | */ 54 | 55 | app.Get("/dht", func(c *fiber.Ctx) error { 56 | nodes := dhTable.RoutingTable().ListPeers() 57 | id, _ := peer.Decode(peerId) 58 | nearest := dhTable.RoutingTable().NearestPeers(kbucket.ConvertPeerID(id), 3) 59 | var dhtStatus = map[string]any{"peers": nodes, "nearest": nearest} 60 | res, _ := json.Marshal(dhtStatus) 61 | return c.SendString(string(res[:])) 62 | }) 63 | 64 | err := app.Listen(":3333") 65 | if err != nil { 66 | logger.Warn("Error in RPC: ", err) 67 | } else { 68 | logger.Info("RPC is active") 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /ptrie_unittest.py: -------------------------------------------------------------------------------- 1 | from trie import HexaryTrie 2 | 3 | class AccountManager: 4 | def __init__(self): 5 | # Initializing a blank trie 6 | self.trie = HexaryTrie(db={}) 7 | self.block_data = {} # To store root hash of trie for each block 8 | 9 | def set_balance(self, account, block, amount): 10 | self.trie[account.encode()] = str(amount).encode() 11 | # Save the root hash of the trie for the given block 12 | self.block_data[block] = self.trie.root_hash 13 | 14 | def get_balance(self, account, block): 15 | root = self.block_data.get(block) 16 | if not root: 17 | return None 18 | # Set the trie's root hash to the one from the desired block 19 | self.trie.root_hash = root 20 | return int(self.trie[account.encode()].decode()) 21 | 22 | def credit(self, account, block, amount): 23 | curr_balance = self.get_balance(account, block-1) or 0 24 | self.set_balance(account, block, curr_balance + amount) 25 | 26 | def debit(self, account, block, amount): 27 | curr_balance = self.get_balance(account, block-1) or 0 28 | if curr_balance < amount: 29 | raise ValueError("Insufficient balance") 30 | self.set_balance(account, block, curr_balance - amount) 31 | 32 | if __name__ == "__main__": 33 | manager = AccountManager() 34 | 35 | # Test setting initial balance 36 | manager.set_balance('0xSomeAccount', 1, 100) 37 | assert manager.get_balance('0xSomeAccount', 1) == 100 38 | 39 | # Test crediting an account 40 | manager.credit('0xSomeAccount', 2, 50) 41 | assert manager.get_balance('0xSomeAccount', 1) == 100 42 | assert manager.get_balance('0xSomeAccount', 2) == 150 43 | 44 | # Test debiting an account 45 | manager.debit('0xSomeAccount', 3, 30) 46 | assert manager.get_balance('0xSomeAccount', 1) == 100 47 | assert manager.get_balance('0xSomeAccount', 2) == 150 48 | assert manager.get_balance('0xSomeAccount', 3) == 120 49 | 50 | print("All tests passed!") 51 | 52 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | passlib 2 | requests 3 | tqdm 4 | argon2_cffi 5 | web3==6.11.1 6 | -------------------------------------------------------------------------------- /tests/merkle_unittest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import hashlib 3 | 4 | def hash_value(value): 5 | return hashlib.sha256(value.encode()).hexdigest() 6 | 7 | def build_merkle_tree(elements, merkle_tree=None): 8 | if merkle_tree is None: 9 | merkle_tree = {} 10 | if len(elements) == 1: 11 | return elements[0], merkle_tree 12 | 13 | new_elements = [] 14 | for i in range(0, len(elements), 2): 15 | left = elements[i] 16 | right = elements[i + 1] if i + 1 < len(elements) else left 17 | combined = left + right 18 | new_hash = hash_value(combined) 19 | merkle_tree[new_hash] = {'left': left, 'right': right} 20 | new_elements.append(new_hash) 21 | return build_merkle_tree(new_elements, merkle_tree) 22 | 23 | class TestMerkleTreeFunctions(unittest.TestCase): 24 | 25 | def test_hash_value(self): 26 | self.assertEqual(hash_value('hello'), hashlib.sha256('hello'.encode()).hexdigest()) 27 | 28 | def test_build_merkle_tree(self): 29 | elements = ['a', 'b', 'c', 'd'] 30 | root, tree = build_merkle_tree(elements) 31 | print ("Merkleroot hash: ", root) 32 | 33 | # Test if the Merkle tree has the correct number of nodes 34 | self.assertEqual(len(tree), len(elements) - 1) 35 | 36 | # Test if the root is correct. This is a simple check and assumes 37 | # you know what the root should be for the elements ['a', 'b', 'c', 'd']. 38 | expected_root = hash_value(hash_value('a' + 'b') + hash_value('c' + 'd')) 39 | self.assertEqual(root, expected_root) 40 | 41 | # Add more tests as necessary to cover the logic of your Merkle tree construction. 42 | 43 | if __name__ == '__main__': 44 | unittest.main() 45 | 46 | -------------------------------------------------------------------------------- /utils/bench.py: -------------------------------------------------------------------------------- 1 | import rlp 2 | from eth_typing import HexStr 3 | from eth_utils import decode_hex 4 | from timeit import default_timer as timer 5 | from statistics import mean 6 | from tqdm import tqdm # new import 7 | 8 | # If you're using Ethereum transactions, you might also need the Transaction class from the 'ethereum' library. 9 | # If you haven't got 'ethereum' installed, you can install it using pip: pip install ethereum 10 | from ethereum.transactions import Transaction 11 | 12 | def benchmark_decode(raw_tx: str, num_trials: int = 1000000): 13 | # Prepare the data 14 | raw_tx_bytes = bytes.fromhex(HexStr(raw_tx[2:])) 15 | 16 | # Store each trial's execution time 17 | execution_times = [] 18 | 19 | # Using tqdm to create a progress bar for the loop 20 | for _ in tqdm(range(num_trials), desc="Decoding", unit="tx"): # wrapped range with tqdm 21 | start_time = timer() 22 | decoded_tx = rlp.decode(raw_tx_bytes, Transaction) 23 | end_time = timer() 24 | execution_times.append(end_time - start_time) 25 | 26 | return execution_times 27 | 28 | def compute_metrics(execution_times): 29 | avg_time = mean(execution_times) 30 | 31 | # Calculate transactions per second 32 | tx_per_second = 1 / avg_time if avg_time > 0 else 0 33 | 34 | return { 35 | 'avg_time': avg_time, 36 | 'tx_per_second': tx_per_second 37 | } 38 | 39 | def main(): 40 | # This is your raw Ethereum transaction. 41 | raw_tx = "0xf8ab80843b9aca00827b0c94999999cf1046e68e36e1aa2e0e07105eddd0000280b844a9059cbb000000000000000000000000f9b8dd0565b1fac5e9a142c3553f663e09444b9c000000000000000000000000000000000000000000000001236efcbcbb34000083030e2da0919b7300531a90a5e36a54d12e59cb33c2f77a3ea340f92bad063030c209bff1a059ca1d78f3ed0b017e07a6214263fb8a4433a7feff7ac4f0dbe771c1130beaf5" 42 | num_trials = 1000000 43 | raw_tx_bytes = bytes.fromhex(HexStr(raw_tx[2:])) 44 | decoded_tx = rlp.decode(raw_tx_bytes, Transaction) 45 | from_account = decoded_tx.to 46 | print(from_account.hex()) 47 | 48 | execution_times = benchmark_decode(raw_tx, num_trials) 49 | metrics = compute_metrics(execution_times) 50 | 51 | # Output the metrics 52 | print(f"\nMetrics over {num_trials} trials:") # added a newline for cleaner output 53 | print(f"Average Time: {metrics['avg_time']:.6f} seconds") 54 | print(f"Transactions per Second: {metrics['tx_per_second']:.2f}") 55 | 56 | if __name__ == "__main__": 57 | main() 58 | 59 | -------------------------------------------------------------------------------- /utils/block_rate_per_account.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import time 3 | import threading 4 | 5 | DATABASE_NAME = "blocks.db" # Update this with your SQLite database name 6 | 7 | def populate_account_block_counts(): 8 | # Establish a connection to the SQLite3 database 9 | with sqlite3.connect(DATABASE_NAME) as conn: 10 | c = conn.cursor() 11 | 12 | # Drop the AccountBlockCounts table if it exists 13 | c.execute('DROP TABLE IF EXISTS AccountBlockCounts') 14 | 15 | # Create the AccountBlockCounts table 16 | c.execute(''' 17 | CREATE TABLE AccountBlockCounts ( 18 | account TEXT NOT NULL, 19 | num_blocks INTEGER NOT NULL 20 | ) 21 | ''') 22 | 23 | # Use a temporary table to filter the last 24 hours' records 24 | c.execute(''' 25 | WITH Last24HourBlocks AS ( 26 | SELECT 27 | account, 28 | created_at 29 | FROM 30 | blocks 31 | WHERE 32 | created_at >= datetime('now', '-1 day') 33 | ) 34 | INSERT INTO AccountBlockCounts (account, num_blocks) 35 | SELECT 36 | account, 37 | COUNT(*) as num_blocks 38 | FROM 39 | Last24HourBlocks 40 | GROUP BY 41 | account 42 | ORDER BY 43 | num_blocks DESC 44 | ''') 45 | 46 | # Commit the transaction 47 | conn.commit() 48 | 49 | print("Records successfully inserted into AccountBlockCounts!") 50 | 51 | def continuous_population(): 52 | while True: 53 | print("Populating AccountBlockCounts...") 54 | populate_account_block_counts() 55 | time.sleep(300) # sleep for 5 minutes 56 | 57 | if __name__ == "__main__": 58 | thread = threading.Thread(target=continuous_population) 59 | thread.start() 60 | thread.join() # Optional, if you want the main thread to wait for the spawned thread. 61 | 62 | -------------------------------------------------------------------------------- /utils/engine.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.7.0; 3 | pragma abicoder v2; // Enable ABI coder v2 4 | 5 | contract AddressToStringMapping { 6 | struct Record { 7 | uint256 blockId; 8 | int mValue; 9 | int tValue; 10 | int pValue; 11 | bytes saltBytes; 12 | bytes key; 13 | uint8 currencyType; 14 | uint256 amount; 15 | } 16 | 17 | mapping(address => mapping(uint256 => Record)) private data; 18 | mapping(address => uint256) private recordCount; 19 | 20 | function setData(address _address, uint256 _blockId, int _mValue, int _tValue, int _pValue, bytes memory _saltBytes, bytes memory _key, uint8 _currencyType, uint256 _amount) public { 21 | Record memory newRecord = Record({ 22 | blockId: _blockId, 23 | mValue: _mValue, 24 | tValue: _tValue, 25 | pValue: _pValue, 26 | saltBytes: _saltBytes, 27 | key: _key, 28 | currencyType: _currencyType, 29 | amount: _amount 30 | }); 31 | 32 | data[_address][recordCount[_address]] = newRecord; 33 | recordCount[_address]++; 34 | } 35 | 36 | function getData(address _address, uint256 _index) public view returns (Record memory) { 37 | return data[_address][_index]; 38 | } 39 | 40 | function getRecordCount(address _address) public view returns (uint256) { 41 | return recordCount[_address]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /utils/get_super_blocks.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import json 3 | import re 4 | from collections import defaultdict 5 | 6 | def generate_superblock_report(db_path): 7 | # Connect to the SQLite database 8 | conn = sqlite3.connect(db_path) 9 | conn.row_factory = sqlite3.Row # This allows us to access columns by name 10 | cursor = conn.cursor() 11 | 12 | # Prepare a dictionary to keep counts 13 | super_blocks_per_block = defaultdict(lambda: defaultdict(int)) 14 | 15 | # Fetch the first row from the blockchain table 16 | cursor.execute("SELECT id, records_json FROM blockchain LIMIT 1;") 17 | block = cursor.fetchone() 18 | 19 | while block is not None: 20 | block_id = block['id'] 21 | records_json = block['records_json'] 22 | try: 23 | # Parse the JSON data 24 | records = json.loads(records_json) 25 | 26 | # Analyze each record for superblocks 27 | for record in records: 28 | hash_to_verify = record.get('hash_to_verify') 29 | account_to_update = record.get('account') 30 | if hash_to_verify and 'WEVOMTAwODIwMjJYRU4' in hash_to_verify and ('XEN' in hash_to_verify or 'XEN1' in hash_to_verify or 'XEN11' in hash_to_verify): 31 | capital_count = sum(1 for char in re.sub('[0-9]', '', hash_to_verify) if char.isupper()) 32 | if capital_count >= 65: 33 | #print(f"Block ID: {block_id}, Account: {account_to_update}, Hash: {hash_to_verify}") 34 | super_blocks_per_block[block_id][account_to_update] += 1 35 | except json.JSONDecodeError: 36 | print(f"Error decoding JSON for block ID: {block_id}") 37 | 38 | # Fetch the next row 39 | cursor.execute("SELECT id, records_json FROM blockchain WHERE id > ? ORDER BY id ASC LIMIT 1;", (block_id,)) 40 | block = cursor.fetchone() 41 | 42 | # Close the database connection 43 | conn.close() 44 | 45 | # Print the report 46 | for block_id, accounts in super_blocks_per_block.items(): 47 | for account, superblock_count in accounts.items(): 48 | print(f"Block ID: {block_id}, Account: {account}, Superblock Balance: {superblock_count}") 49 | 50 | # Replace 'your_database_path.db' with the path to your actual database 51 | generate_superblock_report('blockchain.db') 52 | 53 | -------------------------------------------------------------------------------- /utils/go/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "strings" 6 | "time" 7 | "strconv" 8 | "encoding/json" 9 | "crypto/sha256" 10 | "encoding/hex" 11 | "fmt" 12 | 13 | "github.com/gorilla/websocket" 14 | ) 15 | 16 | func main() { 17 | var addr = "ws://xenblocks.io:6668" 18 | c, _, err := websocket.DefaultDialer.Dial(addr, nil) 19 | if err != nil { 20 | log.Fatal("dial:", err) 21 | } 22 | defer c.Close() 23 | 24 | fmt.Println("Connected to the server!") 25 | 26 | for { 27 | _, message, err := c.ReadMessage() 28 | if err != nil { 29 | log.Println("read:", err) 30 | time.Sleep(5 * time.Second) 31 | continue 32 | } 33 | 34 | decompressedData, err := decompressData(message) 35 | if err != nil { 36 | log.Printf("decompress error: %v", err) 37 | continue 38 | } 39 | 40 | parts := strings.Split(decompressedData, "|") 41 | if len(parts) < 6 { 42 | continue // Not enough parts, skip this message 43 | } 44 | 45 | blockID := parts[0] 46 | hashToVerify := parts[1] 47 | key := parts[2] 48 | 49 | // Start the performance timer 50 | start := time.Now() 51 | var truncatedHash = "" 52 | var bool_flag = false 53 | 54 | // Perform Argon2 verification for the single block ID 55 | if verifyArgon2Hash(hashToVerify, key) { 56 | var shaHash = sha256.Sum256([]byte(hashToVerify)) 57 | // Convert the SHA256 hash to a hexadecimal string and take the first 5 characters 58 | truncatedHash = hex.EncodeToString(shaHash[:])[:5] 59 | bool_flag = true 60 | //fmt.Printf("Verification success for block ID %s\n", blockID) 61 | } else { 62 | fmt.Printf("Verification failed for block ID %s\n", blockID) 63 | continue 64 | } 65 | // Stop the performance timer and print the elapsed time 66 | elapsed := time.Since(start) 67 | elapsedInMilliseconds := elapsed / time.Millisecond 68 | timeStr := strconv.FormatInt(int64(elapsedInMilliseconds), 10) 69 | 70 | fmt.Printf("Verification time for block ID %s: %s %s\n", blockID,truncatedHash,elapsed) 71 | 72 | if bool_flag { 73 | 74 | responseData := map[string]interface{}{ 75 | "block_id": blockID, 76 | "hash": truncatedHash, 77 | "time_diff": timeStr, 78 | } 79 | 80 | // Marshal the response data to JSON 81 | jsonData, err := json.Marshal(responseData) 82 | if err != nil { 83 | log.Printf("JSON marshal error: %v", err) 84 | continue 85 | } 86 | 87 | // Send the JSON response back through the WebSocket 88 | if err := c.WriteMessage(websocket.TextMessage, jsonData); err != nil { 89 | log.Printf("write error: %v", err) 90 | continue 91 | } 92 | } 93 | 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /utils/go/utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "compress/zlib" 6 | "encoding/base64" 7 | "io" 8 | "log" 9 | "regexp" 10 | "strconv" 11 | 12 | "golang.org/x/crypto/argon2" 13 | ) 14 | 15 | 16 | // decompressData decompresses a slice of bytes and returns the resulting string. 17 | func decompressData(compressed []byte) (string, error) { 18 | b := bytes.NewReader(compressed) 19 | r, err := zlib.NewReader(b) 20 | if err != nil { 21 | return "", err 22 | } 23 | defer r.Close() 24 | 25 | var out bytes.Buffer 26 | if _, err = io.Copy(&out, r); err != nil { 27 | return "", err 28 | } 29 | return out.String(), nil 30 | } 31 | 32 | // verifyArgon2Hash checks the validity of an Argon2 hash given the hash and key. 33 | func verifyArgon2Hash(hashToVerify, key string) bool { 34 | re := regexp.MustCompile(`^\$argon2id\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)`) 35 | matches := re.FindStringSubmatch(hashToVerify) 36 | 37 | if len(matches) != 7 { 38 | log.Printf("Hash string is not in the correct format") 39 | return false 40 | } 41 | 42 | //version, _ := strconv.ParseUint(matches[1], 10, 32) 43 | memory, _ := strconv.ParseUint(matches[2], 10, 32) 44 | time, _ := strconv.ParseUint(matches[3], 10, 32) 45 | parallelism, _ := strconv.ParseUint(matches[4], 10, 8) 46 | salt, _ := base64.RawStdEncoding.DecodeString(matches[5]) 47 | decodedHash, _ := base64.RawStdEncoding.DecodeString(matches[6]) 48 | 49 | computedHash := argon2.IDKey([]byte(key), salt, uint32(time), uint32(memory), uint8(parallelism), uint32(len(decodedHash))) 50 | 51 | return bytes.Equal(computedHash, decodedHash) 52 | } 53 | -------------------------------------------------------------------------------- /utils/go_listener/utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "compress/zlib" 6 | "encoding/base64" 7 | "io" 8 | "log" 9 | "regexp" 10 | "strconv" 11 | 12 | "golang.org/x/crypto/argon2" 13 | ) 14 | 15 | 16 | // decompressData decompresses a slice of bytes and returns the resulting string. 17 | func decompressData(compressed []byte) (string, error) { 18 | b := bytes.NewReader(compressed) 19 | r, err := zlib.NewReader(b) 20 | if err != nil { 21 | return "", err 22 | } 23 | defer r.Close() 24 | 25 | var out bytes.Buffer 26 | if _, err = io.Copy(&out, r); err != nil { 27 | return "", err 28 | } 29 | return out.String(), nil 30 | } 31 | 32 | // verifyArgon2Hash checks the validity of an Argon2 hash given the hash and key. 33 | func verifyArgon2Hash(hashToVerify, key string) bool { 34 | re := regexp.MustCompile(`^\$argon2id\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)`) 35 | matches := re.FindStringSubmatch(hashToVerify) 36 | 37 | if len(matches) != 7 { 38 | log.Printf("Hash string is not in the correct format") 39 | return false 40 | } 41 | 42 | //version, _ := strconv.ParseUint(matches[1], 10, 32) 43 | memory, _ := strconv.ParseUint(matches[2], 10, 32) 44 | time, _ := strconv.ParseUint(matches[3], 10, 32) 45 | parallelism, _ := strconv.ParseUint(matches[4], 10, 8) 46 | salt, _ := base64.RawStdEncoding.DecodeString(matches[5]) 47 | decodedHash, _ := base64.RawStdEncoding.DecodeString(matches[6]) 48 | 49 | computedHash := argon2.IDKey([]byte(key), salt, uint32(time), uint32(memory), uint8(parallelism), uint32(len(decodedHash))) 50 | 51 | return bytes.Equal(computedHash, decodedHash) 52 | } 53 | -------------------------------------------------------------------------------- /utils/manage_difficulty.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import threading 3 | 4 | def adjust_difficulty(): 5 | # Connect to the difficulty database 6 | diff_conn = sqlite3.connect('difficulty.db', timeout=10) 7 | diff_c = diff_conn.cursor() 8 | 9 | # Get the latest rate from blockrate table 10 | diff_c.execute("SELECT rate FROM blockrate ORDER BY id DESC LIMIT 1") 11 | latest_rate = diff_c.fetchone() 12 | if latest_rate: 13 | latest_rate = latest_rate[0] 14 | print(f"Latest rate is {latest_rate}") 15 | else: 16 | print("No rate found") 17 | return 18 | 19 | # Get the current level of difficulty 20 | diff_c.execute("SELECT level FROM difficulty WHERE id=1") 21 | current_level = diff_c.fetchone() 22 | if current_level: 23 | current_level = current_level[0] 24 | print(f"Current difficulty level is {current_level}") 25 | else: 26 | print("No difficulty level found") 27 | return 28 | 29 | # Check if the latest rate deviates by 20% from 60 30 | threshold = 60 * 0.2 # 20% of 60 31 | lower_limit = 60 - threshold 32 | upper_limit = 60 + threshold 33 | 34 | if latest_rate < lower_limit or latest_rate > upper_limit: 35 | # Update the level based on the latest rate 36 | new_level = current_level + 300 if latest_rate > upper_limit else current_level - 100 37 | 38 | # Update the difficulty level in the database 39 | diff_c.execute("UPDATE difficulty SET level = ? WHERE id=1", (new_level,)) 40 | diff_conn.commit() 41 | print(f"Difficulty level updated to {new_level}") 42 | 43 | # Close the connection to the database 44 | diff_conn.close() 45 | 46 | # Schedule the next check 47 | threading.Timer(300, adjust_difficulty).start() 48 | 49 | # Initial call to start the loop and reporting 50 | print("Starting the script...") 51 | adjust_difficulty() 52 | 53 | -------------------------------------------------------------------------------- /utils/manage_difficulty2.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import random 3 | import threading 4 | import sys 5 | from datetime import datetime 6 | 7 | 8 | def is_within_five_minutes_of_hour(): 9 | timestamp = datetime.now() 10 | minutes = timestamp.minute 11 | print ("My minutes ", minutes) 12 | return 0 <= minutes < 5 or 55 <= minutes < 60 13 | 14 | def adjust_difficulty(): 15 | # Save stdout to a variable for restoring later 16 | #original_stdout = sys.stdout 17 | 18 | # Open the log file in append mode 19 | with open('difficulty.log', 'a') as f: 20 | # Redirect stdout to the file 21 | sys.stdout = f 22 | 23 | # Connect to the difficulty database 24 | diff_conn = sqlite3.connect('difficulty.db', timeout=10) 25 | diff_c = diff_conn.cursor() 26 | 27 | # Get the latest rate from blockrate table 28 | diff_c.execute("SELECT rate FROM blockrate ORDER BY id DESC LIMIT 1") 29 | latest_rate = diff_c.fetchone() 30 | if latest_rate: 31 | latest_rate = latest_rate[0] 32 | print(f"Latest rate is {latest_rate}") 33 | else: 34 | print("No rate found") 35 | return 36 | 37 | # Get the current level of difficulty 38 | diff_c.execute("SELECT level FROM difficulty WHERE id=1") 39 | current_level = diff_c.fetchone() 40 | if current_level: 41 | current_level = current_level[0] 42 | print(f"Current difficulty level is {current_level}") 43 | else: 44 | print("No difficulty level found") 45 | return 46 | if is_within_five_minutes_of_hour: 47 | # Check if the latest rate deviates by 20% from 60 48 | threshold = 60 * 0.2 # 20% of 60 49 | lower_limit = 60 - threshold 50 | upper_limit = 60 + threshold 51 | else: 52 | # Check if the latest rate deviates by 20% from 60 53 | threshold = 60 * 0.2 # 20% of 60 54 | lower_limit = 60 - threshold 55 | upper_limit = 60 + threshold 56 | 57 | if latest_rate < lower_limit or latest_rate > upper_limit: 58 | # Update the level based on the latest rate 59 | new_level = current_level + 2000 if latest_rate > upper_limit else current_level - 2000 60 | 61 | # Update the difficulty level in the database 62 | diff_c.execute("UPDATE difficulty SET level = ? WHERE id=1", (new_level,)) 63 | diff_conn.commit() 64 | print(f"Difficulty level updated to {new_level}") 65 | 66 | # Close the connection to the database 67 | diff_conn.close() 68 | 69 | # Restore original stdout 70 | #sys.stdout = original_stdout 71 | 72 | # issue randomness every 5 mins 73 | 74 | #diff_conn = sqlite3.connect('difficulty.db', timeout=10) 75 | #diff_c = diff_conn.cursor() 76 | #diff_c.execute("UPDATE difficulty SET level = level + ((random() % 51) - 25) WHERE id=1") 77 | #diff_conn.commit() 78 | #diff_conn.close() 79 | #print ("Randomized difficulty") 80 | # Schedule the next check 81 | threading.Timer(300, adjust_difficulty).start() 82 | 83 | # Initial call to start the loop and reporting 84 | print("Starting the script...") 85 | adjust_difficulty() 86 | 87 | -------------------------------------------------------------------------------- /utils/salt_unittest.py: -------------------------------------------------------------------------------- 1 | import re 2 | import base64 3 | from web3 import Web3 4 | 5 | def restore_eip55_address(lowercase_address: str) -> bool: 6 | # Restore the address using EIP-55 checksum 7 | try: 8 | checksum_address = Web3.to_checksum_address(lowercase_address) 9 | print("Checksummed address is: ", checksum_address) 10 | return True 11 | except ValueError as e: 12 | # Handle the error in case the address is not a valid Ethereum address 13 | print(f"An error occurred: {e}") 14 | return False 15 | 16 | 17 | def check_salt_format_and_ethereum_address(hash_to_verify: str) -> bool: 18 | # Regular expressions for the expected patterns 19 | pattern1 = re.compile(r'WEVOMTAwODIwMjJYRU4') 20 | pattern2 = re.compile(r'^[A-Za-z0-9+/]{27}$') 21 | 22 | # Extract the salt part from the hash_to_verify 23 | parts = hash_to_verify.split("$") 24 | if len(parts) != 6: 25 | return False 26 | salt = parts[4] 27 | 28 | # Check if the salt matches the first pattern 29 | if pattern1.search(salt): 30 | return True 31 | else: 32 | print("Old Salt False") 33 | 34 | # Check if the salt matches the second pattern and is base64 35 | if pattern2.fullmatch(salt): 36 | print ("In Pattern2 match") 37 | try: 38 | # The proper base64 string should have a length that is a multiple of 4. 39 | # We need to add padding if necessary. 40 | missing_padding = len(salt) % 4 41 | if missing_padding: 42 | salt += '=' * (4 - missing_padding) 43 | 44 | # Decode the base64 string 45 | decoded_bytes = base64.b64decode(salt) 46 | decoded_str = decoded_bytes.hex() 47 | print("Decoded salt: ", decoded_str) 48 | 49 | # Check if the decoded string is a valid hexadecimal and of a specific length 50 | if re.fullmatch(r'[0-9a-fA-F]{40}', decoded_str): # Ethereum addresses are 40 hex characters long 51 | # Construct potential Ethereum address 52 | potential_eth_address = '0x' + decoded_str 53 | print("Address matched: ", potential_eth_address) 54 | 55 | # Validate Ethereum address checksum 56 | if restore_eip55_address(potential_eth_address): 57 | print("Checksum of address is valid") 58 | return True 59 | except Exception as e: 60 | print(f"An error occurred: {e}") 61 | return False 62 | 63 | return False 64 | 65 | # Example for testing the function 66 | hash_to_verify = "$argon2id$v=19$m=1500,t=1,p=1$pyWn54uTptICzki0Oa5DknaaiqM$SFjWpTvU0PwEr+Y56fLhFIRL4FWhHXENqJ48RUr1ipApiovrb/ciR5D5//etMI7unr/133U8PKQ6mBWoR39few" 67 | print(check_salt_format_and_ethereum_address(hash_to_verify)) # True if it's a valid Ethereum address with a valid checksum 68 | hash_to_verify = "$argon2id$v=19$m=67400,t=1,p=1$WEVOMTAwODIwMjJYRU4$CiW038mdwhkuhBQHEsUr+08ljPAXUNI7eRyIvkvXnsJELQHyCS0wCxyH3oHjBz1ymjBX34jTN30z+id6Ap1xDw" 69 | print(check_salt_format_and_ethereum_address(hash_to_verify)) # True if it's a valid Ethereum address with a valid checksum 70 | hash_to_verify = "$argon2id$v=19$m=1500,t=1,p=1$QkShdDvVej2+KqeRSqCih0N6Dvs$At03JjGusrxCib4ejiGJ6Boziavjp9l7uWF+2Hb1CWmvXENxUNlBCxAXW8nBmW466h4iZzjYgNuiEtytCF+roA" 71 | print(check_salt_format_and_ethereum_address(hash_to_verify)) # True if it's a valid Ethereum address with a valid checksum 72 | hash_to_verify = "$argon2id$v=19$m=67400,t=1,p=1$y/21bUKjJM6hHEHRh3I6bV6GCe4$h5kZ8qppu/aoEhReGqZ9eHczijaX0Qzak/hBS1ebUpm/BhTqXioycU5wQYFyCd9kyviA5b3QrelckYmSjrZygA" 73 | print(check_salt_format_and_ethereum_address(hash_to_verify)) # True if it's a valid Ethereum address with a valid checksum 74 | hash_to_verify = "$argon2id$v=19$m=67400,t=1,p=1$y/21bUKjJM6hHEHRh3I6bV6GCe4$yV2iuEo42Gy7FkQNAjtODA72sSsqW4I1zaibZbqmLu8BuUW3EKphUyQITh8zXUNI3JF1STxDeCa+pJAJbVSmTw" 75 | print(check_salt_format_and_ethereum_address(hash_to_verify)) # True if it's a valid Ethereum address with a valid checksum 76 | -------------------------------------------------------------------------------- /utils/verify_proofs.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from passlib.hash import argon2 3 | 4 | # Function to generate Argon2 hash 5 | def gen3erate_argon2_hash(key, m_value, t_value, p_value, salt_bytes): 6 | hash = argon2.using(rounds=t_value, memory_cost=m_value, parallelism=p_value, salt=salt_bytes, digest_size=64).hash(key) 7 | return hash 8 | 9 | 10 | def generate_argon2_hash(key, m_value, t_value, p_value, salt_bytes): 11 | # Ensure key and salt_bytes are in bytes format 12 | if isinstance(key, str): 13 | key = key.encode() 14 | if isinstance(salt_bytes, str): 15 | salt_bytes = salt_bytes.encode() 16 | 17 | # Configure the Argon2 hasher 18 | argon2_hasher = argon2.using(time_cost=t_value, memory_cost=m_value, parallelism=p_value, salt=salt_bytes, hash_len=64) 19 | 20 | # Generate the hash using the configured hasher 21 | hashed_data = argon2_hasher.hash(key) 22 | 23 | return hashed_data 24 | 25 | 26 | #0000da975bd6ec3aa878dadc395943619d23407371bc15066c1505ef23203d871633c687a9e5e89f5fc7fb61f05e1ff4ec49ecee28577c5143711185afe2d5a5 27 | #select * from blocks where key = '0000da975bd6ec3aa878dadc395943619d23407371bc15066c1505ef23203d871633c687a9e5e89f5fc7fb61f05e1ff4ec49ecee28577c5143711185afe2d5a5'; 28 | #962524|$argon2id$v=19$m=1327,t=1,p=1$WEVOMTAwODIwMjJYRU4$Vn48cF2Es/CmZXEN11upLsyantNjLy7VP4h2v0z5WFBimDH7AE3kf6uP8AGe1umQncuthETqhKh8yJ7oCFUShg 29 | 30 | # Example usage 31 | key = "0000da975bd6ec3aa878dadc395943619d23407371bc15066c1505ef23203d871633c687a9e5e89f5fc7fb61f05e1ff4ec49ecee28577c5143711185afe2d5a5" # Replace with your actual key 32 | m_value = 1327 # Example m value 33 | t_value = 1 # Example t value 34 | p_value = 1 # Example p value 35 | salt_bytes = b"XEN10082022XEN" # Replace with your actual salt bytes 36 | 37 | argon2_hash = generate_argon2_hash(key, m_value, t_value, p_value, salt_bytes) 38 | print("Argon2 Hash:", argon2_hash) 39 | 40 | #exit(0) 41 | 42 | # Connect to the SQLite database 43 | conn = sqlite3.connect('balances6.db') # Replace with your database file 44 | cursor = conn.cursor() 45 | 46 | # Query to retrieve rows from account_balances 47 | cursor.execute("SELECT m_value, t_value, p_value, salt_bytes, key FROM account_balances") 48 | 49 | # Process each row 50 | for row in cursor.fetchall(): 51 | m_value, t_value, p_value, salt_bytes, key = row 52 | 53 | #print ("key: ", key.hex()) 54 | #print ("salt: ", salt_bytes) 55 | # Generate the Argon2 hash 56 | argon2_hash = generate_argon2_hash(key.hex(), m_value, t_value, p_value, salt_bytes) 57 | 58 | # Print or store the generated hash 59 | print("Generated Hash:", argon2_hash) 60 | 61 | # Close the database connection 62 | conn.close() 63 | 64 | -------------------------------------------------------------------------------- /utils/voter.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import websockets 3 | import json 4 | from collections import deque 5 | from argon2 import PasswordHasher 6 | from argon2.exceptions import VerifyMismatchError 7 | 8 | # Function to verify the hash 9 | def verify_argon2id_hash(hashed_data, key): 10 | ph = PasswordHasher() 11 | try: 12 | ph.verify(hashed_data, key) 13 | return True 14 | except VerifyMismatchError: 15 | return False 16 | 17 | # Store the last 100 block IDs 18 | recent_block_ids = deque(maxlen=100) 19 | 20 | async def get_data(): 21 | uri = "ws://186.233.186.56:8765" 22 | while True: 23 | try: 24 | async with websockets.connect(uri) as websocket: 25 | while True: 26 | await websocket.send("request") 27 | response = await websocket.recv() 28 | data = json.loads(response) 29 | 30 | for block in data: 31 | block_id, argon2id_hash, key, *rest = block.split('|') 32 | 33 | # Only verify if the block ID is not in recent_block_ids 34 | if block_id not in recent_block_ids: 35 | is_valid = verify_argon2id_hash(argon2id_hash, key) 36 | if is_valid: 37 | print(f"Verified Block ID: {block_id}") 38 | 39 | # Add the block ID to the deque 40 | recent_block_ids.append(block_id) 41 | 42 | await asyncio.sleep(3) 43 | except websockets.ConnectionClosed: 44 | print("Connection lost, attempting to reconnect...") 45 | await asyncio.sleep(5) # Wait for 5 seconds before reconnecting 46 | except Exception as e: 47 | print(f"Error occurred: {e}") 48 | await asyncio.sleep(5) # Wait for 5 seconds before attempting to reconnect 49 | 50 | # Run the coroutine 51 | asyncio.run(get_data()) 52 | 53 | -------------------------------------------------------------------------------- /vast/vash.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Update package list and install necessary packages 4 | 5 | sudo apt update 6 | sleep 5 7 | echo "---------------------------" 8 | 9 | sudo apt -y install ocl-icd-opencl-dev 10 | sleep 5 11 | echo "---------------------------" 12 | 13 | sudo apt -y install nano 14 | sleep 5 15 | echo "---------------------------" 16 | 17 | sudo apt -y install htop 18 | sleep 5 19 | echo "---------------------------" 20 | 21 | # sudo apt -y install nvtop 22 | sudo apt -y install cmake 23 | sleep 5 24 | echo "---------------------------" 25 | 26 | sudo apt -y install python3-pip 27 | sleep 5 28 | echo "---------------------------" 29 | 30 | # Clone the repository and build the project 31 | git clone https://github.com/shanhaicoder/XENGPUMiner.git 32 | sleep 5 33 | echo "---------------------------" 34 | 35 | cd XENGPUMiner 36 | sleep 5 37 | echo "---------------------------" 38 | 39 | chmod +x build.sh 40 | sleep 5 41 | echo "---------------------------" 42 | 43 | ./build.sh 44 | sleep 5 45 | echo "---------------------------" 46 | 47 | # Update the configuration file 48 | sed -i 's/account = 0x24691e54afafe2416a8252097c9ca67557271475/account = 0xCbFdb56d42a324cEA11C41D187723a6d5e8609eE/g' config.conf 49 | sleep 5 50 | echo "---------------------------" 51 | 52 | # Install Python requirements 53 | sudo pip install -U -r requirements.txt 54 | sleep 5 55 | echo "---------------------------" 56 | 57 | sudo nohup python3 miner.py --gpu=true > miner.log 2>&1 & 58 | sleep 5 59 | echo "---------------------------" 60 | 61 | sudo nohup ./xengpuminer > xengpuminer.log 2>&1 & 62 | sleep 5 63 | echo "---------------------------" 64 | --------------------------------------------------------------------------------