├── Resources ├── .gitignore ├── README.md ├── miner.py └── LICENSE /Resources: -------------------------------------------------------------------------------- 1 | https://bitcoin.stackexchange.com/questions/8031/what-are-bitcoin-miners-really-solving 2 | 3 | https://en.bitcoin.it/wiki/Difficulty 4 | 5 | https://en.bitcoin.it/wiki/Target 6 | 7 | https://bitcoin.stackexchange.com/questions/30467/what-are-the-equations-to-convert-between-bits-and-difficulty 8 | 9 | https://stackoverflow.com/questions/22059359/trying-to-understand-nbits-value-from-stratum-protocol/22161019#22161019 10 | 11 | https://en.bitcoin.it/wiki/Nonce -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.swo 3 | 4 | ### Python template 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | env/ 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *,cover 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | 58 | # Sphinx documentation 59 | docs/_build/ 60 | # PyBuilder 61 | target/ 62 | 63 | .idea/ 64 | .DS_Store 65 | *.dat 66 | data/ 67 | *.zip 68 | *.pkl 69 | *.tsv 70 | 71 | 72 | # Created by .ignore support plugin (hsz.mobi) 73 | .gitignore 74 | nohup.out 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # My First Bitcoin Miner 2 | For the people who are curious to understand in a simplified setup: 3 | - **How the Bitcoin blockchain works** 4 | - **How mining works** 5 | 6 | For a complete implementation (that can actually mine!), please browse this repository https://github.com/jgarzik/pyminer. 7 | 8 | This miner is not connected to the bitcoin network and is a very simplified version of what would be a real bitcoin miner. The purpose of this implementation is to provide a basic comprehension of the mining logic. 9 | 10 | ## What are bitcoin miners really solving? 11 | 12 | ### Step 1 13 | 14 | At a high level, the miner software takes a list of active transactions, and then groups them together in something called a "block". 15 | 16 | Or more *accurately stated*: The miner software converts all the transactions into a summary view called a "merkle root", and hashes it, which is representative of the transactions. 17 | 18 | ### Step 2 19 | 20 | The mining software then converts this to into a binary format called a Block Header, which also references the previous blocks (also called a chain). 21 | 22 | ``` 23 | Field Purpose Updated when... Size (Bytes) 24 | Version Block version number You upgrade the software and 4 25 | it specifies a new version 26 | 27 | hashPrevBlock 256-bit hash of the previous A new block comes in 32 28 | block header 29 | hashMerkleRoot 256-bit hash based on all A transaction is accepted 32 30 | the transactions in the block 31 | 32 | Time Current timestamp as seconds Every few seconds 4 33 | since 1970-01-01T00:00 UTC 34 | 35 | Bits Current target in compact format The difficulty is adjusted 4 36 | 37 | Nonce 32-bit number (starts at 0) A hash is tried (increments) 4 38 | ``` 39 | 40 | ### Step 3 41 | 42 | The miner hardware changes a small portion of this block called a "nonce". 43 | 44 | ### Step 4 45 | 46 | The block header is hashed and compared to the Target as if it were simply a large number like 10,000,000 > 7,000,000 (the real numbers are much bigger, and in hex). The target is compressed and stored in each block in a field called bits. 47 | 48 | An expanded target looks like this: 49 | 50 | ``` 51 | Target 0000000000000083ef00000000000000000000000000000000000000000000000 52 | ``` 53 | 54 | And the goal is to make sure the SHA256 hash of the block is less than this value. In the example below "83ee" is smaller than "83ef" 55 | 56 | To simplify this concept, you can ballpark the target by counting the leading zeros (as the other answer here explains). Here is an example: 57 | 58 | Here is a sample block with transactions you can view on BlockChain.info. Look in the upper right hand corner of the webpage for this hash: 59 | 60 | ``` 61 | Hash 0000000000000083ee9371ddff055eed7f02348e4eda36c741a2fc62c85bc5cf 62 | ``` 63 | 64 | That previous hash was from today and has 14 leading zeroes. Let's compare that to what was needed 3 years ago with block 100 which has 8 leading zeros. 65 | 66 | ``` 67 | Hash 00000000a8ed5e960dccdf309f2ee2132badcc9247755c32a4b7081422d51899 68 | ``` 69 | 70 | ### Summary 71 | 72 | So at the end of the day, all a miner does is: 73 | 74 | - Take a block header as input. 75 | - Change the nonce. 76 | - Test if the Block Header hash is less than the Target. If it is, you win. 77 | - Go to step 2 (or go to step 1 if someone else won the block). 78 | 79 | 80 | ## References 81 | - https://bitcoin.stackexchange.com/questions/8031/what-are-bitcoin-miners-really-solving 82 | - https://en.bitcoin.it/wiki/Difficulty 83 | - https://en.bitcoin.it/wiki/Target 84 | - https://bitcoin.stackexchange.com/questions/30467/what-are-the-equations-to-convert-between-bits-and-difficulty 85 | - https://stackoverflow.com/questions/22059359/trying-to-understand-nbits-value-from-stratum-protocol/22161019#22161019 86 | - https://en.bitcoin.it/wiki/Nonce 87 | -------------------------------------------------------------------------------- /miner.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | from time import sleep 3 | 4 | 5 | def hash_256(string): 6 | return hashlib.sha256(string.encode('utf-8')).hexdigest() 7 | 8 | 9 | class TransactionGenerator: 10 | def __init__(self): 11 | self.random_seed = 0 12 | 13 | def generate_transaction(self): 14 | transaction_payload = 'This is a transaction between A and B. ' \ 15 | 'We add a random seed here {} to make its hash unique'.format(self.random_seed) 16 | transaction_hash = hash_256(transaction_payload) 17 | self.random_seed += 1 18 | return transaction_hash 19 | 20 | 21 | # a block is a set of transactions and contains information of the previous blocks. 22 | # https://bitcoin.stackexchange.com/questions/8031/what-are-bitcoin-miners-really-solving 23 | class Block: 24 | def __init__(self, hash_prev_block, target): 25 | self.transactions = [] 26 | self.hash_prev_block = hash_prev_block # hash of the all previous blocks. used to maintain integrity. 27 | self.hash_merkle_block = None 28 | self.target = target 29 | self.nounce = 0 30 | 31 | def add_transaction(self, new_transac): 32 | if not self.is_block_full(): 33 | self.transactions.append(new_transac) 34 | self.hash_merkle_block = hash_256(str('-'.join(self.transactions))) 35 | 36 | def is_block_full(self): 37 | # blocks cannot go above 1Mb. Here let's say we cannot go above 1000 transactions. 38 | return len(self.transactions) >= 1000 39 | 40 | def is_block_ready_to_mine(self): 41 | return self.is_block_full() 42 | 43 | def __str__(self): 44 | return '-'.join([self.hash_merkle_block, str(self.nounce)]) 45 | 46 | def apply_mining_step(self): 47 | current_block_hash = hash_256(self.__str__()) 48 | print('CURRENT_BLOCK_HASH = {}, TARGET = {}'.format(current_block_hash, self.target)) 49 | if int(current_block_hash, 16) < int(self.target, 16): 50 | print('Block was successfully mined! You will get a reward of x BTC!') 51 | print('It took {} steps to mine it.'.format(self.nounce)) 52 | return True 53 | else: 54 | # Incrementing the nounce to change current_block_hash to hope to be below the target. 55 | self.nounce += 1 56 | return False 57 | 58 | 59 | class BlockChain: 60 | def __init__(self): 61 | self.block_chain = [] 62 | 63 | def push(self, block): 64 | self.block_chain.append(block) 65 | 66 | def notify_everybody(self): 67 | print('-' * 80) 68 | print('TO ALL THE NODES OF THE NETWORK, THIS BLOCK HAS BEEN ADDED:') 69 | print('[block #{}] : {}'.format(len(self.block_chain), self.get_last_block())) 70 | print('-' * 80) 71 | 72 | def get_last_block(self): 73 | return self.block_chain[-1] 74 | 75 | 76 | def my_first_miner(): 77 | last_block_header = '0e0fb2e3ae9bd2a0fa8b6999bfe6ab7df197a494d4a02885783a697ac74940d9' 78 | last_block_target = '000ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd' 79 | 80 | # init the block chains 81 | block_chain = BlockChain() 82 | 83 | transaction_generator = TransactionGenerator() 84 | 85 | # fills a block with transactions. We have 1500 pending transactions. 86 | # Sorry 500 transactions will have to wait for the next block! 87 | block = Block(last_block_header, last_block_target) 88 | for i in range(1500): 89 | block.add_transaction(transaction_generator.generate_transaction()) 90 | 91 | assert block.is_block_full() 92 | assert block.is_block_ready_to_mine() 93 | 94 | # now that our block is full, we can start to mine it. 95 | while not block.apply_mining_step(): 96 | continue 97 | 98 | block_chain.push(block) 99 | block_chain.notify_everybody() 100 | sleep(5) 101 | 102 | # Difficulty is updated every 2016 blocks. 103 | # Objective is one block generated every 10 minutes. 104 | # If during the last two weeks, blocks are generated every 5 minutes, then difficulty is multiplied by 2. 105 | last_block_header = hash_256(str(block_chain.get_last_block())) 106 | 107 | block_2 = Block(last_block_header, last_block_target) 108 | 109 | for i in range(1232): 110 | block_2.add_transaction(transaction_generator.generate_transaction()) 111 | 112 | assert block_2.is_block_full() 113 | assert block_2.is_block_ready_to_mine() 114 | 115 | # now that our block is full, we can start to mine it. 116 | while not block_2.apply_mining_step(): 117 | continue 118 | 119 | block_chain.push(block_2) 120 | block_chain.notify_everybody() 121 | sleep(5) 122 | 123 | # now let's increase the difficulty. 124 | # we have now 4 zeros at the beginning instead of 3. 125 | last_block_target = '0000dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd' 126 | 127 | last_block_header = hash_256(str(block_chain.get_last_block())) 128 | 129 | block_3 = Block(last_block_header, last_block_target) 130 | 131 | for i in range(1876): 132 | block_3.add_transaction(transaction_generator.generate_transaction()) 133 | 134 | assert block_3.is_block_full() 135 | assert block_3.is_block_ready_to_mine() 136 | 137 | # now that our block is full, we can start to mine it. 138 | while not block_3.apply_mining_step(): 139 | continue 140 | 141 | block_chain.push(block_3) 142 | block_chain.notify_everybody() 143 | sleep(5) 144 | 145 | print('') 146 | print('SUMMARY') 147 | print('') 148 | for i, block_added in enumerate(block_chain.block_chain): 149 | print('Block #{} was added. It took {} steps to find it.'.format(i, block_added.nounce)) 150 | print('Difficulty was increased for the last block!') 151 | 152 | 153 | if __name__ == '__main__': 154 | my_first_miner() 155 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------