Pages:
Author

Topic: Python based Solo miner for CPU | Learn Basic Bitcoin Mining | Just for fun - page 2. (Read 693 times)

copper member
Activity: 1330
Merit: 899
🖤😏
You say just for fun, I wonder where is the fun if we start mining with our CPU 24/7 and never mine anything, could you provide some probability estimations on a single block found/time?
full member
Activity: 994
Merit: 117
Quote
My quick search your code might be based on one of these repository,
https://github.com/iceland2k14/solominer
https://github.com/Pymmdrza/SoloMiner


Yeah I guess its from iceland with few modifications.

Quote
This only applies to Python 2, your code is in Python 3.
Yes but this code was initially written for Python 2.7 so I described that method. For python3 users can directly import as suggested by @witcher_sense. And usually people don't get missing dependecy errors in Python3 as it comes with multiple pre installed libraries.
For python3 pip3 install works fine in many cases.
legendary
Activity: 2450
Merit: 4415
🔐BitcoinMessage.Tools🔑
pip install  error
/home/user/Downloads# pip install hashlib

/home/user/Downloads# pip install binascii


You don't need to install from pip, these modules are from standard python library, which means they come with interpreter.

Just import them like this:

Code:
import binascii
import hashlib
newbie
Activity: 13
Merit: 0
pip install  error
/home/user/Downloads# pip install hashlib
Code:
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting hashlib
  Using cached hashlib-20081119.zip (42 kB)
  error: subprocess-exited-with-error
 
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> See above for output.
 
  note: This error originates from a subprocess, and is likely not a problem with pip.
  Preparing metadata (setup.py) ... error
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

/home/user/Downloads# pip install binascii
Code:
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
ERROR: Could not find a version that satisfies the requirement binascii (from versions: none)
ERROR: No matching distribution found for binascii

newbie
Activity: 13
Merit: 0
full member
Activity: 994
Merit: 117
Hello Bitcoiners

I want to share a python based solo bitcoin miner which uses ckpool. You can use other pools as well if you want. It is basically like a lottery which has extremly low chances to win but it can be used as a proof of concept. Maybe it has already been shared somewhere and I do not remember its true origin so cannot give proper reference.
You can make changes as you want. This code can help users understand true basics of mining bitcoins.
Installing Dependencies
You must have python. Try with old versions first.
Install dependencies with
Code:
pip install hashlib
pip install binascii
If any dependency is missing you can use pip install DependencyName.

Code
Code:
# -*- coding: utf-8 -*-

import socket
import json
import hashlib
import binascii
from pprint import pprint
import random


address = 'YourBitcoinAddress'
nonce   = hex(random.randint(0,2**32-1))[2:].zfill(8)
host    = 'solo.ckpool.org'
port    = 3333
#host    = 'pool.mainnet.bitcoin-global.io'
#port    = 9223

def main():
    print("address:{} nonce:{}".format(address,nonce))
    print("host:{} port:{}".format(host,port))
   
    sock    = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host,port))
   
    #server connection
    sock.sendall(b'{"id": 1, "method": "mining.subscribe", "params": []}\n')
    lines = sock.recv(1024).decode().split('\n')
    response = json.loads(lines[0])
    sub_details,extranonce1,extranonce2_size = response['result']
   
    #authorize workers
    sock.sendall(b'{"params": ["'+address.encode()+b'", "password"], "id": 2, "method": "mining.authorize"}\n')
   
    #we read until 'mining.notify' is reached
    response = b''
    while response.count(b'\n') < 4 and not(b'mining.notify' in response):
        response += sock.recv(1024)
   
   
    #get rid of empty lines
    responses = [json.loads(res) for res in response.decode().split('\n') if len(res.strip())>0 and 'mining.notify' in res]
    pprint(responses)
   
    job_id,prevhash,coinb1,coinb2,merkle_branch,version,nbits,ntime,clean_jobs \
        = responses[0]['params']
   
    target = (nbits[2:]+'00'*(int(nbits[:2],16) - 3)).zfill(64)
    print('nbits:{} target:{}\n'.format(nbits,target))
   
    # extranonce2 = '00'*extranonce2_size
    extranonce2 = hex(random.randint(0,2**32-1))[2:].zfill(2*extranonce2_size)      # create random
   
    coinbase = coinb1 + extranonce1 + extranonce2 + coinb2
    coinbase_hash_bin = hashlib.sha256(hashlib.sha256(binascii.unhexlify(coinbase)).digest()).digest()
   
    print('coinbase:\n{}\n\ncoinbase hash:{}\n'.format(coinbase,binascii.hexlify(coinbase_hash_bin)))
    merkle_root = coinbase_hash_bin
    for h in merkle_branch:
        merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + binascii.unhexlify(h)).digest()).digest()
   
    merkle_root = binascii.hexlify(merkle_root).decode()
   
    #little endian
    merkle_root = ''.join([merkle_root[i]+merkle_root[i+1] for i in range(0,len(merkle_root),2)][::-1])
   
    print('merkle_root:{}\n'.format(merkle_root))
   
    def noncework():
        nonce   = hex(random.randint(0,2**32-1))[2:].zfill(8)   #hex(int(nonce,16)+1)[2:]
        blockheader = version + prevhash + merkle_root + nbits + ntime + nonce +\
            '000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000'
       
    #    print('blockheader:\n{}\n'.format(blockheader))
       
        hash = hashlib.sha256(hashlib.sha256(binascii.unhexlify(blockheader)).digest()).digest()
        hash = binascii.hexlify(hash).decode()
        # print('hash: {}'.format(hash))
        if(hash[:5] == '00000'): print('hash: {}'.format(hash))
        if hash < target :
    #    if(hash[:10] == '0000000000'):
            print('success!!')
            print('hash: {}'.format(hash))
            payload = bytes('{"params": ["'+address+'", "'+job_id+'", "'+extranonce2 \
                +'", "'+ntime+'", "'+nonce+'"], "id": 1, "method": "mining.submit"}\n', 'utf-8')
            sock.sendall(payload)
            print(sock.recv(1024))
            input("Press Enter to continue...")
    #    else:
    #        print('failed mine, hash is greater than target')
   
    for k in range(10000000):
        noncework()
    print("Finished 10M Search. Regaining Information.")
    sock.close()
    main()

main()



Edit Code
You can edit code. Set your Bitcoin address to receive your mining rewards. Set pool host and port. Save code in a .py file.
One of popular solo pool is solo.ckpool.org which has low fee of like 2%. You get 98% of your mining reward.

Run Code
You can run code by opening command prompt in same folder of file and run command
Code:
python FileName.py


Missing Dependencies and errors
As decribed above you can use pip install command to install any missing dependency. You can google errors and still if you did not find solution maybe your python version is not compatible. Try changing python version.

Future Work
If you improve this code then share here so others can benefit as well and I will update this code as well.


Honor List for Code Improvers
  • 1.
  • 2.
  • 3.


Tribute
I want to pay tribute to original author of this code. I am not original author.
Pages:
Jump to: