├── .github └── workflows │ ├── release.yml │ └── staging.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── atomicals-electrumx ├── Cargo.toml └── src │ ├── error.rs │ ├── lib.rs │ ├── test.rs │ ├── type.rs │ └── util.rs ├── build.rs ├── src ├── atomicals_packer.rs ├── atomicals_worker.rs ├── main.rs ├── miner │ ├── .gitignore │ ├── cpu.rs │ ├── ext │ │ └── sha256d.cl │ ├── gpu.rs │ └── mod.rs ├── util.rs └── utils │ ├── bitworkc.rs │ └── mod.rs └── static └── mining.png /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: 5 | - "v[0-9]+.[0-9]+.[0-9]+" 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | 10 | jobs: 11 | build: 12 | name: Build ${{ matrix.target.name }} package 13 | runs-on: ${{ matrix.target.os }} 14 | strategy: 15 | matrix: 16 | target: 17 | [ 18 | { name: x86_64-unknown-linux-gnu, os: ubuntu-latest }, 19 | { name: aarch64-apple-darwin, os: macos-latest }, 20 | { 21 | name: x86_64-pc-windows-msvc, 22 | os: windows-latest, 23 | extension: .exe, 24 | }, 25 | ] 26 | steps: 27 | - name: Fetch latest code 28 | uses: actions/checkout@v4 29 | - name: Setup Rust toolchain 30 | run: rustup target add ${{ matrix.target.name }} 31 | - name: Install OpenCL (Linux) 32 | if: matrix.target.os == 'ubuntu-latest' 33 | run: | 34 | sudo apt-get update 35 | sudo apt install opencl-headers ocl-icd-opencl-dev -y 36 | - uses: Jimver/cuda-toolkit@v0.2.14 37 | if: matrix.target.os == 'windows-latest' 38 | id: cuda-toolkit 39 | with: 40 | cuda: '12.3.2' 41 | method: "local" 42 | sub-packages: '["nvcc","opencl"]' 43 | - name: Set RUSTFLAGS (Windows) 44 | if: matrix.target.os == 'windows-latest' 45 | run: echo "RUSTFLAGS=-L ${{ steps.cuda-toolkit.outputs.CUDA_PATH }}/lib/x64" >> $GITHUB_ENV 46 | - name: Build 47 | run: cargo build --profile ci-release --locked --target ${{ matrix.target.name }} 48 | - name: Prepare artifact 49 | run: | 50 | cp target/${{ matrix.target.name }}/ci-release/collider${{ matrix.target.extension }} collider-${{ matrix.target.name }}${{ matrix.target.extension }} 51 | - name: Upload artifact 52 | uses: actions/upload-artifact@v4.3.1 53 | with: 54 | name: collider-${{ matrix.target.name }}${{ matrix.target.extension }} 55 | path: collider-${{ matrix.target.name }}${{ matrix.target.extension }} 56 | retention-days: 1 57 | 58 | release: 59 | name: Release 60 | runs-on: ubuntu-latest 61 | permissions: 62 | contents: write 63 | discussions: write 64 | needs: [build] 65 | steps: 66 | - name: Download artifacts 67 | uses: actions/download-artifact@v4 68 | - name: Hash 69 | run: | 70 | mkdir -p artifacts 71 | mv collider-*/* artifacts/ 72 | cd artifacts 73 | sha256sum * | tee ../SHA256 74 | md5sum * | tee ../MD5 75 | mv ../SHA256 . 76 | mv ../MD5 . 77 | - name: Publish 78 | uses: softprops/action-gh-release@v2 79 | with: 80 | discussion_category_name: Announcements 81 | generate_release_notes: true 82 | files: artifacts/* 83 | 84 | # No need publish on crates.io because we are using GitHub releases 85 | # publish-on-crates-io: 86 | # name: Publish on crates.io 87 | # runs-on: ubuntu-latest 88 | # steps: 89 | # - name: Fetch latest code 90 | # uses: actions/checkout@v4 91 | # - name: Login 92 | # run: cargo login ${{ secrets.CARGO_REGISTRY_TOKEN }} 93 | # - name: Publish 94 | # run: cargo publish --locked -------------------------------------------------------------------------------- /.github/workflows/staging.yml: -------------------------------------------------------------------------------- 1 | name: Staging 2 | on: 3 | workflow_dispatch: 4 | 5 | env: 6 | CARGO_TERM_COLOR: always 7 | 8 | jobs: 9 | build: 10 | name: Build ${{ matrix.target.name }} package 11 | runs-on: ${{ matrix.target.os }} 12 | strategy: 13 | matrix: 14 | target: 15 | [ 16 | { name: x86_64-unknown-linux-gnu, os: ubuntu-latest }, 17 | { name: aarch64-apple-darwin, os: macos-latest }, 18 | { 19 | name: x86_64-pc-windows-msvc, 20 | os: windows-latest, 21 | extension: .exe, 22 | }, 23 | ] 24 | steps: 25 | - name: Fetch latest code 26 | uses: actions/checkout@v4 27 | - name: Setup Rust toolchain 28 | run: rustup target add ${{ matrix.target.name }} 29 | - name: Install OpenCL (Linux) 30 | if: matrix.target.os == 'ubuntu-latest' 31 | run: | 32 | sudo apt-get update 33 | sudo apt install opencl-headers ocl-icd-opencl-dev -y 34 | - uses: Jimver/cuda-toolkit@v0.2.14 35 | if: matrix.target.os == 'windows-latest' 36 | id: cuda-toolkit 37 | with: 38 | cuda: '12.3.2' 39 | method: "local" 40 | sub-packages: '["nvcc","opencl"]' 41 | - name: Set RUSTFLAGS (Windows) 42 | if: matrix.target.os == 'windows-latest' 43 | run: echo "RUSTFLAGS=-L ${{ steps.cuda-toolkit.outputs.CUDA_PATH }}/lib/x64" >> $GITHUB_ENV 44 | - name: Build 45 | run: cargo build --profile ci-release --locked --target ${{ matrix.target.name }} 46 | - name: Prepare artifact 47 | run: | 48 | cp target/${{ matrix.target.name }}/ci-release/collider${{ matrix.target.extension }} collider-${{ matrix.target.name }}${{ matrix.target.extension }} 49 | - name: Upload artifact 50 | uses: actions/upload-artifact@v4.3.1 51 | with: 52 | name: collider-${{ matrix.target.name }}${{ matrix.target.extension }} 53 | path: collider-${{ matrix.target.name }}${{ matrix.target.extension }} 54 | retention-days: 1 55 | 56 | staging: 57 | name: Staging 58 | runs-on: ubuntu-latest 59 | needs: [build] 60 | steps: 61 | - name: Download artifacts 62 | uses: actions/download-artifact@v4 63 | - name: Hash 64 | run: | 65 | mkdir -p artifacts 66 | mv collider-*/* artifacts/ 67 | cd artifacts 68 | sha256sum * | tee ../SHA256 69 | md5sum * | tee ../MD5 70 | mv ../SHA256 . 71 | mv ../MD5 . -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | .idea 3 | 4 | target 5 | .git -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "collider" 3 | version = "0.2.9" 4 | build = "build.rs" 5 | authors = ["BoxMrChen "] 6 | readme = "README.md" 7 | repository = "https://github.com/nishuzumi/collider" 8 | edition = "2021" 9 | license = "AGPL-3" 10 | 11 | [workspace] 12 | members = ['atomicals-electrumx'] 13 | 14 | [profile.ci-dev] 15 | incremental = false 16 | inherits = "dev" 17 | 18 | [profile.ci-release] 19 | inherits = "release" 20 | lto = true 21 | 22 | [build-dependencies] 23 | # crates.io 24 | vergen = { version = "8.3", features = ["build", "cargo", "git", "gitcl"] } 25 | 26 | [dependencies] 27 | # crates.io 28 | atomicals-electrumx = { version = "0.2.1", path = 'atomicals-electrumx' } 29 | bitcoin = "0.31.1" 30 | eyre = "0.6.12" 31 | tokio = { version = "1.35", features = ["macros", "rt-multi-thread"] } 32 | tracing = { version = "0.1" } 33 | tracing-subscriber = { version = "0.3" } 34 | lazy_static = "1.4.0" 35 | options = "0.5.3" 36 | structopt = "0.3.26" 37 | anyhow = "1.0.80" 38 | serde = { version = "1.0.197", features = ["derive"] } 39 | rand = "0.8.5" 40 | ciborium = "0.2.2" 41 | ring = "0.17.8" 42 | rayon = "1.9.0" 43 | dotenvy = "0.15.7" 44 | hex = "0.4.3" 45 | log = "0.4.21" 46 | indicatif = { version = "0.17.8", features = ["improved_unicode"] } 47 | ocl = { version = "0.19.6" } 48 | colored = "2.1.0" 49 | prettytable-rs = "0.10.0" 50 | reqwest = "0.12.3" 51 | toml = "0.8.12" 52 | semver = "1.0.22" 53 | 54 | [features] 55 | default = ["boardcast"] 56 | boardcast = [] 57 | op_sha256 = [] 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | # Collider 4 | A High-Performance, Open-Source FT Mint Tool for the Atomicals Protocol 5 | 6 | ***Make Atomicals Great Again*** 7 | 8 | [![License](https://img.shields.io/badge/license-AGPL-blue.svg)](https://www.gnu.org/licenses/agpl-3.0.html) 9 | [![Release](https://github.com/nishuzumi/collider/actions/workflows/release.yml/badge.svg)](https://github.com/nishuzumi/collider/actions/workflows/release.yml) 10 | [![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/nishuzumi/collider)](https://github.com/nishuzumi/collider/tags) 11 | [![GitHub code lines](https://tokei.rs/b1/github/nishuzumi/collider)](https://github.com/nishuzumi/collider) 12 | [![GitHub last commit](https://img.shields.io/github/last-commit/nishuzumi/collider?color=red&style=plastic)](https://github.com/nishuzumi/collider) 13 | 14 | [![Telegram](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/collider_atomicals) 15 | 16 | 17 | Collider is a fast and efficient FT (Fungible Token) Mint tool designed for the Atomicals protocol. It harnesses the power of GPU parallel computing to significantly boost the computational performance of the FT Mint process. 18 | 19 | In the past, we have seen many FT Mint tools being monopolized by a few individuals or organizations, which is detrimental to the healthy development of the Atomicals ecosystem. To promote the prosperity of the Atomicals community, we have created Collider as an open-source project. 20 | 21 | By open-sourcing Collider, we aim to: 22 | 23 | Provide a high-performance FT Mint tool that benefits all users of the Atomicals protocol. 24 | 25 | Foster openness and inclusivity within the Atomicals community, preventing tool monopolization. 26 | 27 | Encourage more developers to participate in building the Atomicals ecosystem, driving its growth together. 28 | 29 | Continuously optimize and enhance Collider through the power of the community, making it the standard FT Mint tool for the Atomicals protocol. 30 | 31 | We sincerely invite everyone interested in the Atomicals protocol to join the Collider project. Whether you are a developer, designer, or general user, your contributions will be invaluable. Let us work hand in hand to strive for a brighter future for Atomicals! 32 | 33 | ![Mine](./static/mining.png) 34 | Mine the Infinity (888888888.14) within 3 minutes (Lucky) 35 |
36 | 37 | ## Features 38 | 39 | - Customizable verbosity level for detailed logging 40 | - Support for both mainnet and testnet environments 41 | - Configurable base fee for transactions 42 | - Primary wallet and funding wallet management 43 | - Ticker symbol specification 44 | - Choice of mining algorithm (CPU or GPU or custom by your self) 45 | 46 | ## Getting Started 47 | 48 | ### Prerequisites 49 | 50 | - Rust programming language (latest stable version) 51 | - Cargo package manager 52 | 53 | ### Installation 54 | 55 | #### Option 1: Using Pre-compiled Binaries 56 | 57 | 1. Download the pre-compiled binary for your operating system from the [releases page](https://github.com/nishuzumi/collider/releases). 58 | 59 | 2. Extract the downloaded archive to a directory of your choice. 60 | 61 | 3. Open a terminal and navigate to the directory where you extracted the binary. 62 | 63 | #### Option 2: Building from Source 64 | 65 | 1. Clone the repository: 66 | ```shell 67 | git clone https://github.com/yourusername/collider.git 68 | ``` 69 | 70 | 2. Change to the project directory: 71 | ```shell 72 | cd collider 73 | ``` 74 | 75 | 3. Build the project: 76 | ```shell 77 | cargo build --release 78 | ``` 79 | 4. The compiled binary will be located at `target/release/collider`. 80 | 81 | ### Usage 82 | 83 | To run the Collider, use the following command: 84 | 85 | ```shell 86 | ./collider [OPTIONS] 87 | ``` 88 | 89 | #### Usage 90 | ```shell 91 | Collider 0.2.8 92 | A collider for atomicals. 93 | 94 | USAGE: 95 | collider [FLAGS] [OPTIONS] --funding-wallet --miner --primary-wallet 96 | 97 | FLAGS: 98 | --benchmark 99 | -h, --help Prints help information 100 | -V, --version Prints version information 101 | -v, --verbose Sets the level of verbosity 102 | 103 | OPTIONS: 104 | -a, --api-url [env: API_URL=] 105 | -b, --base-fee [env: BASE_FEE=] [default: 50] 106 | -f, --funding-wallet [env: FUNDING_WALLET=] 107 | -m, --miner [env: MINER=] [default: cpu] [possible values: cpu, gpu] 108 | -p, --primary-wallet [env: PRIMARY_WALLET=] 109 | --testnet [env: TESTNET=] 110 | -t, --ticker [env: TICKER=] 111 | ``` 112 | 113 | **Do not use any wallet containing inscriptions or other assets as a funding wallet !!!!!** 114 | 115 | You can set these environment variables in a `.env` file in the project root directory. The Collider will automatically load the variables from this file. 116 | 117 | Example `.env` file: 118 | 119 | ``` 120 | API_URL=https://api.example.com 121 | TESTNET=true 122 | BASE_FEE=100 123 | PRIMARY_WALLET=your_primary_wallet_address 124 | FUNDING_WALLET=your_funding_wallet_private_key 125 | TICKER=YOUR_TICKER 126 | MINER=cpu 127 | ``` 128 | 129 | ## Performance 130 | The following table shows the performance benchmarks 131 | ``` 132 | CPU Name: Apple M3 Max 133 | GPU Name: Apple M3 Max (OpenCL Version: 1.2) 134 | +--------+------------------------+------------------------+ 135 | | Device | Commit Hash Rate (M/s) | Reveal Hash Rate (M/s) | 136 | +--------+------------------------+------------------------+ 137 | | CPU | 91.41M/s | 150.45M/s | 138 | +--------+------------------------+------------------------+ 139 | | GPU | 462.07M/s | 604.54M/s | 140 | +--------+------------------------+------------------------+ 141 | ``` 142 | ``` 143 | CPU Name: AMD Ryzen 7 7800X3D 8-Core Processor 144 | GPU Name: NVIDIA GeForce RTX 4090 (OpenCL Version: 3.0) 145 | +--------+------------------------+------------------------+ 146 | | Device | Commit Hash Rate (M/s) | Reveal Hash Rate (M/s) | 147 | +--------+------------------------+------------------------+ 148 | | CPU | 69.96M/s | 97.92M/s | 149 | +--------+------------------------+------------------------+ 150 | | GPU | 1.16B/s | 1.49B/s | 151 | +--------+------------------------+------------------------+ 152 | ``` 153 | 154 | You can test your device by running the following command: 155 | ```shell 156 | ./collider --benchmark 157 | ``` 158 | ## Contributing 159 | 160 | Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request. 161 | 162 | ## Roadmap 163 | [] Add multi mint feature - it will allow user use one utxo to mint 100 times in less gas and time. 164 | 165 | [] Improve the performance - The high performance version is currently closed source, if you are interested you can contact me. 166 | 167 | [] Add pure mode - By using public rpc for higher speed calculations, pure mode will not recognize any assets of the funding wallet. 168 | 169 | ## License 170 | 171 | This project is licensed under the GNU AFFERO GENERAL PUBLIC LICENSE. 172 | 173 | ## Acknowledgements 174 | 175 | [Atomicals](https://atomicals.xyz/) - The Atomicals protocol 176 | 177 | [Atomicalsir](https://github.com/hack-ink/atomicalsir) - For providing the foundation and inspiration for this project 178 | 179 | ## Contact 180 | 181 | For any inquiries or questions, please contact [box@bytemahou.com](mailto:box@bytemahou.com). 182 | -------------------------------------------------------------------------------- /atomicals-electrumx/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Xavier Lau ","BoxMrChen "] 3 | description = "Atomicals electrumx APIs." 4 | edition = "2021" 5 | homepage = "https://hack.ink/atomicalsir" 6 | license = "GPL-3.0" 7 | name = "atomicals-electrumx" 8 | repository = "https://github.com/hack-ink/atomicalsir" 9 | version = "0.2.1" 10 | 11 | [dependencies] 12 | # crates.io 13 | array-bytes = { version = "6.2" } 14 | bitcoin = { version = "0.31", features = ["rand-std"] } 15 | reqwest = { version = "0.11", features = ["json", "rustls-tls"] } 16 | serde = { version = "1.0", features = ["derive"] } 17 | serde_json = { version = "1.0" } 18 | sha2 = { version = "0.10" } 19 | thiserror = { version = "1.0" } 20 | tokio = { version = "1.35", features = ["macros", "rt-multi-thread"] } 21 | tracing = { version = "0.1" } 22 | 23 | [dev-dependencies] 24 | tracing-subscriber = { version = "0.3" } 25 | -------------------------------------------------------------------------------- /atomicals-electrumx/src/error.rs: -------------------------------------------------------------------------------- 1 | //! atomicals-electrumx error collections. 2 | 3 | #![allow(missing_docs)] 4 | 5 | // crates.io 6 | use thiserror::Error as ThisError; 7 | 8 | #[derive(Debug, ThisError)] 9 | pub enum Error { 10 | #[error("exceeded maximum retries")] 11 | ExceededMaximumRetries, 12 | 13 | #[error(transparent)] 14 | Bitcoin(#[from] bitcoin::address::Error), 15 | #[error(transparent)] 16 | Reqwest(#[from] reqwest::Error), 17 | } 18 | -------------------------------------------------------------------------------- /atomicals-electrumx/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Atomicals electrumx APIs. 2 | 3 | #![deny(missing_docs, unused_crate_dependencies)] 4 | 5 | // std 6 | use std::{env, future::Future, str::FromStr, time::Duration}; 7 | 8 | // crates.io 9 | use bitcoin::{Address, Amount, Network}; 10 | use reqwest::{Client as ReqwestClient, ClientBuilder as ReqwestClientBuilder}; 11 | use reqwest::header::{CONTENT_TYPE, HeaderMap, USER_AGENT}; 12 | use serde::{de::DeserializeOwned, Serialize}; 13 | use tokio::time; 14 | 15 | use prelude::*; 16 | use r#type::*; 17 | 18 | #[cfg(test)] 19 | mod test; 20 | 21 | pub mod error; 22 | 23 | pub mod r#type; 24 | 25 | pub mod util; 26 | 27 | pub mod prelude { 28 | //! atomicals-electrumx prelude. 29 | 30 | pub use std::result::Result as StdResult; 31 | 32 | pub use super::error::{self, Error}; 33 | 34 | /// atomicals-electrumx `Result` type. 35 | pub type Result = StdResult; 36 | } 37 | 38 | /// Necessary configurations of the client to transform it into an API client. 39 | pub trait Config { 40 | /// Network type. 41 | fn network(&self) -> &Network; 42 | /// Base URI. 43 | fn base_uri(&self) -> &str; 44 | } 45 | 46 | /// Necessary HTTP methods of the client to transform it into an API client. 47 | pub trait Http { 48 | /// Send a POST request. 49 | fn post(&self, uri: U, params: P) -> impl Future> + Send 50 | where 51 | U: Send + Sync + AsRef, 52 | P: Send + Sync + Serialize, 53 | R: DeserializeOwned; 54 | } 55 | 56 | /// Atomicals electrumx APIs. 57 | pub trait Api: Send + Sync + Config + Http { 58 | /// Construct the API's URI. 59 | fn uri_of(&self, uri: S) -> String 60 | where 61 | S: AsRef, 62 | { 63 | format!("{}/{}", self.base_uri(), uri.as_ref()) 64 | } 65 | 66 | /// Make a request at `blockchain.atomicals.get_by_ticker`. 67 | fn get_by_ticker(&self, ticker: S) -> impl Future> + Send 68 | where 69 | S: Send + Sync + AsRef, 70 | { 71 | async move { 72 | Ok(self 73 | .post::<_, _, Response>>( 74 | self.uri_of("blockchain.atomicals.get_by_ticker"), 75 | [ticker.as_ref()], 76 | ) 77 | .await? 78 | .response 79 | .result) 80 | } 81 | } 82 | 83 | /// Make a request at `blockchain.atomicals.get_by_id`. 84 | fn get_ft_info( 85 | &self, 86 | atomical_id: S, 87 | ) -> impl Future>> + Send 88 | where 89 | S: Send + Sync + AsRef, 90 | { 91 | async move { 92 | Ok(self 93 | .post::<_, _, Response>>( 94 | self.uri_of("blockchain.atomicals.get_ft_info"), 95 | [atomical_id.as_ref()], 96 | ) 97 | .await? 98 | .response) 99 | } 100 | } 101 | 102 | /// Make a request at `blockchain.atomicals.get_by_id`. 103 | fn get_unspent_address(&self, address: S) -> impl Future>> + Send 104 | where 105 | S: Send + Sync + AsRef, 106 | { 107 | async move { 108 | self.get_unspent_scripthash(util::address2scripthash( 109 | &Address::from_str(address.as_ref()) 110 | .unwrap() 111 | .require_network(*self.network())?, 112 | )?) 113 | .await 114 | } 115 | } 116 | 117 | /// Make a request at `blockchain.scripthash.listunspent`. 118 | fn get_unspent_scripthash( 119 | &self, 120 | scripthash: S, 121 | ) -> impl Future>> + Send 122 | where 123 | S: Send + Sync + AsRef, 124 | { 125 | async move { 126 | let mut utxos = self 127 | .post::<_, _, Response>>( 128 | self.uri_of("blockchain.scripthash.listunspent"), 129 | [scripthash.as_ref()], 130 | ) 131 | .await? 132 | .response 133 | .into_iter() 134 | .map(|u| u.into()) 135 | .collect::>(); 136 | 137 | utxos.sort_by(|a, b| a.value.cmp(&b.value)); 138 | 139 | Ok(utxos) 140 | } 141 | } 142 | 143 | /// Wait until a matching UTXO is found. 144 | fn wait_until_utxo( 145 | &self, 146 | address: S, 147 | satoshis: u64, 148 | ) -> impl Future> + Send 149 | where 150 | S: Send + Sync + AsRef, 151 | { 152 | async move { 153 | let a = address.as_ref(); 154 | let ba = Amount::from_sat(satoshis); 155 | 156 | loop { 157 | if let Some(u) = self 158 | .get_unspent_address(a) 159 | .await? 160 | .into_iter() 161 | .find(|u| u.atomicals.is_empty() && u.value >= satoshis) 162 | { 163 | tracing::info!( 164 | "funding UTXO detected {}:{} with a value of {} for funding purposes", 165 | u.txid, 166 | u.vout, 167 | u.value 168 | ); 169 | return Ok(u); 170 | } 171 | 172 | tracing::info!( 173 | "awaiting UTXO confirmation until {ba} BTC is received at address {a}" 174 | ); 175 | 176 | time::sleep(Duration::from_secs(5)).await; 177 | } 178 | } 179 | } 180 | 181 | // TODO: Return type. 182 | /// Make a request at `blockchain.scripthash.get_balance`. 183 | fn broadcast(&self, tx: S) -> impl Future> + Send 184 | where 185 | S: Send + Sync + AsRef, 186 | { 187 | async move { 188 | self.post::<_, _, serde_json::Value>( 189 | self.uri_of("blockchain.transaction.broadcast"), 190 | [tx.as_ref()], 191 | ) 192 | .await 193 | } 194 | } 195 | } 196 | 197 | impl Api for T where T: Send + Sync + Config + Http {} 198 | 199 | /// Atomicals electrumx client. 200 | #[derive(Debug,Clone)] 201 | pub struct ElectrumX { 202 | /// HTTP client. 203 | pub client: ReqwestClient, 204 | /// Retry period. 205 | pub retry_period: Duration, 206 | /// Maximum number of retry attempts. 207 | pub max_retries: MaxRetries, 208 | /// Network type. 209 | pub network: Network, 210 | /// Base URI. 211 | pub base_uri: String, 212 | } 213 | 214 | impl Config for ElectrumX { 215 | fn network(&self) -> &Network { 216 | &self.network 217 | } 218 | 219 | fn base_uri(&self) -> &str { 220 | &self.base_uri 221 | } 222 | } 223 | 224 | impl Http for ElectrumX { 225 | async fn post(&self, uri: U, params: P) -> Result 226 | where 227 | U: Send + Sync + AsRef, 228 | P: Send + Sync + Serialize, 229 | R: DeserializeOwned, 230 | { 231 | let u = uri.as_ref(); 232 | let mut headers = HeaderMap::new(); 233 | headers.insert(CONTENT_TYPE, "application/json".parse().unwrap()); 234 | headers.insert(USER_AGENT,"PostmanRuntime/7.37.0".parse().unwrap()); 235 | 236 | for _ in self.max_retries.clone() { 237 | match self.client.get(u).headers(headers.clone()).query(&[("params",&serde_json::to_string(¶ms).unwrap())]).send().await { 238 | Ok(r) => match r.json().await { 239 | Ok(r) => return Ok(r), 240 | Err(e) => { 241 | tracing::error!("failed to parse response into JSON due to {e}"); 242 | } 243 | }, 244 | Err(e) => { 245 | tracing::error!("the request to {u} failed due to {e}"); 246 | } 247 | } 248 | 249 | time::sleep(self.retry_period).await; 250 | } 251 | 252 | Err(Error::ExceededMaximumRetries) 253 | } 254 | } 255 | 256 | /// Builder for [`ElectrumX`]. 257 | #[derive(Debug)] 258 | pub struct ElectrumXBuilder { 259 | /// Request timeout. 260 | pub timeout: Duration, 261 | /// Retry period. 262 | pub retry_period: Duration, 263 | /// Maximum number of retry attempts. 264 | pub max_retries: MaxRetries, 265 | /// Network type. 266 | pub network: Network, 267 | /// Base URI. 268 | pub base_uri: String, 269 | } 270 | 271 | impl ElectrumXBuilder { 272 | /// Use the testnet network. 273 | pub fn testnet() -> Self { 274 | Self::default() 275 | .network(Network::Testnet) 276 | .base_uri(env::var("TEST_RPC").unwrap_or("https://eptestnet.atomicals.xyz/proxy".to_string())) 277 | } 278 | 279 | /// Set request timeout. 280 | pub fn timeout(mut self, timeout: Duration) -> Self { 281 | self.timeout = timeout; 282 | 283 | self 284 | } 285 | 286 | /// Set retry period. 287 | pub fn retry_period(mut self, retry_period: Duration) -> Self { 288 | self.retry_period = retry_period; 289 | 290 | self 291 | } 292 | 293 | /// Set maximum number of retry attempts. 294 | pub fn max_retries(mut self, max_retries: MaxRetries) -> Self { 295 | self.max_retries = max_retries; 296 | 297 | self 298 | } 299 | 300 | /// Set network type. 301 | pub fn network(mut self, network: Network) -> Self { 302 | self.network = network; 303 | 304 | self 305 | } 306 | 307 | /// Set base URI. 308 | pub fn base_uri(mut self, base_uri: S) -> Self 309 | where 310 | S: Into, 311 | { 312 | self.base_uri = base_uri.into(); 313 | 314 | self 315 | } 316 | 317 | /// Build the [`ElectrumX`] client. 318 | pub fn build(self) -> Result { 319 | Ok(ElectrumX { 320 | client: ReqwestClientBuilder::new().timeout(self.timeout).build()?, 321 | retry_period: self.retry_period, 322 | max_retries: self.max_retries, 323 | network: self.network, 324 | base_uri: self.base_uri, 325 | }) 326 | } 327 | } 328 | 329 | impl Default for ElectrumXBuilder { 330 | fn default() -> Self { 331 | Self { 332 | timeout: Duration::from_secs(30), 333 | retry_period: Duration::from_secs(5), 334 | max_retries: MaxRetries::Finite(5), 335 | network: Network::Bitcoin, 336 | base_uri: "https://ep.atomicalmarket.com/proxy".into(), 337 | } 338 | } 339 | } 340 | 341 | /// Maximum number of retry attempts. 342 | #[derive(Debug, Clone)] 343 | pub enum MaxRetries { 344 | /// Unlimited number of retries. 345 | Infinite, 346 | /// Limited number of retries. 347 | Finite(u8), 348 | } 349 | 350 | impl Iterator for MaxRetries { 351 | type Item = (); 352 | 353 | fn next(&mut self) -> Option { 354 | match self { 355 | Self::Infinite => Some(()), 356 | Self::Finite(n) => { 357 | if *n > 0 { 358 | *n -= 1; 359 | 360 | Some(()) 361 | } else { 362 | None 363 | } 364 | } 365 | } 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /atomicals-electrumx/src/test.rs: -------------------------------------------------------------------------------- 1 | // std 2 | use std::future::Future; 3 | 4 | // crates.io 5 | use tokio::runtime::Runtime; 6 | 7 | // atomicals-electrumx 8 | use crate::*; 9 | 10 | fn test(f: F) 11 | where 12 | F: FnOnce(ElectrumX) -> Fut, 13 | Fut: Future, 14 | { 15 | tracing_subscriber::fmt::init(); 16 | 17 | let e = ElectrumXBuilder::testnet().build().unwrap(); 18 | 19 | Runtime::new().unwrap().block_on(f(e)); 20 | } 21 | 22 | #[test] 23 | fn get_by_ticker_should_work() { 24 | test(|e| async move { 25 | e.get_by_ticker("atomicalsir").await.unwrap(); 26 | }); 27 | } 28 | 29 | #[test] 30 | fn get_ft_info_should_work() { 31 | test(|e| async move { 32 | e.get_ft_info(e.get_by_ticker("atomicalsir").await.unwrap().atomical_id).await.unwrap(); 33 | }); 34 | } 35 | 36 | #[test] 37 | fn get_unspent_address_should_work() { 38 | test(|e| async move { 39 | e.get_unspent_address("tb1pemen3j4wvlryktkqsew8ext7wnsgqhmuzl7267rm3xk0th3gh04qr9wcec") 40 | .await 41 | .unwrap(); 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /atomicals-electrumx/src/type.rs: -------------------------------------------------------------------------------- 1 | #![allow(missing_docs)] 2 | 3 | // std 4 | use std::collections::HashMap; 5 | use std::fmt; 6 | 7 | // crates.io 8 | use serde::Deserialize; 9 | 10 | // TODO: Handle errors. 11 | #[derive(Debug, Deserialize)] 12 | pub struct Response { 13 | pub success: bool, 14 | pub response: R, 15 | } 16 | 17 | #[derive(Debug, Deserialize)] 18 | pub struct ResponseResult { 19 | pub global: Option, 20 | pub result: R, 21 | } 22 | #[derive(Debug, Deserialize)] 23 | pub struct Global { 24 | pub atomical_count: u64, 25 | pub atomicals_block_hashes: HashMap, 26 | pub atomicals_block_tip: String, 27 | pub block_tip: String, 28 | pub coin: String, 29 | pub height: u64, 30 | pub network: String, 31 | pub server_time: String, 32 | } 33 | 34 | #[derive(Debug, Deserialize)] 35 | pub struct Ticker { 36 | pub status: String, 37 | pub candidate_atomical_id: String, 38 | pub atomical_id: String, 39 | pub candidates: Vec, 40 | pub r#type: String, 41 | } 42 | #[derive(Debug, Deserialize)] 43 | pub struct Candidate { 44 | pub tx_num: u64, 45 | pub atomical_id: String, 46 | pub commit_height: u64, 47 | pub reveal_location_height: u64, 48 | } 49 | 50 | #[derive(Debug, Deserialize)] 51 | pub struct Ft { 52 | #[serde(rename = "$bitwork")] 53 | pub bitwork: Bitwork, 54 | #[serde(rename = "$max_mints")] 55 | pub max_mints: u64, 56 | #[serde(rename = "$max_supply")] 57 | pub max_supply: i64, 58 | #[serde(rename = "$mint_amount")] 59 | pub mint_amount: u64, 60 | #[serde(rename = "$mint_bitworkc")] 61 | pub mint_bitworkc: Option, 62 | #[serde(rename = "$mint_bitworkr")] 63 | pub mint_bitworkr: Option, 64 | #[serde(rename = "$mint_height")] 65 | pub mint_height: u64, 66 | #[serde(rename = "$mint_mode")] 67 | pub mint_mode: Option, 68 | #[serde(rename = "$request_ticker")] 69 | pub request_ticker: String, 70 | #[serde(rename = "$request_ticker_status")] 71 | pub request_ticker_status: TickerStatus, 72 | #[serde(rename = "$ticker")] 73 | pub ticker: String, 74 | #[serde(rename = "$ticker_candidates")] 75 | pub ticker_candidates: Vec, 76 | pub atomical_id: String, 77 | pub atomical_number: u64, 78 | pub atomical_ref: String, 79 | pub confirmed: bool, 80 | pub dft_info: DftInfo, 81 | pub location_summary: LocationSummary, 82 | pub mint_data: MintData, 83 | pub mint_info: MintInfo, 84 | pub subtype: String, 85 | pub r#type: String, 86 | } 87 | impl fmt::Display for Ft { 88 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 89 | write!(f, 90 | r#" 91 | Ft Into 92 | Ticker: {} 93 | Max mints: {} 94 | Max supply: {} 95 | Mint amount: {} 96 | "#, 97 | self.ticker, 98 | self.max_mints, 99 | self.max_supply, 100 | self.mint_amount, 101 | )?; 102 | if let Some(bitworkc) = &self.mint_bitworkc { 103 | writeln!(f, " Mint bitworkC: {}", bitworkc)?; 104 | } 105 | if let Some(bitworkr) = &self.mint_bitworkr { 106 | writeln!(f, " Mint bitworkR: {}", bitworkr)?; 107 | } 108 | if let Some(bitworkc) = &self.dft_info.mint_bitworkc_current{ 109 | writeln!(f, " Mint bitworkC current: {}", bitworkc)?; 110 | } 111 | Ok(()) 112 | 113 | } 114 | } 115 | #[derive(Debug, Deserialize)] 116 | pub struct Bitwork { 117 | pub bitworkc: String, 118 | pub bitworkr: Option, 119 | } 120 | #[derive(Debug, Deserialize)] 121 | pub struct TickerStatus { 122 | pub note: String, 123 | pub status: String, 124 | pub verified_atomical_id: String, 125 | } 126 | #[derive(Debug, Deserialize)] 127 | pub struct TickerCandidate { 128 | pub atomical_id: String, 129 | pub commit_height: u64, 130 | pub reveal_location_height: u64, 131 | pub tx_num: u64, 132 | pub txid: String, 133 | } 134 | #[derive(Debug, Deserialize)] 135 | pub struct DftInfo { 136 | pub mint_count: u64, 137 | // "mint_bitworkc_current": "888888888.3", 138 | // "mint_bitworkc_next": "888888888.4", 139 | // "mint_bitworkc_next_next": "888888888.5" 140 | pub mint_bitworkc_current: Option, 141 | pub mint_bitworkc_next: Option, 142 | pub mint_bitworkc_next_next: Option, 143 | } 144 | #[derive(Debug, Deserialize)] 145 | pub struct LocationSummary { 146 | pub circulating_supply: u64, 147 | pub unique_holders: u64, 148 | } 149 | #[derive(Debug, Deserialize)] 150 | pub struct MintData { 151 | pub fields: Fields, 152 | } 153 | #[derive(Debug, Deserialize)] 154 | pub struct Fields { 155 | pub args: Args, 156 | pub meta: Option, 157 | } 158 | #[derive(Debug, Deserialize)] 159 | pub struct Args { 160 | pub bitworkc: String, 161 | pub bitworkr: Option, 162 | pub max_mints: i64, 163 | pub mint_amount: u64, 164 | pub mint_bitworkc: Option, 165 | pub mint_bitworkr: Option, 166 | pub mint_height: u64, 167 | // TODO: It's a `String` in mainnet but a `u64` in testnet. 168 | // pub nonce: u64, 169 | pub request_ticker: String, 170 | pub time: u64, 171 | } 172 | #[derive(Debug, Deserialize)] 173 | pub struct Meta { 174 | pub description: Option, 175 | pub legal: Option, 176 | pub name: Option, 177 | } 178 | #[derive(Debug, Deserialize)] 179 | pub struct Legal { 180 | pub terms: String, 181 | } 182 | #[derive(Debug, Deserialize)] 183 | pub struct MintInfo { 184 | #[serde(rename = "$bitwork")] 185 | pub bitwork: Bitwork, 186 | #[serde(rename = "$mint_bitworkc")] 187 | pub mint_bitworkc: Option, 188 | #[serde(rename = "$mint_bitworkr")] 189 | pub mint_bitworkr: Option, 190 | #[serde(rename = "$request_ticker")] 191 | pub request_ticker: String, 192 | pub args: Args, 193 | pub commit_height: u64, 194 | pub commit_index: u64, 195 | pub commit_location: String, 196 | pub commit_tx_num: u64, 197 | pub commit_txid: String, 198 | pub ctx: Ctx, 199 | pub meta: Meta, 200 | pub reveal_location: String, 201 | pub reveal_location_blockhash: String, 202 | pub reveal_location_header: String, 203 | pub reveal_location_height: u64, 204 | pub reveal_location_index: u64, 205 | pub reveal_location_script: String, 206 | pub reveal_location_scripthash: String, 207 | pub reveal_location_tx_num: u64, 208 | pub reveal_location_txid: String, 209 | pub reveal_location_value: u64, 210 | } 211 | // TODO: Check the real type. 212 | #[derive(Debug, Deserialize)] 213 | pub struct Ctx {} 214 | 215 | #[derive(Debug, Deserialize)] 216 | pub struct Unspent { 217 | pub txid: String, 218 | pub tx_hash: String, 219 | pub index: u32, 220 | pub tx_pos: u32, 221 | pub vout: u32, 222 | pub height: u64, 223 | pub value: u64, 224 | // TODO: Check the real type. 225 | pub atomicals: Vec<()>, 226 | } 227 | 228 | #[derive(Clone, Debug)] 229 | pub struct Utxo { 230 | pub txid: String, 231 | // The same as `output_index` and `index`. 232 | pub vout: u32, 233 | pub value: u64, 234 | pub atomicals: Vec<()>, 235 | } 236 | impl From for Utxo { 237 | fn from(v: Unspent) -> Self { 238 | Self { 239 | txid: v.tx_hash, 240 | vout: v.tx_pos, 241 | value: v.value, 242 | atomicals: v.atomicals, 243 | } 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /atomicals-electrumx/src/util.rs: -------------------------------------------------------------------------------- 1 | //! Atomicals electrumx utilities. 2 | 3 | // crates.io 4 | use bitcoin::Address; 5 | use sha2::{Digest, Sha256}; 6 | 7 | // atomicals-electrumx 8 | use crate::prelude::*; 9 | 10 | /// Convert an address to a scripthash. 11 | pub fn address2scripthash(address: &Address) -> Result { 12 | let mut hasher = Sha256::new(); 13 | 14 | hasher.update(address.script_pubkey()); 15 | 16 | let mut hash = hasher.finalize(); 17 | 18 | hash.reverse(); 19 | 20 | Ok(array_bytes::bytes2hex("", hash)) 21 | } 22 | #[test] 23 | fn address2scripthash_should_work() { 24 | // std 25 | use std::str::FromStr; 26 | // crates.io 27 | use bitcoin::Network; 28 | 29 | assert_eq!( 30 | address2scripthash( 31 | &Address::from_str("bc1pqkq0rg5yjrx6u08nhmc652s33g96jmdz4gjp9d46ew6ahun7xuvqaerzsp") 32 | .unwrap() 33 | .require_network(Network::Bitcoin) 34 | .unwrap() 35 | ) 36 | .unwrap(), 37 | "2ae9d6353b5f9b05073e3a4def3b47ab05033d8340ffa6959917c21779f956cf" 38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | // crates.io 4 | use vergen::EmitBuilder; 5 | 6 | fn main() { 7 | let mut emitter = EmitBuilder::builder(); 8 | 9 | emitter.cargo_target_triple(); 10 | 11 | // Disable the git version if installed from . 12 | if emitter 13 | .clone() 14 | .git_sha(true) 15 | .fail_on_error() 16 | .emit() 17 | .is_err() 18 | { 19 | println!("cargo:rustc-env=VERGEN_GIT_SHA=crates.io"); 20 | 21 | emitter 22 | } else { 23 | *emitter.git_sha(true) 24 | } 25 | .emit() 26 | .unwrap(); 27 | 28 | let op_sha256_exists = Path::new("src/miner/op_sha256_gpu.rs").exists(); 29 | 30 | if op_sha256_exists { 31 | println!("cargo:rustc-cfg=feature=\"op_sha256\""); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/atomicals_packer.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use bitcoin::{Address, Amount, Network, TxOut}; 4 | use bitcoin::secp256k1::{All, Secp256k1}; 5 | use eyre::{eyre, Result}; 6 | use serde::Serialize; 7 | 8 | use atomicals_electrumx::{Api, ElectrumX}; 9 | /// Thanks for atomicalsir awesome work 10 | use atomicals_electrumx::r#type::Ft; 11 | 12 | use crate::util::{current_network, GLOBAL_OPTS}; 13 | use crate::utils::bitworkc::BitWork; 14 | 15 | #[derive(Debug)] 16 | pub struct AtomicalsPacker { 17 | pub api: ElectrumX, 18 | pub network: Network, 19 | master_mode: bool, 20 | } 21 | 22 | #[derive(Clone, Debug)] 23 | pub struct TickerData { 24 | pub secp: Secp256k1, 25 | pub satsbyte: u64, 26 | pub bitworkc: BitWork, 27 | pub ticker:String, 28 | pub bitworkr: Option, 29 | pub additional_outputs: Vec, 30 | // pub payload: PayloadWrapper, 31 | } 32 | 33 | #[derive(Clone, Debug)] 34 | pub struct Fees { 35 | pub commit: u64, 36 | // commit_and_reveal: u64, 37 | pub commit_and_reveal_and_outputs: u64, 38 | // reveal: u64, 39 | pub reveal_and_outputs: u64, 40 | } 41 | #[derive(Debug, Serialize, Clone)] 42 | pub struct PayloadWrapper { 43 | pub args: Payload, 44 | } 45 | #[derive(Debug, Serialize, Clone)] 46 | pub struct Payload { 47 | pub mint_ticker: String, 48 | } 49 | impl AtomicalsPacker { 50 | pub fn new(electrumx: ElectrumX, network: Network, master_mode: bool) -> Self { 51 | AtomicalsPacker { 52 | api: electrumx, 53 | network, 54 | master_mode, 55 | } 56 | } 57 | 58 | pub async fn get_bitwork_info(&self, ticker: String) -> Result { 59 | let id = self.api.get_by_ticker(ticker.clone()).await?.atomical_id; 60 | let response = self.api.get_ft_info(id).await?; 61 | let global = response.global.unwrap(); 62 | let ft = response.result; 63 | 64 | if ft.ticker != ticker { 65 | Err(eyre!("ticker mismatch"))?; 66 | } 67 | if ft.subtype != "decentralized" { 68 | Err(eyre!("not decentralized"))?; 69 | } 70 | if ft.mint_height > global.height + 1 { 71 | Err(eyre!("mint height mismatch"))?; 72 | } 73 | if ft.mint_amount == 0 || ft.mint_amount >= 100_000_000 { 74 | Err(eyre!("mint amount mismatch"))?; 75 | } 76 | if ft.dft_info.mint_count >= ft.max_mints && ft.mint_mode.clone().is_some_and(|mode| mode != "perpetual") && !self.master_mode { 77 | Err(eyre!("max mints reached"))?; 78 | } 79 | 80 | Ok(ft) 81 | } 82 | pub async fn generate_worker(&self, ft: &Ft, primary_address: String) -> Result { 83 | let secp = Secp256k1::new(); 84 | let satsbyte = if self.network == Network::Bitcoin { 85 | GLOBAL_OPTS.base_fee 86 | } else { 87 | 2 88 | }; 89 | let wallet = Address::from_str(&primary_address)? 90 | .require_network(current_network()) 91 | .expect("network mismatch"); 92 | let additional_outputs = vec![TxOut { 93 | value: Amount::from_sat(ft.mint_amount), 94 | script_pubkey: wallet.script_pubkey(), 95 | }]; 96 | let bitworkc = BitWork::new( 97 | ft.mint_bitworkc 98 | .clone() 99 | .unwrap_or_else(|| ft.dft_info.mint_bitworkc_current.clone().unwrap()), 100 | ) 101 | .expect("bitworkc parse error"); 102 | 103 | Ok(TickerData { 104 | secp, 105 | satsbyte, 106 | bitworkc, 107 | ticker:ft.ticker.clone(), 108 | bitworkr: ft 109 | .mint_bitworkr 110 | .clone() 111 | .map(|bitwork| BitWork::new(bitwork).unwrap()), 112 | additional_outputs, 113 | // payload, 114 | }) 115 | } 116 | } 117 | 118 | #[cfg(test)] 119 | mod test { 120 | use bitcoin::Network; 121 | use tracing::info; 122 | 123 | use atomicals_electrumx::{Api, ElectrumXBuilder}; 124 | 125 | use crate::atomicals_packer::AtomicalsPacker; 126 | use crate::util::{GLOBAL_OPTS, log}; 127 | 128 | #[tokio::test] 129 | async fn test_get_bitwork_info() { 130 | log(); 131 | let electrumx = ElectrumXBuilder::testnet().build().unwrap(); 132 | let packer = AtomicalsPacker::new(electrumx.clone(), Network::Testnet, true); 133 | let ft = packer 134 | .get_bitwork_info("rollover3".to_string()) 135 | .await 136 | .unwrap(); 137 | info!("{:?}", ft); 138 | assert_eq!(ft.ticker, "rollover3"); 139 | let worker_data = packer 140 | .generate_worker(&ft, GLOBAL_OPTS.primary_wallet.as_ref().unwrap().clone()) 141 | .await 142 | .unwrap(); 143 | info!("{:?}", worker_data); 144 | 145 | let funding_wallet = &GLOBAL_OPTS.funding_wallet.as_ref().unwrap().p2tr_address(&worker_data.secp); 146 | let utxo = electrumx 147 | .wait_until_utxo(funding_wallet.to_string(), worker_data.satsbyte) 148 | .await; 149 | info!("{:?}", utxo); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/atomicals_worker.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::sync::atomic::Ordering; 3 | use std::thread; 4 | use std::time::{Duration, Instant}; 5 | 6 | use bitcoin::{ 7 | Amount, OutPoint, Psbt, ScriptBuf, Sequence, TapLeafHash, TapSighashType, Transaction, TxIn, 8 | TxOut, Witness, 9 | }; 10 | use bitcoin::absolute::LockTime; 11 | use bitcoin::consensus::{deserialize, Encodable}; 12 | use bitcoin::hashes::Hash; 13 | use bitcoin::key::{Keypair, Secp256k1}; 14 | use bitcoin::psbt::Input; 15 | use bitcoin::secp256k1::{All, Message}; 16 | use bitcoin::sighash::{Prevouts, SighashCache}; 17 | use bitcoin::taproot::{LeafVersion, Signature, TaprootBuilder, TaprootSpendInfo}; 18 | use bitcoin::transaction::Version; 19 | use eyre::Result; 20 | use indicatif::{ProgressBar, ProgressStyle}; 21 | use tokio::sync::oneshot; 22 | 23 | use atomicals_electrumx::r#type::Utxo; 24 | 25 | use crate::atomicals_packer::{Fees, Payload, PayloadWrapper, TickerData}; 26 | use crate::miner::Miner; 27 | use crate::util; 28 | use crate::util::{format_speed, GLOBAL_OPTS, tx2bytes}; 29 | 30 | #[derive(Debug, Clone)] 31 | pub struct PayloadScript { 32 | pub payload: PayloadWrapper, 33 | pub payload_encoded: Vec, 34 | funding_spk: ScriptBuf, 35 | reveal_script: ScriptBuf, 36 | reveal_spend_info: TaprootSpendInfo, 37 | pub fees: Fees, 38 | reveal_spk: ScriptBuf, 39 | } 40 | 41 | #[derive(Debug)] 42 | pub struct CommitInfo { 43 | pub commit_tx: Transaction, 44 | commit_output: Vec, 45 | payload_script: PayloadScript, 46 | } 47 | 48 | struct PsbtData { 49 | psbt: Psbt, 50 | payload_script: PayloadScript, 51 | commit_output: Vec, 52 | commit_prev_outs: [TxOut; 1], 53 | } 54 | 55 | /// AtomicalsBuilder is a builder for build available atomicals mining transactions 56 | /// As we all know, the commit tx and reveal tx are the pair transaction in ordinals 57 | /// So we only need know the tx in, and we can build the commit tx and reveal tx without any other information 58 | pub struct AtomicalsWorker { 59 | funding_wallet: Keypair, 60 | miner: RefCell>, 61 | } 62 | 63 | impl AtomicalsWorker { 64 | const BASE_BYTES: f64 = 10.5; 65 | const INPUT_BYTES_BASE: f64 = 67.5; 66 | // Estimated 8-byte value, with a script size of one byte. 67 | // The actual size of the value is determined by the final nonce. 68 | const OP_RETURN_BYTES: f64 = 21. + 8. + 1.; 69 | const OUTPUT_BYTES_BASE: f64 = 31.; 70 | const REVEAL_INPUT_BYTES_BASE: f64 = 41.; 71 | 72 | const VERSION: Version = Version::ONE; 73 | const LOCK_TIME: LockTime = LockTime::ZERO; 74 | pub fn new(funding_wallet: Keypair, miner: Box) -> Self { 75 | AtomicalsWorker { 76 | funding_wallet, 77 | miner: RefCell::new(miner), 78 | } 79 | } 80 | /// Generate the payload script 81 | /// The payload script is the script that will be used in the reveal tx 82 | pub fn generate_payload_script(&self, ticker_data: &TickerData) -> Result { 83 | let TickerData { 84 | secp, 85 | satsbyte, 86 | additional_outputs, 87 | ticker, 88 | .. 89 | } = ticker_data; 90 | 91 | let payload = PayloadWrapper { 92 | args: { 93 | Payload { 94 | mint_ticker: ticker.to_string(), 95 | } 96 | }, 97 | }; 98 | 99 | let payload_encoded = util::cbor(&payload)?; 100 | 101 | let funding_wallet = GLOBAL_OPTS.funding_wallet.as_ref().unwrap(); 102 | let funding_wallet_x_only_public_key = funding_wallet.x_only_public_key(secp); 103 | 104 | let reveal_script = 105 | util::build_reveal_script(&funding_wallet_x_only_public_key, "dmt", &payload_encoded); 106 | 107 | let reveal_spend_info = TaprootBuilder::new() 108 | .add_leaf(0, reveal_script.clone())? 109 | .finalize(secp, funding_wallet_x_only_public_key) 110 | .unwrap(); 111 | let fees = Self::fees_of( 112 | satsbyte.to_owned(), 113 | reveal_script.as_bytes().len(), 114 | additional_outputs, 115 | true, 116 | ); 117 | 118 | let reveal_spk = ScriptBuf::new_p2tr( 119 | secp, 120 | reveal_spend_info.internal_key(), 121 | reveal_spend_info.merkle_root(), 122 | ); 123 | let funding_spk = funding_wallet.p2tr_address(secp).script_pubkey(); 124 | Ok(PayloadScript { 125 | payload, 126 | payload_encoded, 127 | funding_spk, 128 | reveal_script, 129 | reveal_spend_info, 130 | reveal_spk, 131 | fees, 132 | }) 133 | } 134 | 135 | fn build_common_outputs( 136 | &self, 137 | satsbyte: u64, 138 | funding_utxo: &Utxo, 139 | payload_script: &PayloadScript, 140 | ) -> Vec { 141 | let PayloadScript { 142 | fees, 143 | reveal_spk, 144 | funding_spk, 145 | .. 146 | } = payload_script; 147 | 148 | { 149 | let spend = TxOut { 150 | value: Amount::from_sat(fees.reveal_and_outputs), 151 | script_pubkey: reveal_spk.clone(), 152 | }; 153 | let refund = { 154 | let r = funding_utxo 155 | .value 156 | .saturating_sub(fees.reveal_and_outputs) 157 | .saturating_sub( 158 | fees.commit + (Self::OUTPUT_BYTES_BASE * satsbyte as f64).floor() as u64, 159 | ); 160 | 161 | if r > 0 { 162 | Some(TxOut { 163 | value: Amount::from_sat(r), 164 | script_pubkey: funding_spk.clone(), 165 | }) 166 | } else { 167 | None 168 | } 169 | }; 170 | 171 | if let Some(r) = refund { 172 | vec![spend, r] 173 | } else { 174 | vec![spend] 175 | } 176 | } 177 | } 178 | 179 | fn build_psbt_data( 180 | &self, 181 | data: &TickerData, 182 | satsbyte: u64, 183 | funding_utxo: Utxo, 184 | sequence: u32, 185 | commit_input: Vec, 186 | ) -> Result { 187 | let payload_script = self.generate_payload_script(data)?; 188 | let PayloadScript { funding_spk, .. } = payload_script.clone(); 189 | 190 | let commit_output = self.build_common_outputs(satsbyte, &funding_utxo, &payload_script); 191 | let commit_prev_outs = [TxOut { 192 | value: Amount::from_sat(funding_utxo.value), 193 | script_pubkey: funding_spk.clone(), 194 | }]; 195 | 196 | let psbt = Psbt::from_unsigned_tx(Transaction { 197 | version: Self::VERSION, 198 | lock_time: Self::LOCK_TIME, 199 | input: { 200 | let mut i = commit_input.to_owned(); 201 | i[0].sequence = Sequence(sequence); 202 | i 203 | }, 204 | output: commit_output.clone(), 205 | })?; 206 | 207 | Ok(PsbtData { 208 | psbt, 209 | payload_script, 210 | commit_output, 211 | commit_prev_outs, 212 | }) 213 | } 214 | 215 | pub fn build_commit_tx(&self, data: &TickerData, funding_utxo: Utxo) -> Result { 216 | let TickerData { 217 | secp, 218 | satsbyte, 219 | bitworkc, 220 | .. 221 | } = data.clone(); 222 | 223 | let funding_wallet = GLOBAL_OPTS.funding_wallet.as_ref().unwrap(); 224 | 225 | let commit_input = vec![TxIn { 226 | previous_output: OutPoint::new(funding_utxo.txid.parse()?, funding_utxo.vout), 227 | ..Default::default() 228 | }]; 229 | 230 | let (compute_done_sender, compute_done_receiver) = oneshot::channel(); 231 | 232 | let counter = self.miner.borrow_mut().mine_commit_counter(); 233 | let handle = thread::spawn(move || { 234 | create_hash_rate_bar( 235 | "Commit mining: ".to_string(), 236 | move || counter.load(Ordering::Relaxed), 237 | compute_done_receiver, 238 | ); 239 | }); 240 | 241 | let mut psbt_data = self.build_psbt_data( 242 | data, 243 | satsbyte, 244 | funding_utxo.clone(), 245 | 0, 246 | commit_input.clone(), 247 | )?; 248 | 249 | // If there have not found the target sequence, we will return the None 250 | let mut psbt = psbt_data.psbt.clone(); 251 | 252 | let mut serialize_tx = vec![]; 253 | psbt.unsigned_tx 254 | .consensus_encode(&mut serialize_tx) 255 | .unwrap(); 256 | 257 | let mut miner = self.miner.borrow_mut(); 258 | let commit_tx = miner.mine_commit(&serialize_tx, bitworkc.clone(), 0, None); 259 | 260 | psbt.unsigned_tx = deserialize(commit_tx.as_slice()).expect("Cant not deserialize the commit tx"); 261 | 262 | // set it done 263 | compute_done_sender 264 | .send(()) 265 | .expect("send done signal failed"); 266 | 267 | // sign it 268 | 269 | let tap_key_sig = { 270 | let commit_hty = TapSighashType::Default; 271 | let h = SighashCache::new(&psbt_data.psbt.unsigned_tx) 272 | .taproot_key_spend_signature_hash( 273 | 0, 274 | &Prevouts::All(&psbt_data.commit_prev_outs), 275 | commit_hty, 276 | )?; 277 | let m = Message::from_digest(h.to_byte_array()); 278 | 279 | Signature { 280 | sig: secp.sign_schnorr(&m, &funding_wallet.tap_tweak(&secp, None).to_inner()), 281 | hash_ty: commit_hty, 282 | } 283 | }; 284 | 285 | psbt_data.psbt.inputs[0] = Input { 286 | witness_utxo: Some(psbt_data.commit_prev_outs[0].clone()), 287 | final_script_witness: Some(Witness::from_slice(&[tap_key_sig.to_vec()])), 288 | tap_internal_key: Some(funding_wallet.x_only_public_key(&secp)), 289 | ..Default::default() 290 | }; 291 | 292 | let final_tx = psbt_data.psbt.extract_tx_unchecked_fee_rate(); 293 | handle.join().expect("join thread failed"); 294 | 295 | Ok(CommitInfo { 296 | commit_tx: final_tx, 297 | commit_output: psbt_data.commit_output, 298 | payload_script: psbt_data.payload_script, 299 | }) 300 | } 301 | 302 | pub fn build_reveal_tx( 303 | &self, 304 | commit_info: CommitInfo, 305 | data: &TickerData, 306 | ) -> Result { 307 | let TickerData { 308 | secp, 309 | additional_outputs, 310 | bitworkr, 311 | .. 312 | } = data.clone(); 313 | let CommitInfo { 314 | commit_tx, 315 | commit_output, 316 | payload_script, 317 | } = commit_info; 318 | 319 | let PayloadScript { 320 | reveal_script, 321 | reveal_spend_info, 322 | .. 323 | } = payload_script.clone(); 324 | // build reveal tx 325 | let reveal_lh = reveal_script.tapscript_leaf_hash(); 326 | let build_psbt = |nonce: Option| -> Result { 327 | let mut psbt = Psbt::from_unsigned_tx(Transaction { 328 | version: Self::VERSION, 329 | lock_time: Self::LOCK_TIME, 330 | input: vec![TxIn { 331 | previous_output: OutPoint::new(commit_tx.txid(), 0), 332 | sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, 333 | ..Default::default() 334 | }], 335 | output: additional_outputs.clone(), 336 | })?; 337 | if let Some(nonce) = nonce { 338 | psbt.unsigned_tx.output.push(TxOut { 339 | value: Amount::ZERO, 340 | script_pubkey: util::time_nonce_script(nonce), 341 | }); 342 | psbt.outputs.push(Default::default()); 343 | } 344 | Ok(psbt) 345 | }; 346 | 347 | let reveal_tx = if let Some(bitworkr) = bitworkr { 348 | let (compute_done_sender, compute_done_receiver) = oneshot::channel(); 349 | let counter = self.miner.borrow_mut().mine_reveal_counter(); 350 | let handle = thread::spawn(move || { 351 | create_hash_rate_bar( 352 | "Reveal mining: ".to_string(), 353 | move || counter.load(Ordering::Relaxed), 354 | compute_done_receiver, 355 | ); 356 | }); 357 | 358 | let mut reveal_psbt = build_psbt(Some(0))?; 359 | let tx_byte = tx2bytes(&reveal_psbt.unsigned_tx); 360 | 361 | let mut miner = self.miner.borrow_mut(); 362 | let reveal_tx = miner.mine_reveal(&tx_byte, bitworkr.clone(), 0, None); 363 | 364 | compute_done_sender 365 | .send(()) 366 | .expect("send done signal failed"); 367 | 368 | reveal_psbt.unsigned_tx = 369 | deserialize(reveal_tx.as_slice()).expect("Can not deserialize reveal tx"); 370 | 371 | let mut serialize_tx = vec![]; 372 | reveal_psbt 373 | .unsigned_tx 374 | .consensus_encode(&mut serialize_tx) 375 | .unwrap(); 376 | 377 | self.sign_reveal_psbt( 378 | &secp, 379 | &mut reveal_psbt, 380 | &commit_output[0], 381 | &reveal_lh, 382 | &reveal_spend_info, 383 | &reveal_script, 384 | )?; 385 | 386 | handle.join().expect("join thread failed"); 387 | reveal_psbt.extract_tx_unchecked_fee_rate() 388 | } else { 389 | let mut reveal_psbt = build_psbt(None)?; 390 | self.sign_reveal_psbt( 391 | &secp, 392 | &mut reveal_psbt, 393 | &commit_output[0], 394 | &reveal_lh, 395 | &reveal_spend_info, 396 | &reveal_script, 397 | )?; 398 | 399 | // Remove this clone if not needed in the future. 400 | reveal_psbt.extract_tx_unchecked_fee_rate() 401 | }; 402 | 403 | Ok(reveal_tx) 404 | } 405 | 406 | fn sign_reveal_psbt( 407 | &self, 408 | secp: &Secp256k1, 409 | psbt: &mut Psbt, 410 | commit_output: &TxOut, 411 | reveal_left_hash: &TapLeafHash, 412 | reveal_spend_info: &TaprootSpendInfo, 413 | reveal_script: &ScriptBuf, 414 | ) -> Result<()> { 415 | let signer = &self.funding_wallet; 416 | let reveal_hty = TapSighashType::SinglePlusAnyoneCanPay; 417 | let tap_key_sig = { 418 | let h = SighashCache::new(&psbt.unsigned_tx).taproot_script_spend_signature_hash( 419 | 0, 420 | &Prevouts::One(0, commit_output.to_owned()), 421 | *reveal_left_hash, 422 | reveal_hty, 423 | )?; 424 | let m = Message::from_digest(h.to_byte_array()); 425 | 426 | Signature { 427 | sig: secp.sign_schnorr(&m, signer), 428 | hash_ty: reveal_hty, 429 | } 430 | }; 431 | 432 | psbt.inputs[0] = Input { 433 | witness_utxo: Some(commit_output.to_owned()), 434 | tap_internal_key: Some(reveal_spend_info.internal_key()), 435 | tap_merkle_root: reveal_spend_info.merkle_root(), 436 | final_script_witness: { 437 | let mut w = Witness::new(); 438 | 439 | w.push(tap_key_sig.to_vec()); 440 | w.push(reveal_script.as_bytes()); 441 | w.push( 442 | reveal_spend_info 443 | .control_block(&(reveal_script.to_owned(), LeafVersion::TapScript)) 444 | .unwrap() 445 | .serialize(), 446 | ); 447 | 448 | Some(w) 449 | }, 450 | ..Default::default() 451 | }; 452 | 453 | Ok(()) 454 | } 455 | 456 | fn fees_of( 457 | satsbyte: u64, 458 | reveal_script_len: usize, 459 | additional_outputs: &[TxOut], 460 | has_bitworkr: bool, 461 | ) -> Fees { 462 | let satsbyte = satsbyte as f64; 463 | let commit = { 464 | (satsbyte * (Self::BASE_BYTES + Self::INPUT_BYTES_BASE + Self::OUTPUT_BYTES_BASE + 1.)) 465 | .ceil() as u64 466 | }; 467 | let reveal = { 468 | let compact_input_bytes = if reveal_script_len <= 252 { 469 | 1. 470 | } else if reveal_script_len <= 0xFFFF { 471 | 3. 472 | } else if reveal_script_len <= 0xFFFFFFFF { 473 | 5. 474 | } else { 475 | 9. 476 | }; 477 | let op_return_bytes = if has_bitworkr { 478 | Self::OP_RETURN_BYTES 479 | } else { 480 | 0. 481 | }; 482 | 483 | (satsbyte 484 | * (Self::BASE_BYTES 485 | + Self::REVEAL_INPUT_BYTES_BASE 486 | + compact_input_bytes 487 | + reveal_script_len as f64 / 4. 488 | + additional_outputs.len() as f64 * (Self::OUTPUT_BYTES_BASE + 1.) 489 | + op_return_bytes)) 490 | .ceil() as u64 491 | }; 492 | let outputs = additional_outputs 493 | .iter() 494 | .map(|o| o.value.to_sat()) 495 | .sum::(); 496 | let commit_and_reveal = commit + reveal; 497 | let commit_and_reveal_and_outputs = commit_and_reveal + outputs; 498 | 499 | Fees { 500 | commit, 501 | // commit_and_reveal, 502 | commit_and_reveal_and_outputs, 503 | // reveal, 504 | reveal_and_outputs: reveal + outputs, 505 | } 506 | } 507 | } 508 | fn create_hash_rate_bar(prefix: String, count_fn: F, mut done: oneshot::Receiver<()>) 509 | where 510 | F: Fn() -> u64 + Send + 'static, 511 | { 512 | let style = ProgressStyle::default_spinner() 513 | .template("{prefix} {spinner:.green} [{elapsed_precise}] {msg}") 514 | .unwrap(); 515 | let start_time = Instant::now(); 516 | let bar = ProgressBar::new(0); 517 | bar.set_prefix(prefix); 518 | bar.set_style(style); 519 | 520 | while done.try_recv().is_err() { 521 | let hashes_per_second = count_fn(); 522 | 523 | bar.set_message(format!( 524 | "Hash rate: {}/s", 525 | format_speed(hashes_per_second as f64 / start_time.elapsed().as_secs_f64()) 526 | )); 527 | bar.tick(); 528 | 529 | // sample every 100 ms 530 | thread::sleep(Duration::from_millis(100)); 531 | } 532 | bar.finish(); 533 | } 534 | #[cfg(test)] 535 | mod test { 536 | use std::sync::atomic::Ordering; 537 | use std::sync::atomic::Ordering::SeqCst; 538 | 539 | use bitcoin::consensus::{deserialize, encode}; 540 | use bitcoin::Network; 541 | use tokio::time::Instant; 542 | use tracing::info; 543 | 544 | use atomicals_electrumx::{Api, ElectrumXBuilder}; 545 | 546 | use crate::atomicals_packer::AtomicalsPacker; 547 | use crate::atomicals_worker::AtomicalsWorker; 548 | use crate::miner::cpu::CpuMiner; 549 | use crate::miner::Miner; 550 | use crate::util::{GLOBAL_OPTS, log, time}; 551 | use crate::utils::bitworkc::BitWork; 552 | 553 | #[tokio::test] 554 | async fn test_mint_work() { 555 | log(); 556 | let electrumx = ElectrumXBuilder::testnet().build().unwrap(); 557 | let packer = AtomicalsPacker::new(electrumx.clone(), Network::Testnet, true); 558 | let ft = packer.get_bitwork_info("b911".to_string()).await.unwrap(); 559 | info!("{:?}", ft); 560 | let worker_data = packer 561 | .generate_worker(&ft, GLOBAL_OPTS.primary_wallet.as_ref().unwrap().clone()) 562 | .await 563 | .unwrap(); 564 | info!("{:?}", worker_data); 565 | 566 | let funding_wallet = &GLOBAL_OPTS 567 | .funding_wallet 568 | .as_ref() 569 | .unwrap() 570 | .p2tr_address(&worker_data.secp); 571 | let utxo = electrumx 572 | .wait_until_utxo(funding_wallet.to_string(), worker_data.satsbyte) 573 | .await 574 | .unwrap(); 575 | info!("{:?}", utxo); 576 | 577 | let miner = CpuMiner::new(); 578 | 579 | let workder = AtomicalsWorker::new( 580 | GLOBAL_OPTS 581 | .funding_wallet 582 | .as_ref() 583 | .unwrap() 584 | .keypair(&worker_data.secp), 585 | Box::new(miner), 586 | ); 587 | 588 | let result = workder.build_commit_tx(&worker_data, utxo).unwrap(); 589 | info!("{:?}", result); 590 | let commit_hex = encode::serialize_hex(&result.commit_tx); 591 | electrumx.broadcast(commit_hex).await.unwrap(); 592 | // 593 | let txid = result.commit_tx.txid(); 594 | assert!(txid.to_string().starts_with("1234567")); 595 | 596 | let reveal = workder.build_reveal_tx(result, &worker_data).unwrap(); 597 | 598 | info!("{:?}", reveal); 599 | let reveal_hex = encode::serialize_hex(&reveal); 600 | electrumx.broadcast(reveal_hex).await.unwrap(); 601 | } 602 | // commit 01000000012a912f654cc1bd88da5b8a54c52b6dd60b6e831bfba52b32c1314cd17c5634120100000000feffffff024c05000000000000225120e3d5a4789dc4982cfda563c8c23f988f505e481bf9602f7ba5b1045e44e0392000b09a3b0000000022512032447fe28750a7e2b18af49d89a359a81c69bbf6f3db05feb7e8e1688f37e4c200000000 603 | 604 | #[tokio::test] 605 | async fn test_commit_work() { 606 | log(); 607 | let tx = "01000000012a912f654cc1bd88da5b8a54c52b6dd60b6e831bfba52b32c1314cd17c5634120100000000feffffff024c05000000000000225120e3d5a4789dc4982cfda563c8c23f988f505e481bf9602f7ba5b1045e44e0392000b09a3b0000000022512032447fe28750a7e2b18af49d89a359a81c69bbf6f3db05feb7e8e1688f37e4c200000000"; 608 | let tx = hex::decode(tx).unwrap(); 609 | let mut miner = CpuMiner::new(); 610 | let bitwork = BitWork::new("8888888.14".to_string()).unwrap(); 611 | 612 | let now = Instant::now(); 613 | let commit_count = miner.mine_commit_counter().clone(); 614 | let nonce = miner.mine_commit(&tx, bitwork, 0, Some(time() as u32)); 615 | let commit_count = commit_count.load(SeqCst); 616 | info!( 617 | "duration:{:?}, count:{:?}", 618 | now.elapsed(), 619 | commit_count 620 | ); 621 | 622 | let tx:bitcoin::Transaction = deserialize(nonce.as_slice()).unwrap(); 623 | println!("{}",tx.txid()); 624 | } 625 | #[tokio::test] 626 | async fn test_reveal_work() { 627 | log(); 628 | let tx = "01000000017b7afa047d43cb34409d453e11fc048314dd2ee58a5b20c1b0f6a8077b5634120000000000fdffffff02e803000000000000225120adb58bdbccaa9fdd6594859354b502214e3405a74d772a60e255e233468c4c7900000000000000000a6a08000000000000000100000000"; 629 | let tx = hex::decode(tx).unwrap(); 630 | let mut miner = CpuMiner::new(); 631 | let bitwork = BitWork::new("1234567.11".to_string()).unwrap(); 632 | 633 | let now = Instant::now(); 634 | let commit_count = miner.mine_reveal_counter().load(Ordering::Relaxed); 635 | let reveal_tx = miner.mine_reveal(&tx, bitwork, 0, None); 636 | 637 | info!("duration:{:?}, count:{:?}", now.elapsed(), commit_count); 638 | 639 | let tx: bitcoin::Transaction = deserialize(reveal_tx.as_slice()).unwrap(); 640 | println!("{}", tx.txid()) 641 | } 642 | } 643 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate lazy_static; 2 | 3 | use std::sync::atomic::Ordering; 4 | use std::time::Instant; 5 | 6 | use bitcoin::consensus::encode; 7 | use bitcoin::key::Secp256k1; 8 | use bitcoin::Network; 9 | use colored::*; 10 | use eyre::{eyre, Result}; 11 | use ocl::{Device, Platform}; 12 | use prettytable::{Cell, Row, Table}; 13 | use tracing::{info, subscriber, warn}; 14 | use tracing_subscriber::fmt::format::Format; 15 | 16 | use atomicals_electrumx::{Api, ElectrumXBuilder}; 17 | use atomicals_packer::AtomicalsPacker; 18 | 19 | use crate::atomicals_worker::{AtomicalsWorker, PayloadScript}; 20 | use crate::miner::{create_miner, Miner}; 21 | use crate::miner::cpu::CpuMiner; 22 | use crate::miner::gpu::GpuMiner; 23 | use crate::util::{format_speed, get_cpu_desc, GLOBAL_OPTS}; 24 | use crate::utils::bitworkc::BitWork; 25 | 26 | pub mod atomicals_packer; 27 | pub mod atomicals_worker; 28 | mod miner; 29 | mod util; 30 | mod utils; 31 | 32 | #[cfg(not(target_pointer_width = "64"))] 33 | compile_error!("This program requires a 64-bit architecture."); 34 | 35 | #[tokio::main] 36 | async fn main() { 37 | dotenvy::dotenv().ok(); 38 | 39 | let version = env!("CARGO_PKG_VERSION"); 40 | let opts = GLOBAL_OPTS.clone(); 41 | 42 | if GLOBAL_OPTS.verbose { 43 | let format = Format::default(); 44 | let subscriber = tracing_subscriber::fmt() 45 | .with_max_level(tracing::Level::DEBUG) 46 | .event_format(format) 47 | .finish(); 48 | subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); 49 | } else { 50 | let format = Format::default() 51 | .without_time() 52 | .with_target(false) 53 | .with_level(true); 54 | let subscriber = tracing_subscriber::fmt() 55 | .event_format(format) 56 | .with_max_level(tracing::Level::INFO) 57 | .finish(); 58 | 59 | subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); 60 | }; 61 | 62 | let latest_version = get_latest_version().await.unwrap_or(version.to_owned()); 63 | 64 | println!( 65 | "{}", 66 | " 67 | 68 | 69 | ██████╗ ██████╗ ██╗ ██╗ ⚛️╗██████╗ ███████╗██████╗ 70 | ██╔════╝██╔═══██╗██║ ██║ ██║██╔══██╗██╔════╝██╔══██╗ 71 | ██║ ██║ ██║██║ ██║ ██║██║ ██║█████╗ ██████╔╝ 72 | ██║ ██║ ██║██║ ██║ ██║██║ ██║██╔══╝ ██╔══██╗ 73 | ╚██████╗╚██████╔╝███████╗███████╗██║██████╔╝███████╗██║ ██║ 74 | ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝" 75 | .bright_red() 76 | ); 77 | 78 | let twitter = "Author: @BoxMrChen https://x.com/BoxMrChen".blue(); 79 | let boxchen = "@BoxMrChen".yellow(); 80 | println!( 81 | r#" 82 | Made with ❤️ by {boxchen}, @atomicalsir, @atomicals 83 | {twitter} 84 | Github: https://github.com/nishuzumi/collider 85 | Miner Version: {version}, Latest Version: {latest_version} 86 | 87 | "# 88 | ); 89 | 90 | let v1 = semver::Version::parse(version).unwrap(); 91 | let v2 = semver::Version::parse(&latest_version).unwrap(); 92 | 93 | if v1 < v2 { 94 | warn!("Please download the latest version, https://github.com/nishuzumi/collider/releases/latest"); 95 | 96 | if v1.major < v2.major || (v1.major == v2.major && v1.minor < v2.minor) { 97 | std::process::exit(0); 98 | } 99 | } 100 | 101 | if opts.verbose { 102 | tracing::debug!("Verbose mode is enabled"); 103 | } 104 | 105 | if opts.benchmark { 106 | info!("Running collider benchmark..."); 107 | collider_benchmark(); 108 | } else { 109 | info!("Starting collider..."); 110 | mint().await; 111 | } 112 | } 113 | 114 | async fn get_latest_version() -> Result { 115 | let url = "https://raw.githubusercontent.com/nishuzumi/collider/main/Cargo.toml"; 116 | let response = reqwest::get(url).await?; 117 | let cargo_toml_content = response.text().await?; 118 | 119 | let cargo_toml: toml::Value = toml::from_str(&cargo_toml_content)?; 120 | 121 | if let Some(version) = cargo_toml["package"]["version"].as_str() { 122 | Ok(version.to_string()) 123 | } else { 124 | Err(eyre!("Version not found in Cargo.toml")) 125 | } 126 | } 127 | 128 | fn collider_benchmark() { 129 | info!("{}", "Benchmarking, will take a few minutes...".yellow()); 130 | 131 | let commit_tx = "01000000012a912f654cc1bd88da5b8a54c52b6dd60b6e831bfba52b32c1314cd17c5634120100000000feffffff024c05000000000000225120e3d5a4789dc4982cfda563c8c23f988f505e481bf9602f7ba5b1045e44e0392000b09a3b0000000022512032447fe28750a7e2b18af49d89a359a81c69bbf6f3db05feb7e8e1688f37e4c200000000"; 132 | let commit_tx = hex::decode(commit_tx).unwrap(); 133 | 134 | let reveal_tx = "01000000017b7afa047d43cb34409d453e11fc048314dd2ee58a5b20c1b0f6a8077b5634120000000000fdffffff02e803000000000000225120adb58bdbccaa9fdd6594859354b502214e3405a74d772a60e255e233468c4c7900000000000000000a6a08000000000000000100000000"; 135 | let reveal_tx = hex::decode(reveal_tx).unwrap(); 136 | 137 | let miners: Vec> = vec![Box::new(CpuMiner::new()), Box::new(GpuMiner::new())]; 138 | 139 | let bitwork = BitWork::new("1234567.14".to_string()).unwrap(); 140 | let bitwork_r = BitWork::new("1234567.11".to_string()).unwrap(); 141 | 142 | let mut table = Table::new(); 143 | table.add_row(Row::new(vec![ 144 | Cell::new("Device"), 145 | Cell::new("Commit Hash Rate (M/s)"), 146 | Cell::new("Reveal Hash Rate (M/s)"), 147 | ])); 148 | for mut miner in miners { 149 | // commit 150 | let now = Instant::now(); 151 | let _ = miner 152 | .mine_commit(&commit_tx, bitwork.clone(), 0, None); 153 | let elapsed = now.elapsed(); 154 | let hash_rate = 155 | miner.mine_commit_counter().load(Ordering::SeqCst) as f64 / elapsed.as_secs_f64(); 156 | 157 | let now = Instant::now(); 158 | let _ = miner 159 | .mine_reveal(&reveal_tx, bitwork_r.clone(), 0, None); 160 | let elapsed = now.elapsed(); 161 | let reveal_hash_rate = 162 | miner.mine_reveal_counter().load(Ordering::SeqCst) as f64 / elapsed.as_secs_f64(); 163 | 164 | let commit_str = format!("{}/s", format_speed(hash_rate)); 165 | let reveal_str = format!("{}/s", format_speed(reveal_hash_rate).as_str()); 166 | 167 | table.add_row(Row::new(vec![ 168 | Cell::new(miner.name()), 169 | Cell::new(commit_str.as_str()), 170 | Cell::new(reveal_str.as_str()), 171 | ])); 172 | } 173 | 174 | println!(); 175 | println!("{}", "Benchmark results:".blue()); 176 | println!("CPU Name: {}", get_cpu_desc()); 177 | let platform = Platform::default(); 178 | let devices = Device::list_all(platform).unwrap(); 179 | 180 | for device in devices.iter() { 181 | println!( 182 | "GPU Name: {} (OpenCL Version: {})", 183 | device.name().unwrap(), 184 | device.version().unwrap() 185 | ); 186 | } 187 | table.printstd(); 188 | } 189 | 190 | async fn mint() { 191 | let opts = GLOBAL_OPTS.clone(); 192 | 193 | let (electrumx, network) = if opts.testnet { 194 | info!("Using testnet"); 195 | ( 196 | ElectrumXBuilder::testnet().build().unwrap(), 197 | Network::Testnet, 198 | ) 199 | } else { 200 | info!("Using mainnet"); 201 | let mut client = ElectrumXBuilder::default(); 202 | if let Some(api_url) = opts.api_url { 203 | client = client.base_uri(api_url); 204 | } 205 | 206 | (client.build().unwrap(), Network::Bitcoin) 207 | }; 208 | 209 | // print primary wallet address 210 | let secp = Secp256k1::new(); 211 | info!( 212 | "Primary wallet address: {}", 213 | opts.primary_wallet.clone().unwrap() 214 | ); 215 | info!( 216 | "Funding wallet address: {}", 217 | opts.funding_wallet.as_ref().unwrap().p2tr_address(&secp) 218 | ); 219 | 220 | let packer = AtomicalsPacker::new(electrumx.clone(), network, false); 221 | 222 | let ft = packer 223 | .get_bitwork_info(opts.ticker.unwrap().clone()) 224 | .await 225 | .expect("get bitwork info error"); 226 | 227 | info!("Bitwork info: {}", ft); 228 | let worker_data = packer 229 | .generate_worker(&ft, opts.primary_wallet.clone().unwrap()) 230 | .await 231 | .expect("generate worker error"); 232 | 233 | let funding_wallet = opts.funding_wallet.as_ref().unwrap().p2tr_address(&secp); 234 | let miner = create_miner(); 235 | 236 | let worker = AtomicalsWorker::new( 237 | GLOBAL_OPTS.funding_wallet.as_ref().unwrap().keypair(&secp), 238 | miner, 239 | ); 240 | 241 | // Generate fake payload script for fee 242 | let PayloadScript { fees, .. } = worker 243 | .generate_payload_script(&worker_data) 244 | .expect("Cannot generate payload script"); 245 | 246 | let utxo = electrumx 247 | .wait_until_utxo( 248 | funding_wallet.to_string(), 249 | fees.commit_and_reveal_and_outputs, 250 | ) 251 | .await 252 | .expect("wait until utxo error"); 253 | 254 | let commit_result = worker 255 | .build_commit_tx(&worker_data, utxo) 256 | .expect("build commit tx error"); 257 | 258 | let commit_hex = encode::serialize_hex(&commit_result.commit_tx); 259 | // print the commit hex content 260 | let testnet = if opts.testnet { "testnet/" } else { "" }; 261 | info!("🔍 Commit hex: {}", commit_hex); 262 | #[cfg(feature = "boardcast")] 263 | { 264 | electrumx 265 | .broadcast(commit_hex) 266 | .await 267 | .expect("broadcast commit tx error"); 268 | info!( 269 | "🔍🎺 Commit tx broadcasted successfully! 🚀 {}", 270 | format!( 271 | "https://mempool.space/{}tx/{}", 272 | testnet, 273 | commit_result.commit_tx.txid() 274 | ) 275 | .blue() 276 | ); 277 | } 278 | 279 | let reveal_result = worker 280 | .build_reveal_tx(commit_result, &worker_data) 281 | .expect("build reveal tx error"); 282 | 283 | let reveal_hex = encode::serialize_hex(&reveal_result); 284 | // print the reveal hex content 285 | info!("🔓 Reveal hex: {}", reveal_hex); 286 | #[cfg(feature = "boardcast")] 287 | { 288 | electrumx 289 | .broadcast(reveal_hex) 290 | .await 291 | .expect("broadcast reveal tx error"); 292 | info!( 293 | "🔓🎺 Reveal tx broadcasted successfully! 🚀 {}", 294 | format!( 295 | "https://mempool.space/{}tx/{}", 296 | testnet, 297 | reveal_result.txid() 298 | ) 299 | .blue() 300 | ); 301 | } 302 | 303 | info!("🎉 Eureka! 💥 The Collider has successfully smashed the problem and computed the result! 🧪✨") 304 | } 305 | -------------------------------------------------------------------------------- /src/miner/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | 3 | !mod.rs 4 | !cpu.rs 5 | !gpu.rs 6 | !ext/sha256d.cl -------------------------------------------------------------------------------- /src/miner/cpu.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | use std::sync::atomic::{AtomicU64, Ordering}; 3 | 4 | use rayon::prelude::*; 5 | use ring::digest::{Context, SHA256}; 6 | 7 | use crate::miner::{find_first_sequence_position, find_time_nonce_script_position, Miner}; 8 | use crate::util::time; 9 | use crate::utils::bitworkc::BitWork; 10 | 11 | pub struct CpuMiner { 12 | commit_counter: Arc, 13 | sequence_count: u32, 14 | reveal_counter: Arc, 15 | } 16 | 17 | impl CpuMiner { 18 | pub fn new() -> CpuMiner { 19 | CpuMiner { 20 | sequence_count: 0x80000000, // enable abs time lock 21 | commit_counter: Arc::new(AtomicU64::new(0)), 22 | reveal_counter: Arc::new(AtomicU64::new(0)), 23 | } 24 | } 25 | pub fn find_seq_by_range_co( 26 | &mut self, 27 | data: &[u8], 28 | target: BitWork, 29 | start: u32, 30 | max: Option, 31 | counter: Option<&AtomicU64>, 32 | ) -> Vec { 33 | self.sequence_count = 0x80000000; 34 | let max = max.unwrap_or_else(|| time() as u32); 35 | let range = 100000u32; 36 | let pos = find_first_sequence_position(data); 37 | loop { 38 | let mut init_hash = Context::new(&SHA256); 39 | init_hash.update(&data[..pos]); 40 | init_hash.update(self.sequence_count.to_le_bytes().as_slice()); 41 | init_hash.update(&data[pos + 4..data.len() - 4]); 42 | 43 | // work forever.... 44 | let result = (start..max) 45 | .into_par_iter() 46 | .step_by(range as usize) 47 | .find_map_any(|block_start| { 48 | for i in block_start..=(block_start + range).min(max) { 49 | let mut hash_eng = init_hash.clone(); 50 | // let us find the lock time 51 | hash_eng.update(&i.to_le_bytes()); 52 | let hash2 = hash_eng.finish(); 53 | 54 | let mut context: Context = Context::new(&SHA256); 55 | context.update(hash2.as_ref()); 56 | let second_hash = context.finish(); 57 | let result: &[u8] = second_hash.as_ref(); 58 | 59 | if target.matches(result) { 60 | counter 61 | .map(|c| c.fetch_add((i - block_start) as u64, Ordering::Relaxed)); 62 | 63 | let mut result = Vec::new(); 64 | 65 | result.extend_from_slice(&data[..pos]); 66 | result.extend_from_slice(&self.sequence_count.to_le_bytes()); 67 | result.extend_from_slice(&data[pos + 4..data.len() - 4]); 68 | result.extend_from_slice(&i.to_le_bytes()); 69 | 70 | return Some(result); 71 | } 72 | } 73 | 74 | counter.map(|c| c.fetch_add(range as u64, Ordering::Relaxed)); 75 | None 76 | }); 77 | 78 | if let Some(tx) = result { 79 | return tx; 80 | } 81 | 82 | // I do not think it will overflow 83 | self.sequence_count += 1; 84 | } 85 | } 86 | } 87 | impl Miner for CpuMiner { 88 | fn name(&self) -> &'static str { 89 | "CPU" 90 | } 91 | 92 | fn mine_commit(&mut self, tx: &[u8], bitworkc: BitWork, start: u32, max: Option) -> Vec { 93 | let counter = self.commit_counter.clone(); 94 | self.find_seq_by_range_co(tx, bitworkc, start, max, Some(&counter)) 95 | } 96 | 97 | fn mine_commit_counter(&self) -> Arc { 98 | self.commit_counter.clone() 99 | } 100 | 101 | fn mine_reveal(&mut self, tx: &[u8], bitworkr: BitWork, start: u64, max: Option) -> Vec { 102 | find_return_nonce_by_range_co(tx, bitworkr, start, max, Some(&self.reveal_counter)) 103 | } 104 | 105 | fn mine_reveal_counter(&self) -> Arc { 106 | self.reveal_counter.clone() 107 | } 108 | } 109 | 110 | pub fn find_return_nonce_by_range_co( 111 | data: &[u8], 112 | target: BitWork, 113 | start: u64, 114 | max: Option, 115 | counter: Option<&AtomicU64>, 116 | ) -> Vec { 117 | let max = max.unwrap_or(u64::MAX); 118 | let range = 100000u32; 119 | let pos = find_time_nonce_script_position(data); 120 | let mut init_hash = Context::new(&SHA256); 121 | init_hash.update(&data[..pos]); 122 | 123 | // change it to carry mode 124 | (start..=max).step_by(u32::MAX as usize).find_map(|start| { 125 | let end = (start + u32::MAX as u64).min(max); 126 | let offset = (end - start) as u32; 127 | (0..offset) 128 | .into_par_iter() 129 | .step_by(range as usize) 130 | .find_map_any(|offset| { 131 | for ii in offset..=(range + offset).min(u32::MAX) { 132 | let i = ii as u64 + start; 133 | let mut hash_eng = init_hash.clone(); 134 | hash_eng.update(i.to_le_bytes().as_slice()); 135 | hash_eng.update(&data[pos + 8..]); 136 | let hash2 = hash_eng.finish(); 137 | 138 | let mut context: Context = Context::new(&SHA256); 139 | context.update(hash2.as_ref()); 140 | let second_hash = context.finish(); 141 | let result: &[u8] = second_hash.as_ref(); 142 | 143 | if target.matches(result) { 144 | counter.map(|counter| { 145 | counter.fetch_add((ii - offset) as u64, Ordering::Relaxed) 146 | }); 147 | 148 | let mut result = vec![]; 149 | 150 | result.extend_from_slice(&data[..pos]); 151 | result.extend_from_slice(&i.to_le_bytes()); 152 | result.extend_from_slice(&data[pos + 8..]); 153 | return Some(result); 154 | } 155 | } 156 | 157 | if let Some(counter) = counter { 158 | counter.fetch_add(range as u64, Ordering::Relaxed); 159 | } 160 | None 161 | }) 162 | }).expect("failed to find nonce in u64, crazy") 163 | } 164 | 165 | #[cfg(test)] 166 | mod test{ 167 | use crate::miner::cpu::CpuMiner; 168 | use crate::miner::tests::{mint_commit_by, mint_reveal_by}; 169 | use crate::util::log; 170 | 171 | #[test] 172 | fn test_commit(){ 173 | log(); 174 | let mut miner = CpuMiner::new(); 175 | mint_commit_by(&mut miner); 176 | } 177 | 178 | #[test] 179 | fn test_reveal(){ 180 | log(); 181 | let mut miner = CpuMiner::new(); 182 | mint_reveal_by(&mut miner); 183 | } 184 | 185 | } -------------------------------------------------------------------------------- /src/miner/ext/sha256d.cl: -------------------------------------------------------------------------------- 1 | #ifndef uint8_t 2 | #define uint8_t unsigned char 3 | #endif 4 | 5 | #ifndef uint32_t 6 | #define uint32_t unsigned int 7 | #endif 8 | #ifndef uint64_t 9 | #define uint64_t unsigned long int 10 | #endif 11 | #define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) 12 | #define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) 13 | // Initially for use in SHA-512 14 | #define hashBlockSize_int32 hashBlockSize 15 | #define hashDigestSize_int32 hashDigestSize 16 | #define word unsigned int 17 | 18 | unsigned int SWAP (unsigned int val) 19 | { 20 | return (rotate(((val) & 0x00FF00FF), 24U) | rotate(((val) & 0xFF00FF00), 8U)); 21 | } 22 | 23 | /* 24 | Modified: hash_main function works for any length inputs. 25 | */ 26 | 27 | #define F1(x,y,z) (bitselect(z,y,x)) 28 | #define F0(x,y,z) (bitselect (x, y, ((x) ^ (z)))) 29 | #define mod(x,y) ((x)-((x)/(y)*(y))) 30 | #define shr32(x,n) ((x) >> (n)) 31 | #define rotl32(a,n) rotate ((a), (n)) 32 | 33 | #define S0(x) (rotl32 ((x), 25u) ^ rotl32 ((x), 14u) ^ shr32 ((x), 3u)) 34 | #define S1(x) (rotl32 ((x), 15u) ^ rotl32 ((x), 13u) ^ shr32 ((x), 10u)) 35 | #define S2(x) (rotl32 ((x), 30u) ^ rotl32 ((x), 19u) ^ rotl32 ((x), 10u)) 36 | #define S3(x) (rotl32 ((x), 26u) ^ rotl32 ((x), 21u) ^ rotl32 ((x), 7u)) 37 | 38 | #define SHA256C00 0x428a2f98u 39 | #define SHA256C01 0x71374491u 40 | #define SHA256C02 0xb5c0fbcfu 41 | #define SHA256C03 0xe9b5dba5u 42 | #define SHA256C04 0x3956c25bu 43 | #define SHA256C05 0x59f111f1u 44 | #define SHA256C06 0x923f82a4u 45 | #define SHA256C07 0xab1c5ed5u 46 | #define SHA256C08 0xd807aa98u 47 | #define SHA256C09 0x12835b01u 48 | #define SHA256C0a 0x243185beu 49 | #define SHA256C0b 0x550c7dc3u 50 | #define SHA256C0c 0x72be5d74u 51 | #define SHA256C0d 0x80deb1feu 52 | #define SHA256C0e 0x9bdc06a7u 53 | #define SHA256C0f 0xc19bf174u 54 | #define SHA256C10 0xe49b69c1u 55 | #define SHA256C11 0xefbe4786u 56 | #define SHA256C12 0x0fc19dc6u 57 | #define SHA256C13 0x240ca1ccu 58 | #define SHA256C14 0x2de92c6fu 59 | #define SHA256C15 0x4a7484aau 60 | #define SHA256C16 0x5cb0a9dcu 61 | #define SHA256C17 0x76f988dau 62 | #define SHA256C18 0x983e5152u 63 | #define SHA256C19 0xa831c66du 64 | #define SHA256C1a 0xb00327c8u 65 | #define SHA256C1b 0xbf597fc7u 66 | #define SHA256C1c 0xc6e00bf3u 67 | #define SHA256C1d 0xd5a79147u 68 | #define SHA256C1e 0x06ca6351u 69 | #define SHA256C1f 0x14292967u 70 | #define SHA256C20 0x27b70a85u 71 | #define SHA256C21 0x2e1b2138u 72 | #define SHA256C22 0x4d2c6dfcu 73 | #define SHA256C23 0x53380d13u 74 | #define SHA256C24 0x650a7354u 75 | #define SHA256C25 0x766a0abbu 76 | #define SHA256C26 0x81c2c92eu 77 | #define SHA256C27 0x92722c85u 78 | #define SHA256C28 0xa2bfe8a1u 79 | #define SHA256C29 0xa81a664bu 80 | #define SHA256C2a 0xc24b8b70u 81 | #define SHA256C2b 0xc76c51a3u 82 | #define SHA256C2c 0xd192e819u 83 | #define SHA256C2d 0xd6990624u 84 | #define SHA256C2e 0xf40e3585u 85 | #define SHA256C2f 0x106aa070u 86 | #define SHA256C30 0x19a4c116u 87 | #define SHA256C31 0x1e376c08u 88 | #define SHA256C32 0x2748774cu 89 | #define SHA256C33 0x34b0bcb5u 90 | #define SHA256C34 0x391c0cb3u 91 | #define SHA256C35 0x4ed8aa4au 92 | #define SHA256C36 0x5b9cca4fu 93 | #define SHA256C37 0x682e6ff3u 94 | #define SHA256C38 0x748f82eeu 95 | #define SHA256C39 0x78a5636fu 96 | #define SHA256C3a 0x84c87814u 97 | #define SHA256C3b 0x8cc70208u 98 | #define SHA256C3c 0x90befffau 99 | #define SHA256C3d 0xa4506cebu 100 | #define SHA256C3e 0xbef9a3f7u 101 | #define SHA256C3f 0xc67178f2u 102 | 103 | __constant uint k_sha256[64] = 104 | { 105 | SHA256C00, SHA256C01, SHA256C02, SHA256C03, 106 | SHA256C04, SHA256C05, SHA256C06, SHA256C07, 107 | SHA256C08, SHA256C09, SHA256C0a, SHA256C0b, 108 | SHA256C0c, SHA256C0d, SHA256C0e, SHA256C0f, 109 | SHA256C10, SHA256C11, SHA256C12, SHA256C13, 110 | SHA256C14, SHA256C15, SHA256C16, SHA256C17, 111 | SHA256C18, SHA256C19, SHA256C1a, SHA256C1b, 112 | SHA256C1c, SHA256C1d, SHA256C1e, SHA256C1f, 113 | SHA256C20, SHA256C21, SHA256C22, SHA256C23, 114 | SHA256C24, SHA256C25, SHA256C26, SHA256C27, 115 | SHA256C28, SHA256C29, SHA256C2a, SHA256C2b, 116 | SHA256C2c, SHA256C2d, SHA256C2e, SHA256C2f, 117 | SHA256C30, SHA256C31, SHA256C32, SHA256C33, 118 | SHA256C34, SHA256C35, SHA256C36, SHA256C37, 119 | SHA256C38, SHA256C39, SHA256C3a, SHA256C3b, 120 | SHA256C3c, SHA256C3d, SHA256C3e, SHA256C3f, 121 | }; 122 | 123 | #define SHA256_STEP(F0a,F1a,a,b,c,d,e,f,g,h,x,K) \ 124 | { \ 125 | h += K; \ 126 | h += x; \ 127 | h += S3 (e); \ 128 | h += F1a (e,f,g); \ 129 | d += h; \ 130 | h += S2 (a); \ 131 | h += F0a (a,b,c); \ 132 | } 133 | 134 | #define SHA256_EXPAND(x,y,z,w) (S1 (x) + y + S0 (z) + w) 135 | 136 | static void sha256_process2 (const unsigned int *W, unsigned int *digest) 137 | { 138 | unsigned int a = digest[0]; 139 | unsigned int b = digest[1]; 140 | unsigned int c = digest[2]; 141 | unsigned int d = digest[3]; 142 | unsigned int e = digest[4]; 143 | unsigned int f = digest[5]; 144 | unsigned int g = digest[6]; 145 | unsigned int h = digest[7]; 146 | 147 | unsigned int w0_t = W[0]; 148 | unsigned int w1_t = W[1]; 149 | unsigned int w2_t = W[2]; 150 | unsigned int w3_t = W[3]; 151 | unsigned int w4_t = W[4]; 152 | unsigned int w5_t = W[5]; 153 | unsigned int w6_t = W[6]; 154 | unsigned int w7_t = W[7]; 155 | unsigned int w8_t = W[8]; 156 | unsigned int w9_t = W[9]; 157 | unsigned int wa_t = W[10]; 158 | unsigned int wb_t = W[11]; 159 | unsigned int wc_t = W[12]; 160 | unsigned int wd_t = W[13]; 161 | unsigned int we_t = W[14]; 162 | unsigned int wf_t = W[15]; 163 | 164 | #define ROUND_EXPAND(i) \ 165 | { \ 166 | w0_t = SHA256_EXPAND (we_t, w9_t, w1_t, w0_t); \ 167 | w1_t = SHA256_EXPAND (wf_t, wa_t, w2_t, w1_t); \ 168 | w2_t = SHA256_EXPAND (w0_t, wb_t, w3_t, w2_t); \ 169 | w3_t = SHA256_EXPAND (w1_t, wc_t, w4_t, w3_t); \ 170 | w4_t = SHA256_EXPAND (w2_t, wd_t, w5_t, w4_t); \ 171 | w5_t = SHA256_EXPAND (w3_t, we_t, w6_t, w5_t); \ 172 | w6_t = SHA256_EXPAND (w4_t, wf_t, w7_t, w6_t); \ 173 | w7_t = SHA256_EXPAND (w5_t, w0_t, w8_t, w7_t); \ 174 | w8_t = SHA256_EXPAND (w6_t, w1_t, w9_t, w8_t); \ 175 | w9_t = SHA256_EXPAND (w7_t, w2_t, wa_t, w9_t); \ 176 | wa_t = SHA256_EXPAND (w8_t, w3_t, wb_t, wa_t); \ 177 | wb_t = SHA256_EXPAND (w9_t, w4_t, wc_t, wb_t); \ 178 | wc_t = SHA256_EXPAND (wa_t, w5_t, wd_t, wc_t); \ 179 | wd_t = SHA256_EXPAND (wb_t, w6_t, we_t, wd_t); \ 180 | we_t = SHA256_EXPAND (wc_t, w7_t, wf_t, we_t); \ 181 | wf_t = SHA256_EXPAND (wd_t, w8_t, w0_t, wf_t); \ 182 | } 183 | 184 | #define ROUND_STEP(i) \ 185 | { \ 186 | SHA256_STEP (F0, F1, a, b, c, d, e, f, g, h, w0_t, k_sha256[i + 0]); \ 187 | SHA256_STEP (F0, F1, h, a, b, c, d, e, f, g, w1_t, k_sha256[i + 1]); \ 188 | SHA256_STEP (F0, F1, g, h, a, b, c, d, e, f, w2_t, k_sha256[i + 2]); \ 189 | SHA256_STEP (F0, F1, f, g, h, a, b, c, d, e, w3_t, k_sha256[i + 3]); \ 190 | SHA256_STEP (F0, F1, e, f, g, h, a, b, c, d, w4_t, k_sha256[i + 4]); \ 191 | SHA256_STEP (F0, F1, d, e, f, g, h, a, b, c, w5_t, k_sha256[i + 5]); \ 192 | SHA256_STEP (F0, F1, c, d, e, f, g, h, a, b, w6_t, k_sha256[i + 6]); \ 193 | SHA256_STEP (F0, F1, b, c, d, e, f, g, h, a, w7_t, k_sha256[i + 7]); \ 194 | SHA256_STEP (F0, F1, a, b, c, d, e, f, g, h, w8_t, k_sha256[i + 8]); \ 195 | SHA256_STEP (F0, F1, h, a, b, c, d, e, f, g, w9_t, k_sha256[i + 9]); \ 196 | SHA256_STEP (F0, F1, g, h, a, b, c, d, e, f, wa_t, k_sha256[i + 10]); \ 197 | SHA256_STEP (F0, F1, f, g, h, a, b, c, d, e, wb_t, k_sha256[i + 11]); \ 198 | SHA256_STEP (F0, F1, e, f, g, h, a, b, c, d, wc_t, k_sha256[i + 12]); \ 199 | SHA256_STEP (F0, F1, d, e, f, g, h, a, b, c, wd_t, k_sha256[i + 13]); \ 200 | SHA256_STEP (F0, F1, c, d, e, f, g, h, a, b, we_t, k_sha256[i + 14]); \ 201 | SHA256_STEP (F0, F1, b, c, d, e, f, g, h, a, wf_t, k_sha256[i + 15]); \ 202 | } 203 | 204 | ROUND_STEP (0); 205 | 206 | ROUND_EXPAND(); 207 | ROUND_STEP(16); 208 | 209 | ROUND_EXPAND(); 210 | ROUND_STEP(32); 211 | 212 | ROUND_EXPAND(); 213 | ROUND_STEP(48); 214 | 215 | digest[0] += a; 216 | digest[1] += b; 217 | digest[2] += c; 218 | digest[3] += d; 219 | digest[4] += e; 220 | digest[5] += f; 221 | digest[6] += g; 222 | digest[7] += h; 223 | } 224 | 225 | #define def_hash(funcName, passTag, hashTag) \ 226 | /* The main hashing function */ \ 227 | static void funcName(passTag const unsigned int *pass, int pass_len, hashTag unsigned int* hash) \ 228 | { \ 229 | int plen=pass_len/4; \ 230 | if (mod(pass_len,4)) plen++; \ 231 | \ 232 | unsigned int slidePadding=0; \ 233 | if (mod(pass_len,64)>=56) slidePadding=1; \ 234 | \ 235 | hashTag unsigned int* p = hash; \ 236 | \ 237 | unsigned int W[0x10]={0}; \ 238 | int loops=plen; \ 239 | int curloop=0; \ 240 | unsigned int State[8]={0}; \ 241 | State[0] = 0x6a09e667; \ 242 | State[1] = 0xbb67ae85; \ 243 | State[2] = 0x3c6ef372; \ 244 | State[3] = 0xa54ff53a; \ 245 | State[4] = 0x510e527f; \ 246 | State[5] = 0x9b05688c; \ 247 | State[6] = 0x1f83d9ab; \ 248 | State[7] = 0x5be0cd19; \ 249 | \ 250 | while (loops>0) \ 251 | { \ 252 | W[0x0]=0x0; \ 253 | W[0x1]=0x0; \ 254 | W[0x2]=0x0; \ 255 | W[0x3]=0x0; \ 256 | W[0x4]=0x0; \ 257 | W[0x5]=0x0; \ 258 | W[0x6]=0x0; \ 259 | W[0x7]=0x0; \ 260 | W[0x8]=0x0; \ 261 | W[0x9]=0x0; \ 262 | W[0xA]=0x0; \ 263 | W[0xB]=0x0; \ 264 | W[0xC]=0x0; \ 265 | W[0xD]=0x0; \ 266 | W[0xE]=0x0; \ 267 | W[0xF]=0x0; \ 268 | \ 269 | for (int m=0;loops!=0 && m<16;m++) \ 270 | { \ 271 | W[m]^=SWAP(pass[m+(curloop*16)]); \ 272 | loops--; \ 273 | } \ 274 | \ 275 | if (loops==0 && mod(pass_len,64)!=0) \ 276 | { \ 277 | unsigned int padding=0x80<<(((pass_len+4)-((pass_len+4)/4*4))*8); \ 278 | int v=mod(pass_len,64); \ 279 | W[v/4]|=SWAP(padding); \ 280 | if (slidePadding==0) \ 281 | { \ 282 | /* Let's add length */ \ 283 | W[0x0F]=pass_len*8; \ 284 | } \ 285 | } \ 286 | \ 287 | sha256_process2(W,State); \ 288 | curloop++; \ 289 | } \ 290 | \ 291 | if (slidePadding!=0) { \ 292 | W[0x0]=0x0; \ 293 | W[0x1]=0x0; \ 294 | W[0x2]=0x0; \ 295 | W[0x3]=0x0; \ 296 | W[0x4]=0x0; \ 297 | W[0x5]=0x0; \ 298 | W[0x6]=0x0; \ 299 | W[0x7]=0x0; \ 300 | W[0x8]=0x0; \ 301 | W[0x9]=0x0; \ 302 | W[0xA]=0x0; \ 303 | W[0xB]=0x0; \ 304 | W[0xC]=0x0; \ 305 | W[0xD]=0x0; \ 306 | W[0xE]=0x0; \ 307 | W[0x0F]=pass_len*8; \ 308 | \ 309 | sha256_process2(W,State); \ 310 | } else { \ 311 | if (mod(plen,16)==0) \ 312 | { \ 313 | W[0x0]=0x80000000; \ 314 | W[0x1]=0x0; \ 315 | W[0x2]=0x0; \ 316 | W[0x3]=0x0; \ 317 | W[0x4]=0x0; \ 318 | W[0x5]=0x0; \ 319 | W[0x6]=0x0; \ 320 | W[0x7]=0x0; \ 321 | W[0x8]=0x0; \ 322 | W[0x9]=0x0; \ 323 | W[0xA]=0x0; \ 324 | W[0xB]=0x0; \ 325 | W[0xC]=0x0; \ 326 | W[0xD]=0x0; \ 327 | W[0xE]=0x0; \ 328 | W[0x0F]=pass_len*8; \ 329 | \ 330 | sha256_process2(W,State); \ 331 | } \ 332 | } \ 333 | \ 334 | p[0]=SWAP(State[0]); \ 335 | p[1]=SWAP(State[1]); \ 336 | p[2]=SWAP(State[2]); \ 337 | p[3]=SWAP(State[3]); \ 338 | p[4]=SWAP(State[4]); \ 339 | p[5]=SWAP(State[5]); \ 340 | p[6]=SWAP(State[6]); \ 341 | p[7]=SWAP(State[7]); \ 342 | return; \ 343 | } 344 | 345 | def_hash(hash_global, __global, __global) 346 | def_hash(hash_private, __private, __private) 347 | def_hash(hash_glbl_to_priv, __global, __private) 348 | def_hash(hash_priv_to_glbl, __private, __global) 349 | 350 | #undef F0 351 | #undef F1 352 | #undef S0 353 | #undef S1 354 | #undef S2 355 | #undef S3 356 | 357 | #undef mod 358 | #undef shr32 359 | #undef rotl32 360 | 361 | typedef struct { 362 | int found; 363 | uint32_t results[256]; 364 | } resultBulk; 365 | 366 | typedef struct { 367 | uchar mask[32]; 368 | uchar pattern[32]; 369 | bool ext; 370 | uchar ext_pos; 371 | uchar ext_value; 372 | uchar _padding[5]; 373 | } BitWorkForGPU; 374 | 375 | typedef struct { 376 | uint data_len; 377 | uint pos; 378 | } Params; 379 | 380 | __kernel void sha256d_append( 381 | __global uchar *header, 382 | __global const Params* params, 383 | __global const BitWorkForGPU* bw, 384 | __global resultBulk *output_buffer 385 | ) { 386 | __private uint8_t tempHdr[255]; 387 | __private uint8_t tempDigest[32] = {0}; 388 | 389 | uint header_length = params->data_len; 390 | uint pos = params->pos; 391 | 392 | for (uint x = 0; x < header_length; x++) { 393 | tempHdr[x] = header[x]; 394 | } 395 | 396 | uint id = get_global_id(0); 397 | tempHdr[header_length - 1] = (id >> 24) & 0xFF; 398 | tempHdr[header_length - 2] = (id >> 16) & 0xFF; 399 | tempHdr[header_length - 3] = (id >> 8) & 0xFF; 400 | tempHdr[header_length - 4] = id & 0xFF; 401 | 402 | hash_private(tempHdr,header_length,tempDigest); 403 | 404 | hash_private(tempDigest,32,tempDigest); 405 | 406 | for (int i = 0; i < 32; i++) { 407 | if ((tempDigest[i] & bw->mask[i]) != bw->pattern[i]) { 408 | return; 409 | } 410 | } 411 | 412 | if (bw->ext) { 413 | uint8_t ext_pos = bw->ext_pos; 414 | uint8_t ext_value = bw->ext_value; 415 | if (tempDigest[31 - ext_pos] < ext_value) { 416 | return; 417 | } 418 | } 419 | 420 | uint index = atomic_add(&output_buffer->found,1); 421 | output_buffer->results[index] = id; 422 | } 423 | 424 | __kernel void sha256d( 425 | __global uchar *header, 426 | __global const Params* params, 427 | __global const BitWorkForGPU* bw, 428 | __global resultBulk *output_buffer 429 | ) { 430 | __private uint8_t tempHdr[255]; 431 | __private uint8_t tempDigest[32] = {0}; 432 | 433 | uint header_length = params->data_len; 434 | uint pos = params->pos; 435 | 436 | for (uint x = 0; x < pos; x++) { 437 | tempHdr[x] = header[x]; 438 | } 439 | 440 | uint id = get_global_id(0); 441 | tempHdr[pos + 3] = (id >> 24) & 0xFF; 442 | tempHdr[pos + 2] = (id >> 16) & 0xFF; 443 | tempHdr[pos + 1] = (id >> 8) & 0xFF; 444 | tempHdr[pos + 0] = id & 0xFF; 445 | 446 | for (uint x = pos + 4; x < header_length; x++) { 447 | tempHdr[x] = header[x]; 448 | } 449 | 450 | hash_private(tempHdr,header_length,tempDigest); 451 | 452 | hash_private(tempDigest,32,tempDigest); 453 | 454 | for (int i = 0; i < 32; i++) { 455 | if ((tempDigest[i] & bw->mask[i]) != bw->pattern[i]) { 456 | return; 457 | } 458 | } 459 | 460 | if (bw->ext) { 461 | uint8_t ext_pos = bw->ext_pos; 462 | uint8_t ext_value = bw->ext_value; 463 | if (tempDigest[31 - ext_pos] < ext_value) { 464 | return; 465 | } 466 | } 467 | 468 | uint index = atomic_add(&output_buffer->found,1); 469 | output_buffer->results[index] = id; 470 | } 471 | 472 | __kernel void sha256d_64( 473 | __global uchar *header, 474 | __global const Params* params, 475 | __global const BitWorkForGPU* bw, 476 | ulong offset, 477 | __global resultBulk *output_buffer 478 | ) { 479 | __private uint8_t tempHdr[255]; 480 | __private uint8_t tempDigest[32] = {0}; 481 | 482 | uint header_length = params->data_len; 483 | uint pos = params->pos; 484 | 485 | for (uint x = 0; x < pos; x++) { 486 | tempHdr[x] = header[x]; 487 | } 488 | 489 | ulong id = get_global_id(0) + offset; 490 | 491 | tempHdr[pos + 7] = (id >> 56) & 0xFF; 492 | tempHdr[pos + 6] = (id >> 48) & 0xFF; 493 | tempHdr[pos + 5] = (id >> 40) & 0xFF; 494 | tempHdr[pos + 4] = (id >> 32) & 0xFF; 495 | tempHdr[pos + 3] = (id >> 24) & 0xFF; 496 | tempHdr[pos + 2] = (id >> 16) & 0xFF; 497 | tempHdr[pos + 1] = (id >> 8) & 0xFF; 498 | tempHdr[pos + 0] = id & 0xFF; 499 | 500 | for (uint x = pos + 8; x < header_length; x++) { 501 | tempHdr[x] = header[x]; 502 | } 503 | 504 | hash_private(tempHdr,header_length,tempDigest); 505 | 506 | hash_private(tempDigest,32,tempDigest); 507 | 508 | for (int i = 0; i < 32; i++) { 509 | if ((tempDigest[i] & bw->mask[i]) != bw->pattern[i]) { 510 | return; 511 | } 512 | } 513 | 514 | if (bw->ext) { 515 | uint8_t ext_pos = bw->ext_pos; 516 | uint8_t ext_value = bw->ext_value; 517 | if (tempDigest[31 - ext_pos] < ext_value) { 518 | return; 519 | } 520 | } 521 | 522 | uint index = atomic_add(&output_buffer->found,1); 523 | output_buffer->results[index] = get_global_id(0); 524 | } -------------------------------------------------------------------------------- /src/miner/gpu.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | use std::sync::atomic::{AtomicU64, Ordering}; 3 | 4 | use ocl::{Buffer, MemFlags, OclPrm, ProQue}; 5 | 6 | use crate::miner::{find_first_sequence_position, find_time_nonce_script_position, Miner}; 7 | use crate::util::time; 8 | use crate::utils::bitworkc::BitWork; 9 | 10 | pub struct GpuMiner { 11 | commit_counter: Arc, 12 | reveal_counter: Arc, 13 | sequence: u32, 14 | } 15 | 16 | const KERNEL_CODE: &str = include_str!("ext/sha256d.cl"); 17 | 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 19 | #[repr(C, packed)] 20 | struct HashResult64 { 21 | found: i32, 22 | results: [u32; 255], 23 | } 24 | 25 | impl Default for HashResult64 { 26 | fn default() -> Self { 27 | HashResult64 { 28 | found: 0, 29 | results: [0; 255], 30 | } 31 | } 32 | } 33 | unsafe impl OclPrm for HashResult64 {} 34 | 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 36 | #[repr(C, packed)] 37 | struct HashResult { 38 | found: i32, 39 | results: [u32; 255], 40 | } 41 | 42 | impl Default for HashResult { 43 | fn default() -> Self { 44 | HashResult { 45 | found: 0, 46 | results: [0; 255], 47 | } 48 | } 49 | } 50 | unsafe impl OclPrm for HashResult {} 51 | 52 | #[derive(Default, Clone, Debug, Copy, PartialEq, Eq)] 53 | #[repr(C, packed)] 54 | pub struct BitWorkForGPU { 55 | pub mask: [u8; 32], 56 | pub pattern: [u8; 32], 57 | pub ext: bool, 58 | pub ext_pos: u8, 59 | pub ext_value: u8, 60 | } 61 | unsafe impl OclPrm for BitWorkForGPU {} 62 | 63 | #[derive(Default, Clone, Debug, Copy, PartialEq, Eq)] 64 | #[repr(C, packed)] 65 | pub struct Params { 66 | pub data_len: u32, 67 | pub pos: u32, 68 | } 69 | unsafe impl OclPrm for Params {} 70 | 71 | impl GpuMiner { 72 | pub fn new() -> GpuMiner { 73 | GpuMiner { 74 | sequence: 0x80000000, 75 | commit_counter: Arc::new(AtomicU64::new(0)), 76 | reveal_counter: Arc::new(AtomicU64::new(0)), 77 | } 78 | } 79 | pub fn find_seq_by_gpu( 80 | &mut self, 81 | data: &[u8], 82 | target: BitWork, 83 | start: u32, 84 | max: Option, 85 | counter: Option<&AtomicU64>, 86 | ) -> Vec { 87 | self.sequence = 0x80000000; 88 | let max = max.unwrap_or(time() as u32); 89 | let pos = find_first_sequence_position(data); 90 | // change data 91 | loop { 92 | let mut new_data = Vec::new(); 93 | new_data.extend_from_slice(&data[..pos]); 94 | new_data.extend_from_slice(&self.sequence.to_le_bytes()); 95 | new_data.extend_from_slice(&data[pos + 4..]); 96 | 97 | let data = new_data.as_slice(); 98 | 99 | let (pro_que, data_buffer, params_buffer, bit_work_buffer) = 100 | generate_pro_que_params(data, target.clone(), pos as u32); 101 | 102 | let mut output = vec![HashResult::default()]; 103 | let output_buf = Buffer::::builder() 104 | .queue(pro_que.queue().clone()) 105 | .flags(MemFlags::READ_WRITE) 106 | .len(output.len()) 107 | .copy_host_slice(&output) 108 | .build() 109 | .unwrap(); 110 | 111 | let range = 1 << 24; 112 | let mut offset = start; 113 | while offset < max { 114 | let result = offset.checked_add(range); 115 | let size = if result.is_none() || result.unwrap() > max { 116 | max - offset 117 | } else { 118 | range 119 | }; 120 | // let size = 1; 121 | let kernel = pro_que 122 | .kernel_builder("sha256d_append") 123 | .arg(&data_buffer) 124 | .arg(¶ms_buffer) 125 | .arg(&bit_work_buffer) 126 | .arg(&output_buf) 127 | .global_work_offset(offset) 128 | .global_work_size(size) 129 | .build() 130 | .unwrap(); 131 | 132 | unsafe { 133 | kernel.enq().unwrap(); 134 | } 135 | 136 | output_buf.read(&mut output).enq().unwrap(); 137 | 138 | counter.map(|c| c.fetch_add(size as u64, Ordering::Relaxed)); 139 | 140 | let output = output[0]; 141 | if output.found > 0 { 142 | let time_lock = output.results[0]; 143 | let mut result = vec![]; 144 | result.extend_from_slice(&data[..data.len() - 4]); 145 | result.extend_from_slice(&time_lock.to_le_bytes()); 146 | 147 | return result; 148 | }; 149 | offset += size; 150 | } 151 | 152 | self.sequence += 1; 153 | } 154 | } 155 | } 156 | impl Miner for GpuMiner { 157 | fn name(&self) -> &'static str { 158 | "GPU" 159 | } 160 | 161 | fn mine_commit( 162 | &mut self, 163 | tx: &[u8], 164 | bitworkc: BitWork, 165 | start: u32, 166 | max: Option, 167 | ) -> Vec { 168 | let counter = self.commit_counter.clone(); 169 | self.find_seq_by_gpu(tx, bitworkc, start, max, Some(&counter)) 170 | } 171 | 172 | fn mine_commit_counter(&self) -> Arc { 173 | self.commit_counter.clone() 174 | } 175 | 176 | fn mine_reveal( 177 | &mut self, 178 | tx: &[u8], 179 | bitworkr: BitWork, 180 | start: u64, 181 | max: Option, 182 | ) -> Vec { 183 | find_return_nonce_by_gpu(tx, bitworkr, start, max, Some(&self.reveal_counter)) 184 | } 185 | 186 | fn mine_reveal_counter(&self) -> Arc { 187 | self.reveal_counter.clone() 188 | } 189 | } 190 | 191 | pub fn find_return_nonce_by_gpu( 192 | data: &[u8], 193 | target: BitWork, 194 | start: u64, 195 | max: Option, 196 | counter: Option<&AtomicU64>, 197 | ) -> Vec { 198 | let max = max.unwrap_or(u64::MAX); 199 | let pos = find_time_nonce_script_position(data) as u32; 200 | 201 | let range = 10000000; 202 | let mut offset = start; 203 | 204 | let (pro_que, data_buffer, params_buffer, bit_work_buffer) = 205 | generate_pro_que_params(data, target, pos); 206 | 207 | let mut output = vec![HashResult64::default()]; 208 | let output_buf = Buffer::::builder() 209 | .queue(pro_que.queue().clone()) 210 | .flags(MemFlags::READ_WRITE) 211 | .len(output.len()) 212 | .copy_host_slice(&output) 213 | .build() 214 | .unwrap(); 215 | 216 | while offset < max { 217 | let result = offset.checked_add(range); 218 | let size = if result.is_none() || result.unwrap() > max { 219 | max - offset 220 | } else { 221 | range 222 | }; 223 | 224 | let kernel = pro_que 225 | .kernel_builder("sha256d_64") 226 | .arg(&data_buffer) 227 | .arg(¶ms_buffer) 228 | .arg(&bit_work_buffer) 229 | .arg(offset) 230 | .arg(&output_buf) 231 | .global_work_size(size as usize) 232 | .build() 233 | .unwrap(); 234 | 235 | unsafe { 236 | kernel.enq().unwrap(); 237 | } 238 | 239 | output_buf.read(&mut output).enq().unwrap(); 240 | 241 | counter.map(|c| c.fetch_add(size, Ordering::Relaxed)); 242 | 243 | let output = output[0]; 244 | if output.found > 0 { 245 | let output_data = output.results[0] as u64 + offset; 246 | let mut result = vec![]; 247 | result.extend_from_slice(&data[..pos as usize]); 248 | result.extend_from_slice(&output_data.to_le_bytes()); 249 | result.extend_from_slice(&data[pos as usize + 8..]); 250 | 251 | return result; 252 | }; 253 | offset += size; 254 | } 255 | 256 | panic!("not found in u64, crazy"); 257 | } 258 | 259 | pub fn generate_pro_que_params( 260 | data: &[u8], 261 | target: BitWork, 262 | pos: u32, 263 | ) -> (ProQue, Buffer, Buffer, Buffer) { 264 | let pro_que = ProQue::builder().src(KERNEL_CODE).build().unwrap(); 265 | 266 | let data_buffer = Buffer::builder() 267 | .queue(pro_que.queue().clone()) 268 | .flags(MemFlags::READ_ONLY) 269 | .len(data.len()) 270 | .copy_host_slice(data) 271 | .build() 272 | .unwrap(); 273 | let params_buffer = Buffer::builder() 274 | .queue(pro_que.queue().clone()) 275 | .flags(MemFlags::READ_ONLY) 276 | .len(1) 277 | .copy_host_slice(&[Params { 278 | data_len: data.len() as u32, 279 | pos, 280 | }]) 281 | .build() 282 | .unwrap(); 283 | 284 | let bit_work_buffer = Buffer::builder() 285 | .queue(pro_que.queue().clone()) 286 | .flags(MemFlags::READ_ONLY) 287 | .len(1) 288 | .copy_host_slice(&[BitWorkForGPU { 289 | mask: target.mask, 290 | pattern: target.pattern, 291 | ext: target.ext.is_some(), 292 | ext_pos: target.ext.clone().map(|e| e.pos).unwrap_or(0), 293 | ext_value: target.ext.map(|e| e.value).unwrap_or(0), 294 | }]) 295 | .build() 296 | .unwrap(); 297 | 298 | (pro_que, data_buffer, params_buffer, bit_work_buffer) 299 | } 300 | 301 | #[cfg(test)] 302 | mod tests { 303 | use tracing::info; 304 | 305 | use crate::miner::tests::{mint_commit_by, mint_reveal_by}; 306 | use crate::util::log; 307 | 308 | use super::*; 309 | 310 | #[test] 311 | fn test_commit() { 312 | log(); 313 | let mut miner = GpuMiner::new(); 314 | mint_commit_by(&mut miner); 315 | } 316 | 317 | #[test] 318 | fn test_reveal() { 319 | log(); 320 | info!("start"); 321 | let mut miner = GpuMiner::new(); 322 | mint_reveal_by(&mut miner); 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /src/miner/mod.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | use std::sync::atomic::AtomicU64; 3 | 4 | use bitcoin::opcodes::all::OP_RETURN; 5 | use log::info; 6 | 7 | use crate::util::GLOBAL_OPTS; 8 | use crate::utils::bitworkc::BitWork; 9 | 10 | pub mod cpu; 11 | pub mod gpu; 12 | #[cfg(feature = "op_sha256")] 13 | pub mod op_sha256_gpu; 14 | 15 | pub trait Miner { 16 | fn name(&self) -> &'static str; 17 | fn mine_commit( 18 | &mut self, 19 | tx: &[u8], 20 | bitworkc: BitWork, 21 | start: u32, 22 | max: Option, 23 | ) -> Vec; 24 | 25 | fn mine_commit_counter(&self) -> Arc; 26 | 27 | fn mine_reveal( 28 | &mut self, 29 | tx: &[u8], 30 | bitworkr: BitWork, 31 | start: u64, 32 | max: Option, 33 | ) -> Vec; 34 | 35 | fn mine_reveal_counter(&self) -> Arc; 36 | } 37 | pub fn create_miner() -> Box { 38 | match GLOBAL_OPTS.miner.as_str() { 39 | "cpu" => Box::new(cpu::CpuMiner::new()), 40 | "gpu" => Box::new(gpu::GpuMiner::new()), 41 | _ => { 42 | panic!("Invalid miner type: {}", GLOBAL_OPTS.miner); 43 | } 44 | } 45 | } 46 | pub fn find_first_sequence_position(serialized_tx: &[u8]) -> usize { 47 | let mut offset = 0; 48 | // skip the version number (4 bytes) 49 | offset += 4; 50 | // get the number of inputs (assume it's a small varint, i.e. 1 byte) 51 | let input_count = serialized_tx[offset] as usize; 52 | offset += 1; 53 | if input_count == 0 { 54 | panic!("Cannot find sequence number in a transaction with no inputs."); 55 | } 56 | // foreach input 57 | // skip the previous transaction hash (32 bytes) and output index (4 bytes) 58 | offset += 32 + 4; 59 | // parse the script length (assume it's a small varint, i.e. 1 byte) 60 | let script_length = serialized_tx[offset] as usize; 61 | offset += 1; 62 | // skip the script and the sequence number 63 | offset += script_length; 64 | // offset is now at the beginning of the sequence number 65 | offset 66 | } 67 | pub fn find_time_nonce_script_position(serialized_tx: &[u8]) -> usize { 68 | info!( 69 | "find_time_nonce_script_position, serialized_tx: {:?}", 70 | hex::encode(serialized_tx) 71 | ); 72 | let mut offset = 0; 73 | // skip the version number (4 bytes) 74 | offset += 4; 75 | // parse the number of inputs (variable length) 76 | let (input_count, input_count_len) = parse_varint(&serialized_tx[offset..]); 77 | offset += input_count_len; 78 | // foreach input 79 | for _ in 0..input_count { 80 | // skip the previous output hash (32 bytes) 81 | offset += 32; 82 | // skip the previous output index (4 bytes) 83 | offset += 4; 84 | // parse the script length (variable length) 85 | let (script_length, script_length_len) = parse_varint(&serialized_tx[offset..]); 86 | offset += script_length_len; 87 | // skip the script 88 | offset += script_length as usize; 89 | // skip the sequence number (4 bytes) 90 | offset += 4; 91 | } 92 | // parse the number of outputs (variable length) 93 | let (output_count, output_count_len) = parse_varint(&serialized_tx[offset..]); 94 | offset += output_count_len; 95 | // foreach output 96 | for _ in 0..output_count { 97 | // skip the value (8 bytes) 98 | offset += 8; 99 | // parse the script length (variable length) 100 | let (script_length, script_length_len) = parse_varint(&serialized_tx[offset..]); 101 | offset += script_length_len; 102 | // check if the script matches the time_nonce_script pattern 103 | if serialized_tx[offset] == OP_RETURN.to_u8() { 104 | offset += 1; 105 | if serialized_tx[offset] == 8 { 106 | // found the time_nonce_script 107 | return offset + 1; 108 | } 109 | } 110 | // skip the script 111 | offset += script_length as usize; 112 | } 113 | offset 114 | } 115 | fn parse_varint(data: &[u8]) -> (u64, usize) { 116 | let first_byte = data[0]; 117 | if first_byte < 0xfd { 118 | (first_byte as u64, 1) 119 | } else if first_byte == 0xfd { 120 | (u16::from_le_bytes([data[1], data[2]]) as u64, 3) 121 | } else if first_byte == 0xfe { 122 | ( 123 | u32::from_le_bytes([data[1], data[2], data[3], data[4]]) as u64, 124 | 5, 125 | ) 126 | } else { 127 | ( 128 | u64::from_le_bytes([ 129 | data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], 130 | ]), 131 | 9, 132 | ) 133 | } 134 | } 135 | struct StepByIterator { 136 | start: u64, 137 | end: u64, 138 | step: u64, 139 | } 140 | 141 | impl Iterator for StepByIterator { 142 | type Item = u64; 143 | 144 | fn next(&mut self) -> Option { 145 | if self.start < self.end { 146 | let current = self.start; 147 | self.start += self.step; 148 | Some(current) 149 | } else { 150 | None 151 | } 152 | } 153 | } 154 | #[cfg(test)] 155 | mod tests { 156 | use std::sync::atomic::Ordering::SeqCst; 157 | use std::time::Instant; 158 | 159 | use bitcoin::consensus::deserialize; 160 | use tracing::info; 161 | 162 | use crate::miner::Miner; 163 | use crate::utils::bitworkc::BitWork; 164 | 165 | pub fn mint_commit_by(miner:&mut impl Miner){ 166 | let tx = "01000000012a912f654cc1bd88da5b8a54c52b6dd60b6e831bfba52b32c1314cd17c5634120100000000feffffff024c05000000000000225120e3d5a4789dc4982cfda563c8c23f988f505e481bf9602f7ba5b1045e44e0392000b09a3b0000000022512032447fe28750a7e2b18af49d89a359a81c69bbf6f3db05feb7e8e1688f37e4c200000000"; 167 | let tx = hex::decode(tx).unwrap(); 168 | let bitwork = BitWork::new("88888888.11".to_string()).unwrap(); 169 | 170 | let now = Instant::now(); 171 | let commit_count = miner.mine_commit_counter().clone(); 172 | let tx_raw = miner.mine_commit(&tx, bitwork, 0, None); 173 | 174 | let commit_count = commit_count.load(SeqCst); 175 | info!("duration:{:?}, count:{:?}", now.elapsed(), commit_count); 176 | 177 | let tx: bitcoin::Transaction = deserialize(tx_raw.as_slice()).unwrap(); 178 | println!("{}", tx.txid()); 179 | } 180 | 181 | pub fn mint_reveal_by(miner:&mut impl Miner){ 182 | let tx = "01000000017b7afa047d43cb34409d453e11fc048314dd2ee58a5b20c1b0f6a8077b5634120000000000fdffffff02e803000000000000225120adb58bdbccaa9fdd6594859354b502214e3405a74d772a60e255e233468c4c7900000000000000000a6a08000000000000000100000000"; 183 | let tx = hex::decode(tx).unwrap(); 184 | let bitwork = BitWork::new("12345688".to_string()).unwrap(); 185 | 186 | let now = Instant::now(); 187 | let reveal_count = miner.mine_reveal_counter().clone(); 188 | let reveal_tx = miner.mine_reveal(&tx, bitwork, 0, None); 189 | 190 | let reveal_count = reveal_count.load(SeqCst); 191 | info!("duration:{:?}, count:{:?}", now.elapsed(), reveal_count); 192 | 193 | let tx: bitcoin::Transaction = deserialize(reveal_tx.as_slice()).unwrap(); 194 | println!("{}", tx.txid()) 195 | } 196 | 197 | } 198 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process::Command; 3 | use std::str::FromStr; 4 | use std::time::{SystemTime, UNIX_EPOCH}; 5 | 6 | use bitcoin::{Address, key, Network, PrivateKey, Script, ScriptBuf, TapNodeHash, XOnlyPublicKey}; 7 | use bitcoin::consensus::Encodable; 8 | use bitcoin::key::{Keypair, Secp256k1, TapTweak, TweakedKeypair}; 9 | use bitcoin::opcodes::all::{OP_CHECKSIG, OP_ENDIF, OP_IF, OP_RETURN}; 10 | use bitcoin::opcodes::OP_0; 11 | use bitcoin::script::PushBytes; 12 | use bitcoin::secp256k1::All; 13 | use eyre::Result; 14 | use lazy_static::lazy_static; 15 | use serde::Serialize; 16 | use structopt::StructOpt; 17 | 18 | #[derive(Clone, Debug, StructOpt)] 19 | #[structopt(name = "Collider", about = "A collider for atomicals.")] 20 | pub struct Opt { 21 | #[structopt(long)] 22 | pub benchmark: bool, 23 | /// Sets the level of verbosity 24 | #[structopt(short, long)] 25 | pub verbose: bool, 26 | 27 | #[structopt(short, long, env = "API_URL")] 28 | pub api_url: Option, 29 | 30 | #[structopt(long, env = "TESTNET")] 31 | pub testnet: bool, 32 | 33 | #[structopt(short, long, default_value = "50", env = "BASE_FEE")] 34 | pub base_fee: u64, 35 | 36 | #[structopt(short, long, env = "PRIMARY_WALLET", required_unless("benchmark"))] 37 | pub primary_wallet: Option, 38 | 39 | #[structopt(short, long, env = "FUNDING_WALLET", parse(try_from_str = WifPrivateKey::from_str),required_unless("benchmark"))] 40 | pub funding_wallet: Option, 41 | 42 | #[structopt(short, long, env = "TICKER")] 43 | pub ticker: Option, 44 | 45 | #[structopt(short, long, env = "MINER", default_value = "cpu",required_unless("benchmark"), possible_values = &["cpu", "gpu"])] 46 | pub miner: String, 47 | } 48 | 49 | lazy_static! { 50 | pub static ref GLOBAL_OPTS: Opt = { 51 | if cfg!(test) { 52 | Opt { 53 | benchmark: false, 54 | verbose: false, 55 | api_url: None, 56 | testnet: true, 57 | base_fee: 50, 58 | ticker: Option::from("atom".to_string()), 59 | primary_wallet: Option::from(env::var("PRIMARY_WALLET").expect("PRIMARY_WALLET is not set")), 60 | funding_wallet: Option::from(WifPrivateKey::from_str( 61 | env::var("FUNDING_WALLET") 62 | .expect("FUNDING_WALLET is not set") 63 | .as_str(), 64 | ) 65 | .unwrap()), 66 | miner: "gpu".to_string(), 67 | } 68 | } else { 69 | Opt::from_args() 70 | } 71 | }; 72 | } 73 | 74 | pub fn current_network() -> Network { 75 | if GLOBAL_OPTS.testnet { 76 | Network::Testnet 77 | } else { 78 | Network::Bitcoin 79 | } 80 | } 81 | 82 | #[cfg(test)] 83 | pub fn log() { 84 | dotenvy::dotenv().ok(); 85 | let subscriber = tracing_subscriber::fmt() 86 | .with_max_level(tracing::Level::DEBUG) // 设置日志级别 87 | .finish(); 88 | 89 | tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); 90 | } 91 | 92 | pub fn tx2bytes(tx: &bitcoin::Transaction) -> Vec { 93 | let mut buf = Vec::new(); 94 | tx.consensus_encode(&mut buf).unwrap(); 95 | buf 96 | } 97 | #[allow(dead_code)] 98 | pub fn tx2hex(tx: &bitcoin::Transaction) -> String { 99 | hex::encode(tx2bytes(tx)) 100 | } 101 | 102 | #[derive(Clone, Debug)] 103 | pub struct WifPrivateKey(PrivateKey); 104 | 105 | impl FromStr for WifPrivateKey { 106 | type Err = key::Error; 107 | fn from_str(s: &str) -> Result { 108 | PrivateKey::from_wif(s).map(WifPrivateKey) 109 | } 110 | } 111 | 112 | impl WifPrivateKey { 113 | pub(crate) fn keypair(&self, secp: &Secp256k1) -> Keypair { 114 | self.0.inner.keypair(&secp) 115 | } 116 | pub(crate) fn x_only_public_key(&self, secp: &Secp256k1) -> XOnlyPublicKey { 117 | let (x, _) = self.0.inner.x_only_public_key(secp); 118 | x 119 | } 120 | 121 | pub fn p2tr_address(&self, secp: &Secp256k1) -> Address { 122 | Address::p2tr(secp, self.x_only_public_key(secp), None, current_network()) 123 | } 124 | 125 | pub fn tap_tweak( 126 | &self, 127 | secp: &Secp256k1, 128 | merkle_tree: Option, 129 | ) -> TweakedKeypair { 130 | let pair = Keypair::from_secret_key(secp, &self.0.inner); 131 | pair.tap_tweak(secp, merkle_tree) 132 | } 133 | } 134 | pub fn time() -> u64 { 135 | SystemTime::now() 136 | .duration_since(UNIX_EPOCH) 137 | .unwrap() 138 | .as_secs() 139 | } 140 | pub fn time_nonce_script(nonce: u64) -> ScriptBuf { 141 | Script::builder() 142 | .push_opcode(OP_RETURN) 143 | .push_slice(nonce.to_le_bytes()) 144 | .into_script() 145 | } 146 | 147 | pub fn cbor(v: &T) -> Result> 148 | where 149 | T: Serialize, 150 | { 151 | let mut cbor = Vec::new(); 152 | 153 | ciborium::into_writer(v, &mut cbor)?; 154 | 155 | Ok(cbor) 156 | } 157 | 158 | pub fn build_reveal_script( 159 | x_only_public_key: &XOnlyPublicKey, 160 | op_type: &str, 161 | payload: &[u8], 162 | ) -> ScriptBuf { 163 | // format!( 164 | // "{} OP_CHECKSIG OP_0 OP_IF {} {} {} OP_ENDIF", 165 | // &private_key.public_key(&Default::default()).to_string()[2..], 166 | // array_bytes::bytes2hex("", "atom"), 167 | // array_bytes::bytes2hex("", op_type), 168 | // payload.chunks(520).map(|c| array_bytes::bytes2hex("", c)).collect::>().join(" ") 169 | // ) 170 | let b = Script::builder() 171 | .push_x_only_key(x_only_public_key) 172 | .push_opcode(OP_CHECKSIG) 173 | .push_opcode(OP_0) 174 | .push_opcode(OP_IF) 175 | .push_slice(<&PushBytes>::try_from("atom".as_bytes()).unwrap()) 176 | .push_slice(<&PushBytes>::try_from(op_type.as_bytes()).unwrap()); 177 | 178 | payload 179 | .chunks(520) 180 | .fold(b, |b, c| b.push_slice(<&PushBytes>::try_from(c).unwrap())) 181 | .push_opcode(OP_ENDIF) 182 | .into_script() 183 | } 184 | 185 | pub fn format_speed(speed: f64) -> String { 186 | const UNITS: [&str; 4] = ["", "K", "M", "G"]; 187 | let mut speed = speed; 188 | let mut unit_index = 0; 189 | 190 | while speed >= 1000.0 && unit_index < UNITS.len() - 1 { 191 | speed /= 1000.0; 192 | unit_index += 1; 193 | } 194 | 195 | format!("{:.2}{}", speed, UNITS[unit_index]) 196 | } 197 | 198 | #[cfg(target_os = "macos")] 199 | pub fn get_cpu_desc() -> String { 200 | let output = Command::new("sysctl") 201 | .arg("-n") 202 | .arg("machdep.cpu.brand_string") 203 | .output() 204 | .expect("failed to execute process"); 205 | 206 | String::from_utf8_lossy(&output.stdout).trim().to_string() 207 | } 208 | 209 | #[cfg(target_os = "linux")] 210 | pub fn get_cpu_desc() -> String { 211 | use std::io::{BufRead, BufReader}; 212 | let file = std::fs::File::open("/proc/cpuinfo").expect("Could not open /proc/cpuinfo"); 213 | let reader = std::io::BufReader::new(file); 214 | 215 | for line in reader.lines() { 216 | if let Ok(line) = line { 217 | if line.starts_with("model name") { 218 | let cpu_desc = line.split(':').nth(1).expect("Could not split line").trim(); 219 | return cpu_desc.to_string(); 220 | } 221 | } 222 | } 223 | 224 | "Unknown".to_string() 225 | } 226 | 227 | #[cfg(target_os = "windows")] 228 | pub fn get_cpu_desc() -> String { 229 | let output = Command::new("wmic") 230 | .args(["cpu", "get", "name"]) 231 | .output() 232 | .expect("failed to execute process"); 233 | 234 | let output = String::from_utf8_lossy(&output.stdout); 235 | output.trim().split('\n').nth(1).unwrap_or("Unknown").trim().to_string() 236 | } -------------------------------------------------------------------------------- /src/utils/bitworkc.rs: -------------------------------------------------------------------------------- 1 | use eyre::{eyre, Result}; 2 | 3 | #[derive(Clone, Debug)] 4 | pub struct Ext { 5 | pub value: u8, 6 | pub pos: u8, 7 | } 8 | #[derive(Clone, Debug)] 9 | pub struct BitWork { 10 | pub raw: String, 11 | pub mask: [u8; 32], 12 | pub pattern: [u8; 32], 13 | pub ext: Option, 14 | } 15 | 16 | impl BitWork { 17 | pub fn new(raw_hex_str: String) -> Result { 18 | let mut ext = None; 19 | let mut hex_str = raw_hex_str.clone(); 20 | if raw_hex_str.contains('.') { 21 | let parts: Vec<&str> = raw_hex_str.split('.').collect(); 22 | hex_str = parts[0].to_string(); 23 | let hex_str_len = hex_str.len(); 24 | 25 | let mut ext_num = parts[1].parse().expect("Bitworkc ext parse error"); 26 | // offset the pos 27 | if hex_str_len % 2 == 0 { 28 | // hex_str_len -= 1; 29 | ext_num <<= 4; 30 | } else { 31 | ext_num += hex_str[hex_str_len - 1..].parse::().unwrap() << 4; 32 | } 33 | 34 | ext = Some(Ext { 35 | value: ext_num, 36 | pos: (hex_str_len / 2) as u8, 37 | }); 38 | } 39 | 40 | if hex_str.len() > 64 { 41 | return Err(eyre!("Hex string too long")); 42 | } 43 | 44 | let mut pattern = [0u8; 32]; 45 | let mut mask = [0u8; 32]; 46 | 47 | for (i, c) in hex_str.chars().enumerate() { 48 | let digit = c.to_digit(16).ok_or(eyre!("Invalid hex character"))?; 49 | let byte_index = 31 - i / 2; 50 | if i % 2 == 0 { 51 | pattern[byte_index] |= (digit as u8) << 4; 52 | mask[byte_index] |= 0xF0; 53 | } else { 54 | pattern[byte_index] |= digit as u8; 55 | mask[byte_index] |= 0x0F; 56 | } 57 | } 58 | 59 | Ok(BitWork { 60 | raw: raw_hex_str, 61 | mask, 62 | pattern, 63 | ext, 64 | }) 65 | } 66 | 67 | pub fn matches(&self, data: &[u8]) -> bool { 68 | if data.len() < 32 { 69 | return false; 70 | } 71 | 72 | for (index, word) in data.iter().enumerate() { 73 | let mask = self.mask[index]; 74 | let pattern = self.pattern[index]; 75 | if (word & mask) != pattern { 76 | return false; 77 | } 78 | } 79 | // if is inf 80 | if let Some(Ext { value, pos }) = self.ext.clone() { 81 | return data[31 - pos as usize] >= value; 82 | } 83 | 84 | true 85 | } 86 | } 87 | 88 | #[cfg(test)] 89 | mod test { 90 | use crate::util::log; 91 | 92 | use super::*; 93 | 94 | #[test] 95 | fn test_bitworkc() { 96 | let bitworkc = BitWork::new("aabbccd".to_string()).unwrap(); 97 | println!("{:?}", bitworkc); 98 | } 99 | 100 | #[test] 101 | fn test_mask() { 102 | let matcher = BitWork::new("aabbccd".to_string()).unwrap(); 103 | let patten = [0xd4, 0xcc, 0xbb, 0xaa]; 104 | let mut data = vec![0; 32]; 105 | let len = 32; 106 | data[len - 4] = patten[0]; 107 | data[len - 3] = patten[1]; 108 | data[len - 2] = patten[2]; 109 | data[len - 1] = patten[3]; 110 | 111 | assert!(matcher.matches(&data)); 112 | } 113 | 114 | #[test] 115 | fn test_inf_mask() { 116 | let matcher = BitWork::new("9999.12".to_string()).unwrap(); 117 | { 118 | let mut data = vec![0; 32]; 119 | let len = 32; 120 | data[len - 3] = 0x11; 121 | data[len - 2] = 0x99; 122 | data[len - 1] = 0x99; 123 | 124 | assert!(!matcher.matches(&data)) 125 | } 126 | { 127 | let mut data = vec![0; 32]; 128 | let len = 32; 129 | data[len - 3] = 0xc0; 130 | data[len - 2] = 0x99; 131 | data[len - 1] = 0x99; 132 | 133 | assert!(matcher.matches(&data)) 134 | } 135 | } 136 | 137 | #[test] 138 | fn test_inf_mask_2() { 139 | let matcher = BitWork::new("99999.12".to_string()).unwrap(); 140 | { 141 | let mut data = vec![0; 32]; 142 | let len = 32; 143 | data[len - 3] = 0x11; 144 | data[len - 2] = 0x99; 145 | data[len - 1] = 0x99; 146 | 147 | assert!(!matcher.matches(&data)) 148 | } 149 | { 150 | let mut data = vec![0; 32]; 151 | let len = 32; 152 | data[len - 3] = 0x9c; 153 | data[len - 2] = 0x99; 154 | data[len - 1] = 0x99; 155 | 156 | assert!(matcher.matches(&data)) 157 | } 158 | } 159 | 160 | #[test] 161 | fn test_inf_mask_3() { 162 | log(); 163 | // 1234567.11 164 | let matcher = BitWork::new("1234567.11".to_string()).unwrap(); 165 | { 166 | let mut data = vec![0; 32]; 167 | let len = 32; 168 | 169 | data[len - 4] = 0x79; 170 | data[len - 3] = 0x56; 171 | data[len - 2] = 0x34; 172 | data[len - 1] = 0x12; 173 | 174 | assert!(!matcher.matches(&data)) 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod bitworkc; 2 | -------------------------------------------------------------------------------- /static/mining.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishuzumi/collider/f3f03e568fb89cad67d5be4f10c8ac34dc343e1d/static/mining.png --------------------------------------------------------------------------------