Question

I'm trying to figure out how does simple Bitcoin mining algorithm works in plain simple c or c# or some pseudo language. I've found an example at http://pastebin.com/EXDsRbYH, but unfortunately It isn't clear what it does. I was unable to run it.

Suppose I have only one input: a Bitcoin wallet "abc..." which I would like to be used for the Bitcoins to be mined. I need simple to understand algorithm that will do the bitcoin mining on one machine with one thread on one cpu [I know it will take ages to complete :)]

Was it helpful?

Solution

Super-dumb and rather useless, but I did this one for demo purposes once:

from hashlib import md5
from random import random
import sys

# what to hash
data = "Bitcoins!"

# This is just a first run to init the variables 
h = md5(data.encode('utf-8'))
v = h.digest()
best = v
best_i = data
best_vhex = h.hexdigest()

# x ist just a helper to only display
# a subset of all updates (calculates faster)
x = 0
step = 100

# In reality, this loop stops when the "h" hash
# is below a certain threshold (called "difficulty")
while True:
  i = data + str(random())
  h = md5(i.encode('utf-8'))
  v = h.digest()
  vhex = h.hexdigest()

  # log progress
  if v < best or x > step:
    msg = "%-25s | %-25s -> %s" % (i, best_i, best_vhex)
    sys.stdout.write('\r' + msg)
    x = 0
  else:
    x += 1

  # check if new best one
  if v < best:
    best_i, best, best_vhex = i, v, vhex
    print
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top