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():
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):
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):
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
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
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):
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))))
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([
# human addresses
human_address_type = ChecksummedType(ComposedType([
- ('version', StructType("<B")),
+ ('version', StructType('<B')),
('pubkey_hash', ShortHashType()),
]))
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:
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,
'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,
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)
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]
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([
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))
('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'):
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)
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
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!')
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
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)
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:
share.check(self, self.net)
except:
print
- print "Share check failed:"
+ print 'Share check failed:'
log.err()
print
return False
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
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
@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):
# 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!'
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)
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:
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):
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
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("<Q", random.randrange(2**64)),
+ nonce=struct.pack('<Q', random.randrange(2**64)),
block_target=state['target'],
net=args.net,
)
print 'Generating!', 2**256//p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2']//1000000
- print "Target: %x" % (p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2'],)
+ print 'Target: %x' % (p2pool.coinbase_type.unpack(generate_tx['tx_ins'][0]['script'])['share_data']['target2'],)
#, have', shares.count(my_script) - 2, 'share(s) in the current chain. Fee:', sum(tx.value_in - tx.value_out for tx in extra_txs)/100000000
transactions = [generate_tx] + [tx.tx for tx in extra_txs]
merkle_root = bitcoin.data.merkle_hash(transactions)
if state['best_share_hash'] is not None:
timestamp2 = math.median((s.timestamp for s in itertools.islice(tracker.get_chain_to_root(state['best_share_hash']), 11)), use_float=False) + 1
if timestamp2 > 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):
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'])
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
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):
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)
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]
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]
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()
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)
# 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]
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
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)
try:
import py2exe
except ImportError:
- print "missing py2exe"
+ print 'missing py2exe'
setup(name='p2pool',