From 942376c7c347a7e0f55f592a31339775b1690d15 Mon Sep 17 00:00:00 2001 From: forrest Date: Thu, 14 Jul 2011 13:25:03 +0000 Subject: [PATCH] style cleanup git-svn-id: svn://forre.st/p2pool@1387 470744a7-cac9-478e-843e-5ec1b25c69e8 --- dump_addrs.py | 4 +- p2pool/bitcoin/data.py | 32 +++++++++++----------- p2pool/bitcoin/getwork.py | 10 +++--- p2pool/bitcoin/p2p.py | 12 ++++---- p2pool/data.py | 48 +++++++------------------------- p2pool/main.py | 65 ++++++++++++++++++++++--------------------- p2pool/p2p.py | 4 +- p2pool/util/bases.py | 2 +- p2pool/util/deferral.py | 2 +- p2pool/util/math.py | 4 +- p2pool/worker_interface.py | 8 +++--- setup.py | 2 +- 12 files changed, 84 insertions(+), 109 deletions(-) diff --git a/dump_addrs.py b/dump_addrs.py index 29b7300..c0330a1 100644 --- a/dump_addrs.py +++ b/dump_addrs.py @@ -6,14 +6,14 @@ import sqlite3 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(): diff --git a/p2pool/bitcoin/data.py b/p2pool/bitcoin/data.py index f9cef35..f4ec5d4 100644 --- a/p2pool/bitcoin/data.py +++ b/p2pool/bitcoin/data.py @@ -160,9 +160,9 @@ class HashType(Type): 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): @@ -172,7 +172,7 @@ class ShortHashType(Type): 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): @@ -209,20 +209,20 @@ class StructType(Type): 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 @@ -251,7 +251,7 @@ class ChecksummedType(Type): 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 @@ -263,14 +263,14 @@ class ChecksummedType(Type): 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("> 24) - 3)) - assert target == self._bits_to_target1(struct.pack("= 128: - n = "\x00" + n + n = '\x00' + n bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1] - bits = struct.unpack("= 0") + raise ValueError('n must be >= 0') updates = {} while n: diff --git a/p2pool/bitcoin/getwork.py b/p2pool/bitcoin/getwork.py index 9173514..6e2d4fe 100644 --- a/p2pool/bitcoin/getwork.py +++ b/p2pool/bitcoin/getwork.py @@ -35,7 +35,7 @@ class BlockAttempt(object): 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, @@ -85,10 +85,10 @@ if __name__ == '__main__': '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, diff --git a/p2pool/bitcoin/p2p.py b/p2pool/bitcoin/p2p.py index 19064d5..aaf46d6 100644 --- a/p2pool/bitcoin/p2p.py +++ b/p2pool/bitcoin/p2p.py @@ -49,7 +49,7 @@ class BaseProtocol(protocol.Protocol): 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) @@ -80,7 +80,7 @@ class BaseProtocol(protocol.Protocol): 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] @@ -184,7 +184,7 @@ class Protocol(BaseProtocol): 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([ @@ -248,7 +248,7 @@ class Protocol(BaseProtocol): message_reply = bitcoin_data.ComposedType([ ('hash', bitcoin_data.HashType()), ('reply', bitcoin_data.EnumType(bitcoin_data.StructType(' 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!') @@ -198,11 +198,11 @@ class Share(object): 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 @@ -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) @@ -307,35 +307,9 @@ class OkayTracker(bitcoin_data.Tracker): 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: @@ -346,7 +320,7 @@ class OkayTracker(bitcoin_data.Tracker): share.check(self, self.net) except: print - print "Share check failed:" + print 'Share check failed:' log.err() print return False @@ -382,7 +356,7 @@ class OkayTracker(bitcoin_data.Tracker): 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 diff --git a/p2pool/main.py b/p2pool/main.py index 81f5395..56e764d 100644 --- a/p2pool/main.py +++ b/p2pool/main.py @@ -93,7 +93,7 @@ def get_last_p2pool_block_hash(current_block_hash, get_block, net): block = yield get_block(block_hash) except: print - print "Error getting block while searching block chain:" + print 'Error getting block while searching block chain:' log.err() print continue @@ -135,24 +135,24 @@ def getwork(bitcoind): @defer.inlineCallbacks def get_payout_script(factory): - while True: - try: - res = yield (yield factory.getProtocol()).check_order(order=bitcoin.p2p.Protocol.null_order) - if res['reply'] != 'success': - print - print 'Error getting payout script:' - print res - print - continue - my_script = res['script'] - except Exception: + while True: + try: + res = yield (yield factory.getProtocol()).check_order(order=bitcoin.p2p.Protocol.null_order) + if res['reply'] != 'success': print print 'Error getting payout script:' - log.err() + print res print - else: - defer.returnValue(my_script) - yield deferral.sleep(1) + continue + my_script = res['script'] + except Exception: + print + print 'Error getting payout script:' + log.err() + print + else: + defer.returnValue(my_script) + yield deferral.sleep(1) @defer.inlineCallbacks def main(args): @@ -162,7 +162,7 @@ def main(args): # connect to bitcoind over JSON-RPC and do initial getwork url = 'http://%s:%i/' % (args.bitcoind_address, args.bitcoind_rpc_port) - print "Testing bitcoind RPC connection to '%s' with authorization '%s:%s'..." % (url, args.bitcoind_rpc_username, args.bitcoind_rpc_password) + print '''Testing bitcoind RPC connection to '%s' with authorization '%s:%s'...''' % (url, args.bitcoind_rpc_username, args.bitcoind_rpc_password) bitcoind = jsonrpc.Proxy(url, (args.bitcoind_rpc_username, args.bitcoind_rpc_password)) work, height = yield getwork(bitcoind) print ' ...success!' @@ -170,7 +170,7 @@ def main(args): print # connect to bitcoind over bitcoin-p2p and do checkorder to get pubkey to send payouts to - print "Testing bitcoind P2P connection to '%s:%s'..." % (args.bitcoind_address, args.bitcoind_p2p_port) + print '''Testing bitcoind P2P connection to '%s:%s'...''' % (args.bitcoind_address, args.bitcoind_p2p_port) factory = bitcoin.p2p.ClientFactory(args.net) reactor.connectTCP(args.bitcoind_address, args.bitcoind_p2p_port, factory) my_script = yield get_payout_script(factory) @@ -235,12 +235,12 @@ def main(args): print 'Got duplicate share, ignoring. Hash: %x' % (share.hash,) return - #print "Received share %x" % (share.hash,) + #print 'Received share %x' % (share.hash,) tracker.add(share) best, desired = tracker.think(ht) for peer2, share_hash in desired: - print "Requesting parent share %x" % (share_hash,) + print 'Requesting parent share %x' % (share_hash,) peer2.send_getshares(hashes=[share_hash]) if share.gentx is not None: @@ -264,9 +264,9 @@ def main(args): def p2p_share_hash(share_hash, peer): if share_hash in tracker.shares: - print "Got share hash, already have, ignoring. Hash: %x" % (share_hash,) + print 'Got share hash, already have, ignoring. Hash: %x' % (share_hash,) else: - print "Got share hash, requesting! Hash: %x" % (share_hash,) + print 'Got share hash, requesting! Hash: %x' % (share_hash,) peer.send_getshares(hashes=[share_hash]) def p2p_get_to_best(chain_id_data, have, peer): @@ -307,7 +307,7 @@ def main(args): nodes.append(((yield reactor.resolve('p2pool.forre.st')), args.net.P2P_PORT)) except: print - print "Error resolving bootstrap node IP:" + print 'Error resolving bootstrap node IP:' log.err() print @@ -349,17 +349,18 @@ def main(args): def compute(state): extra_txs = [tx for tx in tx_pool.itervalues() if tx.is_good()] # XXX limit to merkle_branch and block max size - 1000000 byte + # and sigops generate_tx = p2pool.generate_transaction( tracker=tracker, previous_share_hash=state['best_share_hash'], new_script=my_script, subsidy=(50*100000000 >> state['height']//210000) + sum(tx.value_in - tx.value_out for tx in extra_txs), - nonce=struct.pack(" timestamp: - print "Toff", timestamp2 - timestamp + print 'Toff', timestamp2 - timestamp timestamp = timestamp2 ba = bitcoin.getwork.BlockAttempt(state['version'], state['previous_block'], merkle_root, timestamp, state['target']) - #print "SENT", 2**256//p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2'] + #print 'SENT', 2**256//p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2'] return ba.getwork(p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2']) def got_response(data): @@ -380,7 +381,7 @@ def main(args): header = bitcoin.getwork.decode_data(data) transactions = merkle_root_to_transactions.get(header['merkle_root'], None) if transactions is None: - print "Couldn't link returned work's merkle root with its transactions - should only happen if you recently restarted p2pool" + print '''Couldn't link returned work's merkle root with its transactions - should only happen if you recently restarted p2pool''' return False block = dict(header=header, txs=transactions) hash_ = bitcoin.data.block_header_type.hash256(block['header']) @@ -430,9 +431,9 @@ def main(args): self.seen_at_block = seen_at_block self.mentions = set([bitcoin.data.tx_type.hash256(tx)] + [tx_in['previous_output']['hash'] for tx_in in tx['tx_ins']]) #print - #print "%x %r" % (seen_at_block, tx) + #print '%x %r' % (seen_at_block, tx) #for mention in self.mentions: - # print "%x" % mention + # print '%x' % mention #print self.parents_all_in_blocks = False self.value_in = 0 @@ -457,7 +458,7 @@ def main(args): if not self.parents_all_in_blocks: return False x = self.is_good2() - #print "is_good:", x + #print 'is_good:', x return x def is_good2(self): @@ -478,7 +479,7 @@ def main(args): tx_pool[bitcoin.data.tx_type.hash256(tx)] = Tx(tx, current_work.value['previous_block']) except: print - print "Error handling tx:" + print 'Error handling tx:' log.err() print factory.new_tx.watch(new_tx) diff --git a/p2pool/p2p.py b/p2pool/p2p.py index b74b8fc..212e4c3 100644 --- a/p2pool/p2p.py +++ b/p2pool/p2p.py @@ -370,7 +370,7 @@ class Node(object): def attempt_ended(self, connector): host, port = connector.getDestination().host, connector.getDestination().port if (host, port) not in self.attempts: - raise ValueError("don't have attempt") + raise ValueError('''don't have attempt''') if connector is not self.attempts[host, port]: raise ValueError('wrong connector') del self.attempts[host, port] @@ -385,7 +385,7 @@ class Node(object): def lost_conn(self, conn): if conn.nonce not in self.peers: - raise ValueError("don't have peer") + raise ValueError('''don't have peer''') if conn is not self.peers[conn.nonce]: raise ValueError('wrong conn') del self.peers[conn.nonce] diff --git a/p2pool/util/bases.py b/p2pool/util/bases.py index 9c45589..2d043b2 100644 --- a/p2pool/util/bases.py +++ b/p2pool/util/bases.py @@ -15,7 +15,7 @@ def natural_to_string(n, alphabet=None, min_width=0): def string_to_natural(s, alphabet=None): if alphabet is None: s = s.encode('hex') - return int("0"+s, 16) + return int('0'+s, 16) assert len(set(alphabet)) == len(alphabet) if not s or (s != alphabet[0] and s.startswith(alphabet[0])): raise ValueError() diff --git a/p2pool/util/deferral.py b/p2pool/util/deferral.py index 60a0add..90e9918 100644 --- a/p2pool/util/deferral.py +++ b/p2pool/util/deferral.py @@ -158,7 +158,7 @@ class DeferredCacher(object): def eb(fail): self.waiting.pop(key).callback(None) print - print "Error when requesting noncached value:" + print 'Error when requesting noncached value:' fail.printTraceback() print self.func(key).addCallback(cb).addErrback(eb) diff --git a/p2pool/util/math.py b/p2pool/util/math.py index 0442c36..d291d1e 100644 --- a/p2pool/util/math.py +++ b/p2pool/util/math.py @@ -7,7 +7,7 @@ def median(x, use_float=True): # there exist better algorithms... y = sorted(x) if not y: - raise ValueError("empty sequence!") + raise ValueError('empty sequence!') left = (len(y) - 1)//2 right = len(y)//2 sum = y[left] + y[right] @@ -43,7 +43,7 @@ def nth(i, n=0): def geometric(p): if p <= 0 or p > 1: - raise ValueError("p must be in the interval (0.0, 1.0]") + raise ValueError('p must be in the interval (0.0, 1.0]') if p == 1: return 1 return int(math.log1p(-random.random()) / math.log1p(-p)) + 1 diff --git a/p2pool/worker_interface.py b/p2pool/worker_interface.py index cf4fb67..82ba7cc 100644 --- a/p2pool/worker_interface.py +++ b/p2pool/worker_interface.py @@ -42,7 +42,7 @@ class WorkerInterface(jsonrpc.Server): self.putChild('', self) def rpc_getwork(self, data=None): - if data is not None: - return self.response_callback(data) - - return self.compute(self.work.value) + if data is not None: + return self.response_callback(data) + + return self.compute(self.work.value) diff --git a/setup.py b/setup.py index fc3b28b..f0204d5 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from distutils.core import setup try: import py2exe except ImportError: - print "missing py2exe" + print 'missing py2exe' setup(name='p2pool', -- 1.7.1