473,385 Members | 1,824 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Simple hashcash implementation


Hi!

Here's a simple hashcash implementation in Python.

28 lines of actual code.

Can be reduced to 17 lines for instructional purposes,
if you don't want clustering, and use xrange() instead
of irange().

I tried to make this as simple and elegant as possible.
Feel free to repost this code, if you can make the it
more simple.

I have made no attempt to optimize this code.

# ----------------------------------------------
# hashcash.py: Hashcash implementation
# ----------------------------------------------

"""
Hashcash is a "proof of work."

Example:
import sha
sha.new('denmark2890CF').hexdigest() '000000cf89643370c24e413ec0886ab92bd7f6e8'

Here we have a 24-bit partial SHA collision against the zero string.

This proves to us that someone took the prefix 'denmark', and
tried about 2**24 different suffixes. Thus we know that
someone has burnt around 2**24 CPU cycles on the prefix string
'denmark'. Usually, 'denmark' will be a unique challenge string,
so old hashcash cannot be recycled.

For speed, this library takes the hash of the string 'denmark' before
doing the collision with the zero string. Otherwise, it is identical
to the above example.

Library examples:
import hashcash
hashcash.make_token('Denmark', 22) '59538D' hashcash.verify_token('Denmark', '59538D') 22 t = hashcash.make_cluster('Denmark', 18)
t 'BC48-D5A1-F8C2-27F0-9CC0-DD31-2F04-2052-835-FFF1-E319-0E91-A9D0-D359
-E996-70BA' hashcash.verify_cluster('Denmark', t)

18

Note that make_token() takes wildly varying amounts of CPU time.
The make_cluster() function concatenates 16 hashcash tokens to even
out the amount of CPU time spent.

"""

import sha, math, itertools

def trailing_zeros(n):
"""Number of trailing 0s in binary representation of integer n."""
if n <= 0: return 0
for i in itertools.count(0):
if n & (1<<i): return i

def irange(n):
"""Implementation of xrange(n) that does not overflow."""
i = 0
while i < n:
yield i; i += 1

def all_strings(charset='0123456789ABCDEF'):
"""Yields all strings in given character set, sorted by length."""
m = len(charset)
for n in itertools.count(0):
for i in irange(m**n):
yield ''.join([charset[(i//(m**j))%m] for j in xrange(n)])

def hash(s):
"""Hash function used by hashcash. Returns an integer."""
return int(sha.new(s).hexdigest(), 16)

def make_token(s, n, charset='0123456789ABCDEF'):
"""Makes hashcash token of value 'n' against basestring 's'."""
h = sha.new(s).digest()
for token in all_strings(charset):
if trailing_zeros(hash(h + token)) >= n: return token

def verify_token(s, token):
"""Returns hashcash value of given token against basestring 's'."""
return trailing_zeros(hash(sha.new(s).digest() + token))

def make_cluster(s, n, charset='0123456789ABCDEF'):
"""Makes hashcash cluster of value 'n' against basestring 's'."""
return '-'.join([make_token(s+str(i),n-4,charset) for i in range(16)])

def verify_cluster(s, token):
"""Hashcash value of the given cluster against basestring 's'."""
T = token.split('-')
return min([verify_token(s+str(i), T[i]) for i in range(len(T))])+\
int(math.log(len(T)) / math.log(2.0))
This document is in public domain (as are all of my past Usenet postings).

- Connelly
Jul 18 '05 #1
1 2514
ba*****@engr.orst.edu wrote:
Here's a simple hashcash implementation in Python.
28 lines of actual code....


Looks like you've spent a bit of time on this. If you do think it
is generally useful, why not put it in the Python Cookbook?
<http://aspn.activestate.com/ASPN/Python/Cookbook/>

-Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: David Mertz, Ph.D. | last post by:
I decided to write a pure Python hashcash implementation. I have seen David McNab's Python implementation. Unfortunately, as near as I can tell (which is supported on the hashcash mailing list...
6
by: Beach Potato | last post by:
Hi: I've searched newsgroups and various archives, including MSDN & MFC sources, but at this point failed to locate an accurate and simple implementation of WndProc function for MSWindows window...
13
by: Michael B Allen | last post by:
Hi, I've tried to write the *simplest* memory allocator possible. I think it would be useful in many cases such as allocating memory on stack as a poor man's garbage collection perhaps. I was...
7
by: Ray Mitchell | last post by:
Hello, I realize that the source code for vsscanf is available from several sources, such as GNU. However, all such source code I've found so far is filled with cryptic (to me) #ifdefs, system...
16
by: Rod | last post by:
I can't get this alert to show no matter what I do. Making me crazy. One doesn't equal two...does it? <html> <head> <title>Rider Survey</title> <link rel="stylesheet" type="text/css"...
0
by: coosa | last post by:
Dear all; My code is is a bit long but is modular at least. I'm attempting to implement the depth first search for an application that is supposed to: 1- Fetch based on an ID from the database a...
17
by: marks542004 | last post by:
Hi all , I am an old programmer now hobbyist who has used cobol, basic, and RPG . I am new to c++ but have Microsoft Visual Studio 6.0. I have a program in Basic that reads a file , looks for...
19
by: pinkfloydhomer | last post by:
I can understand why properties are neat if you want to limit access (only get, no set), or you want to do some bookkeeping or sanity checking on values (in set) or if you want to change the...
30
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.