Skip to content

Commit

Permalink
style cleanup
Browse files Browse the repository at this point in the history
git-svn-id: svn://forre.st/p2pool@1387 470744a7-cac9-478e-843e-5ec1b25c69e8
  • Loading branch information
forrest committed Jul 14, 2011
1 parent c4e6779 commit 942376c
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 109 deletions.
4 changes: 2 additions & 2 deletions dump_addrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
import db
import p2p

print "main"
print 'main'
x = p2p.AddrStore(db.SQLiteDict(sqlite3.connect(os.path.join(os.path.dirname(__file__), 'addrs.dat'), isolation_level=None), 'addrs'))

for k, v in x.iteritems():
print k, v

print
print "testnet"
print 'testnet'
x = p2p.AddrStore(db.SQLiteDict(sqlite3.connect(os.path.join(os.path.dirname(__file__), 'addrs.dat'), isolation_level=None), 'addrs_testnet'))

for k, v in x.iteritems():
Expand Down
32 changes: 16 additions & 16 deletions p2pool/bitcoin/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,9 @@ def read(self, file):

def write(self, file, item):
if not 0 <= item < 2**256:
raise ValueError("invalid hash value - %r" % (item,))
raise ValueError('invalid hash value - %r' % (item,))
if item != 0 and item < 2**160:
warnings.warn("very low hash value - maybe you meant to use ShortHashType? %x" % (item,))
warnings.warn('very low hash value - maybe you meant to use ShortHashType? %x' % (item,))
return file, ('%064x' % (item,)).decode('hex')[::-1]

class ShortHashType(Type):
Expand All @@ -172,7 +172,7 @@ def read(self, file):

def write(self, file, item):
if not 0 <= item < 2**160:
raise ValueError("invalid hash value - %r" % (item,))
raise ValueError('invalid hash value - %r' % (item,))
return file, ('%040x' % (item,)).decode('hex')[::-1]

class ListType(Type):
Expand Down Expand Up @@ -209,20 +209,20 @@ def write(self, file, item):
data = struct.pack(self.desc, item)
if struct.unpack(self.desc, data)[0] != item:
# special test because struct doesn't error on some overflows
raise ValueError("item didn't survive pack cycle (%r)" % (item,))
raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
return file, data

class IPV6AddressType(Type):
def read(self, file):
data, file = read(file, 16)
if data[:12] != '00000000000000000000ffff'.decode('hex'):
raise ValueError("ipv6 addresses not supported yet")
raise ValueError('ipv6 addresses not supported yet')
return '.'.join(str(ord(x)) for x in data[12:]), file

def write(self, file, item):
bits = map(int, item.split('.'))
if len(bits) != 4:
raise ValueError("invalid address: %r" % (bits,))
raise ValueError('invalid address: %r' % (bits,))
data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
assert len(data) == 16, len(data)
return file, data
Expand Down Expand Up @@ -251,7 +251,7 @@ def read(self, file):
data = self.inner.pack(obj)

if file.read(4) != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
raise ValueError("invalid checksum")
raise ValueError('invalid checksum')

return obj, file

Expand All @@ -263,14 +263,14 @@ def write(self, file, item):
class FloatingIntegerType(Type):
# redundancy doesn't matter here because bitcoin checks binary bits against its own computed bits
# so it will always be encoded 'normally' in blocks (they way bitcoin does it)
_inner = StructType("<I")
_inner = StructType('<I')

def read(self, file):
bits, file = self._inner.read(file)
target = self._bits_to_target(bits)
if __debug__:
if self._target_to_bits(target) != bits:
raise ValueError("bits in non-canonical form")
raise ValueError('bits in non-canonical form')
return target, file

def write(self, file, item):
Expand All @@ -281,21 +281,21 @@ def truncate_to(self, x):

def _bits_to_target(self, bits2):
target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
assert target == self._bits_to_target1(struct.pack("<I", bits2))
assert target == self._bits_to_target1(struct.pack('<I', bits2))
assert self._target_to_bits(target, _check=False) == bits2
return target

def _bits_to_target1(self, bits):
bits = bits[::-1]
length = ord(bits[0])
return bases.string_to_natural((bits[1:] + "\0"*length)[:length])
return bases.string_to_natural((bits[1:] + '\0'*length)[:length])

def _target_to_bits(self, target, _check=True):
n = bases.natural_to_string(target)
if n and ord(n[0]) >= 128:
n = "\x00" + n
n = '\x00' + n
bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
bits = struct.unpack("<I", bits2)[0]
bits = struct.unpack('<I', bits2)[0]
if _check:
if self._bits_to_target(bits) != target:
raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
Expand All @@ -312,7 +312,7 @@ def read(self, file):

def write(self, file, item):
if item == self.none_value:
raise ValueError("none_value used")
raise ValueError('none_value used')
return self.inner.write(file, self.none_value if item is None else item)

address_type = ComposedType([
Expand Down Expand Up @@ -373,7 +373,7 @@ def target_to_average_attempts(target):
# human addresses

human_address_type = ChecksummedType(ComposedType([
('version', StructType("<B")),
('version', StructType('<B')),
('pubkey_hash', ShortHashType()),
]))

Expand Down Expand Up @@ -497,7 +497,7 @@ def get_highest_height(self):

def get_nth_parent_hash(self, item_hash, n):
if n < 0:
raise ValueError("n must be >= 0")
raise ValueError('n must be >= 0')

updates = {}
while n:
Expand Down
10 changes: 5 additions & 5 deletions p2pool/bitcoin/getwork.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __repr__(self):
def getwork(self, target=None, _check=3):
target2 = self.target if target is None else target
#if target2 >= 2**256//2**32:
# raise ValueError("target higher than standard maximum")
# raise ValueError('target higher than standard maximum')

block_data = bitcoin_data.block_header_type.pack(dict(
version=self.version,
Expand Down Expand Up @@ -85,10 +85,10 @@ def decode_data(data):
'data': '0000000163930d52a5ffca79b29b95a659a302cd4e1654194780499000002274000000002e133d9e51f45bc0886d05252038e421e82bff18b67dc14b90d9c3c2f422cd5c4dd4598e1a44b9f200000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000'
}, _check=100)
BlockAttempt.from_getwork({
"midstate" : "f4a9b048c0cb9791bc94b13ee0eec21e713963d524fd140b58bb754dd7b0955f",
"data" : "000000019a1d7342fb62090bda686b22d90f9f73d0f5c418b9c980cd0000011a00000000680b07c8a2f97ecd831f951806857e09f98a3b81cdef1fa71982934fef8dc3444e18585d1a0abbcf00000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000",
"hash1" : "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000",
"target" : "0000000000000000000000000000000000000000000000cfbb0a000000000000"
'midstate' : 'f4a9b048c0cb9791bc94b13ee0eec21e713963d524fd140b58bb754dd7b0955f',
'data' : '000000019a1d7342fb62090bda686b22d90f9f73d0f5c418b9c980cd0000011a00000000680b07c8a2f97ecd831f951806857e09f98a3b81cdef1fa71982934fef8dc3444e18585d1a0abbcf00000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000',
'hash1' : '00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000',
'target' : '0000000000000000000000000000000000000000000000cfbb0a000000000000'
})
ba = BlockAttempt(
1,
Expand Down
12 changes: 6 additions & 6 deletions p2pool/bitcoin/p2p.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def dataReceiver(self):
print 'INVALID HASH'
continue

type_ = getattr(self, "message_" + command, None)
type_ = getattr(self, 'message_' + command, None)
if type_ is None:
print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
print 'NO TYPE FOR', repr(command)
Expand Down Expand Up @@ -80,7 +80,7 @@ def dataReceiver(self):
def sendPacket(self, command, payload2):
if len(command) >= 12:
raise ValueError('command too long')
type_ = getattr(self, "message_" + command, None)
type_ = getattr(self, 'message_' + command, None)
if type_ is None:
raise ValueError('invalid command')
#print 'SEND', command, repr(payload2)[:500]
Expand Down Expand Up @@ -184,7 +184,7 @@ def handle_inv(self, invs):
elif inv['type'] == 'block':
self.factory.new_block.happened(inv['hash'])
else:
print "Unknown inv type", item
print 'Unknown inv type', item

message_getdata = bitcoin_data.ComposedType([
('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
Expand Down Expand Up @@ -248,7 +248,7 @@ def handle_headers(self, headers):
message_reply = bitcoin_data.ComposedType([
('hash', bitcoin_data.HashType()),
('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
('script', bitcoin_data.PossiblyNone("", bitcoin_data.VarStrType())),
('script', bitcoin_data.PossiblyNone('', bitcoin_data.VarStrType())),
])
def handle_reply(self, hash, reply, script):
self.check_order.got_response(hash, dict(reply=reply, script=script))
Expand All @@ -263,7 +263,7 @@ def handle_ping(self):
('signature', bitcoin_data.VarStrType()),
])
def handle_alert(self, message, signature):
print "ALERT:", (message, signature)
print 'ALERT:', (message, signature)

def connectionLost(self, reason):
if hasattr(self.factory, 'gotConnection'):
Expand Down Expand Up @@ -372,7 +372,7 @@ def heard_headers(self, headers):
print len(self.tracker.shares)

def request(self, have, last):
#print "REQ", ('[' + ', '.join(map(hex, have)) + ']', hex(last) if last is not None else None)
#print 'REQ', ('[' + ', '.join(map(hex, have)) + ']', hex(last) if last is not None else None)
if self.factory.conn.value is not None:
self.factory.conn.value.send_getheaders(version=1, have=have, last=last)

Expand Down
48 changes: 11 additions & 37 deletions p2pool/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, inner):
def read(self, file):
values, file = bitcoin_data.ListType(self.inner).read(file)
if values != sorted(set(values)):
raise ValueError("invalid values")
raise ValueError('invalid values')
references, file = bitcoin_data.ListType(bitcoin_data.VarIntType()).read(file)
return [values[reference] for reference in references], file

Expand Down Expand Up @@ -166,8 +166,8 @@ def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
self.hash = bitcoin_data.block_header_type.hash256(header)

if self.hash > self.target2:
print "hash", hex(self.hash)
print "targ", hex(self.target2)
print 'hash', hex(self.hash)
print 'targ', hex(self.target2)
raise ValueError('not enough work!')


Expand Down Expand Up @@ -198,11 +198,11 @@ def check(self, tracker, net):
gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)

if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
raise ValueError("gentx doesn't match header via merkle_branch")
raise ValueError('''gentx doesn't match header via merkle_branch''')

if self.other_txs is not None:
if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
raise ValueError("gentx doesn't match header via other_txs")
raise ValueError('''gentx doesn't match header via other_txs''')

self.gentx = gentx

Expand Down Expand Up @@ -246,9 +246,9 @@ def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonc
pre_target2 = math.clip(pre_target, (previous_share2.target2*9//10, previous_share2.target2*11//10))
pre_target3 = math.clip(pre_target2, (0, 2**256//2**24 - 1))
target2 = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
print attempts_per_second//1000, "KHASH"
#print "TARGET", 2**256//target2, 2**256/pre_target
#print "ATT", bitcoin_data.target_to_average_attempts(target2)//1000
print attempts_per_second//1000, 'KHASH'
#print 'TARGET', 2**256//target2, 2**256/pre_target
#print 'ATT', bitcoin_data.target_to_average_attempts(target2)//1000


attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
Expand Down Expand Up @@ -307,35 +307,9 @@ def __init__(self, net):
bitcoin_data.Tracker.__init__(self)
self.net = net
self.verified = bitcoin_data.Tracker()
"""
self.okay_cache = {} # hash -> height

def is_okay(self, start, _height_after=0):
'''
Returns:
{'result': 'okay', verified_height: ...} # if share has an okay parent or if share has CHAIN_LENGTH children and CHAIN_LENTH parents that it verified with
{'result': 'needs_share', 'share_hash': ...} # if share doesn't have CHAIN_LENGTH parents
#{'result': 'needs_share_shares', 'share_hash': ...} # if share has CHAIN_LENGTH children and needs its shares to
{'result': 'not_okay'} # if the share has a not okay parent or if the share has an okay parent and failed validation
'''
if start in self.okay_cache:
return dict(result='okay', verified_height=self.okay_cache['start'])
share = self.shares[start]
if start not in self.shares:
return dict(result='needs_share', share_hash=start)
length = len
to_end_rev = []
for share in itertools.islice(self.get_chain(start), self.net.CHAIN_LENGTH):
if share in self.okay_cache:
return validate(share, to_end_rev[::-1])
to_end_rev.append(share)
# picking up last share from for loop, ew
self.okay_cache.add(share)
return validate(share, to_end_rev[::-1])
"""
def attempt_verify(self, share):
height, last = self.get_height_and_last(share.hash)
if height < self.net.CHAIN_LENGTH and last is not None:
Expand All @@ -346,7 +320,7 @@ def attempt_verify(self, share):
share.check(self, self.net)
except:
print
print "Share check failed:"
print 'Share check failed:'
log.err()
print
return False
Expand Down Expand Up @@ -382,7 +356,7 @@ def think(self, ht):
get = can
else:
get = want
#print "Z", head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
#print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
for share in itertools.islice(self.get_chain_known(last_hash), get):
if not self.attempt_verify(share):
break
Expand Down
Loading

0 comments on commit 942376c

Please sign in to comment.