def history_callback(self, msg_id, msg, param): for each in param: TxStore().add(msg['params'][0], each['tx_hash'], each['height']) for tx, height in TxStore().unverify_tx_list: NetWorkManager().add_message(GetMerkle([tx, height]), self.get_merkle_callback) for tx in TxStore().unfetch_tx: NetWorkManager().add_message(Get([tx]), self.get_tx_callback)
def __init__(self): set_testnet() # logging.config.fileConfig(log_conf_path) init() network = NetWorkManager() network.start() BlockChain().init_header() # todo: init from config self.conf = MyConfigParser() self.conf.read(conf_path) self.wallet_dict = SortedDict() for k, v in self.conf.items('wallet'): if k.startswith('wallet_name_'): wallet_name = k[12:] wallet_type = self.conf.get('wallet', 'wallet_type_' + wallet_name) wallet_config_file = v # self.conf.get('wallet', k) self.wallet_dict[wallet_name] = self.init_wallet( wallet_type, wallet_config_file) self._current = self.conf.get('wallet', 'current') if self._current is not None: self.current_wallet = self.wallet_dict[self._current] self.current_wallet.sync() else: self.current_wallet = None
def init_header(self): if BlockStore().height <= 0: # NetWorkManager().init_header(self.init_header_callback) NetWorkManager().add_message(GetHeaderFile([]), self.init_header_callback) else: NetWorkManager().add_message( headers_subscribe([]), callback=self.catch_up, subscribe=self.receive_header) # do not have id
def test_hd_cold_hot_wallet(): global network, hot_wallet set_testnet() logging.config.fileConfig('logging.conf') # drop() init() network = NetWorkManager() network.start_ioloop() network.start_client() # BlockChain().init_header() network.add_message(Version(["2.8.2", "0.10"])) hot_wallet = HDWatchOnlyWallet(WalletConfig(store_path='hd_hot_wallet.json')) seed = from_seed(u'reopen panel title aerobic wheat fury blame cement swarm wheel ball where', None) hot_wallet.xpub = seed.xpub hot_wallet.keystore = BIP32KeyHotStore({}) hot_wallet.keystore.xpub = seed.xpub hot_wallet.sync() hot_wallet.synchronize() print hot_wallet.get_change_addresses() print hot_wallet.get_receiving_addresses() outputs = [Output((TYPE_ADDRESS, 'mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj', 100000))] tx = hot_wallet.make_unsigned_transaction(hot_wallet.get_utxo(), outputs, {}) print tx cold_wallet = HDWallet(WalletConfig(store_path='hd_cold_wallet.json')) if cold_wallet.keystore is None: cold_wallet.init_key_store(seed) cold_wallet.sign_transaction(tx, None) print tx
def init_header_callback(self, future): try: dt = datetime.now() result = future.result() cnt = len(result) for idx in xrange(cnt / (80 * BLOCK_INTERVAL)): print idx BlockStore().connect_chunk( idx, result[idx * 80 * BLOCK_INTERVAL:idx * 80 * BLOCK_INTERVAL + 80 * BLOCK_INTERVAL]) if cnt > cnt / (80 * BLOCK_INTERVAL) * (80 * BLOCK_INTERVAL): for idx in xrange((cnt - (cnt / (80 * BLOCK_INTERVAL) * (80 * BLOCK_INTERVAL))) / 80): height = cnt / (80 * BLOCK_INTERVAL) * BLOCK_INTERVAL + idx header = BlockStore().deserialize_header( result[(cnt / (80 * BLOCK_INTERVAL) * BLOCK_INTERVAL + idx) * 80:(cnt / (80 * BLOCK_INTERVAL) * BLOCK_INTERVAL + idx) * 80 + 80]) BlockStore().connect_header(header, height) print height print datetime.now() - dt from electrumq.message.all import headers_subscribe NetWorkManager().add_message( headers_subscribe([]), callback=self.catch_up, subscribe=self.receive_header) # do not have id except Exception as ex: print ex traceback.print_exc()
def init_header_callback(self, future): try: result = future.result() block_cnt = len(result) / 80 for idx in xrange(block_cnt / BLOCK_INTERVAL): BlockStore().connect_chunk( idx, result[idx * 80 * BLOCK_INTERVAL:idx * 80 * BLOCK_INTERVAL + 80 * BLOCK_INTERVAL]) if block_cnt > block_cnt / BLOCK_INTERVAL * BLOCK_INTERVAL: for idx in xrange(block_cnt - (block_cnt / BLOCK_INTERVAL * BLOCK_INTERVAL)): height = block_cnt / BLOCK_INTERVAL * BLOCK_INTERVAL + idx BlockStore().connect_raw_header( result[(block_cnt / BLOCK_INTERVAL * BLOCK_INTERVAL + idx) * 80:(block_cnt / BLOCK_INTERVAL * BLOCK_INTERVAL + idx) * 80 + 80], height) NetWorkManager().add_message( headers_subscribe([]), callback=self.catch_up, subscribe=self.receive_header) # do not have id except Exception as ex: logger.exception(ex.message) traceback.print_exc()
def test_application(self): manager = NetWorkManager() manager.start() @gen.coroutine def version_callback(msg_id, msg, param): self.is_callback = True self.assertEqual(msg_id, 0) self.assertEqual(msg, {'params': {}, 'method': 'server.version'}) manager.add_message(Version({}), version_callback) manager.quit()
class HowToUseChain(AsyncTestCase): def setUp(self): super(HowToUseChain, self).setUp() self.manager = NetWorkManager() self.manager.start() def tearDown(self): self.manager.quit() self.wait_quit() super(HowToUseChain, self).tearDown() @gen_test() def wait_quit(self): yield gen.sleep(MAX_WAIT_SECONDS_BEFORE_SHUTDOWN + 0.01) def test_application(self): bc = BlockChain() future = Future() future.set_result(open('../files/testnet_headers').read()) bc.init_header_callback(future)
def test_detail(self): manager = NetWorkManager() self.ioloop = IOLoop() self.ioloop.start() ip, port = manager.get_server() self.client = RPCClient(ioloop=self.ioloop, ip=ip, port=port) result = yield self.client.connect_with_future() self.assertTrue(result) @gen.coroutine def version_callback(msg_id, msg, param): self.is_callback = True self.assertEqual(msg_id, 0) self.assertEqual(msg, {'params': {}, 'method': 'server.version'}) self.client.add_message(Version({}), version_callback) yield gen.sleep(2) self.ioloop.quit() yield gen.sleep(self.ioloop.loop_quit_wait + 0.01)
def catch_up(self, msg_id, msg, result): logger.debug('catchup %s, %s, %s' % (msg_id, msg, result)) height = result['block_height'] local_height = BlockStore().height if height > local_height: from electrumq.message.all import GetHeader, GetChunk next_height = min( height, local_height / BLOCK_INTERVAL * BLOCK_INTERVAL + BLOCK_INTERVAL - 1) logger.debug( 'catch up trunc from %d to %d' % (next_height / BLOCK_INTERVAL, height / BLOCK_INTERVAL)) for h in xrange(next_height / BLOCK_INTERVAL, height / BLOCK_INTERVAL + 1): NetWorkManager().add_message(GetChunk([h]), self.get_trunc_callback)
def catch_up(self, msg_id, msg, result): print 'catchup', msg_id, msg, result height = result['block_height'] local_height = BlockStore().height if height > local_height: from electrumq.message.all import GetChunk next_height = min( height, local_height / BLOCK_INTERVAL * BLOCK_INTERVAL + 2015) # logger.debug('catch up header from %d to %d' % (local_height + 1, next_height)) # for h in xrange(local_height + 1, next_height + 1): # # pass # NetWorkManager().client.add_message(GetHeader([h]), self.connect_header2) logger.debug( 'catch up trunc from %d to %d' % (next_height / BLOCK_INTERVAL, height / BLOCK_INTERVAL)) for h in xrange(next_height / BLOCK_INTERVAL, height / BLOCK_INTERVAL + 1): NetWorkManager().add_message(GetChunk([h]), self.get_trunc_callback)
def test_hd_wallet(): global network, hot_wallet set_testnet() logging.config.fileConfig('logging.conf') # drop() init() network = NetWorkManager() network.start_ioloop() network.start_client() network.add_message(Version(["2.8.2", "0.10"])) hot_wallet = HDWallet(WalletConfig(store_path='hd_wallet.json')) if hot_wallet.keystore is None: hot_wallet.init_key_store(from_seed(u'reopen panel title aerobic wheat fury blame cement swarm wheel ball where', None)) hot_wallet.sync() hot_wallet.synchronize() print hot_wallet.get_change_addresses() print hot_wallet.get_receiving_addresses() inputs = [ {'prevout_hash': e[0], 'prevout_n': e[1], 'scriptSig': e[2], 'value': e[3], 'address': e[4], 'coinbase': False, 'height': 10000} for e in TxStore().get_unspend_outs('mipTN4UeM9Ab9PH5dU9XA5MjwAJnzkwCpX')] outputs = [] outputs.append((TYPE_ADDRESS, 'mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj', 100000))
def sync(self): NetWorkManager().add_message(GetHistory([self.address]), self.history_callback)
def test_base_wallet(self): network = NetWorkManager() network.start() wallet = SimpleWallet( WalletConfig(store_path=dirs.user_data_dir + '/' + '00.json')) wallet.sync()
def sync(self): for address in (self.receiving_addresses + self.change_addresses): NetWorkManager().add_message(GetHistory([address]), self.history_callback)
def test_cold_hot_wallet(): global network, hot_wallet set_testnet() logging.config.fileConfig('logging.conf') # drop() init() network = NetWorkManager() network.start_ioloop() network.start_client() BlockChain().init_header() network.add_message(Version(["2.8.2", "0.10"])) network.add_message(GetHistory(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(GetMempool(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(GetBalance(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(Listunspent(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(address_subscribe( ['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) # 'mmXqJTLjjyD6Xp2tJ7syCeZTcwvRjcojLz' hot_wallet = WatchOnlySimpleWallet(WalletConfig(store_path='watch_only_simple_wallet.json')) secret = '\x20\x12\x10\x09' + '\x09' * 28 if hot_wallet.keystore is None: hot_wallet.init_key_store( WatchOnlySimpleKeyStore.create(public_key_from_private_key(secret))) # hot_wallet.sync() inputs = [ {'prevout_hash': e[0], 'prevout_n': e[1], 'scriptSig': e[2], 'value': e[3], 'address': e[4], 'coinbase': False, 'height': 10000} for e in TxStore().get_unspend_outs('mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj')] outputs = [] outputs.append(Output((TYPE_ADDRESS, 'mkp8FGgySzhh5mmmHDcxRxmeS3X5fXm68i', 100000))) tx = hot_wallet.make_unsigned_transaction(inputs, outputs, {}) print tx cold_wallet = ColdSimpleWallet(WalletConfig(store_path='cold_simple_wallet.json')) if cold_wallet.keystore is None: cold_wallet.init_key_store(SimpleKeyStore.create(SecretToASecret(secret, True), None)) cold_wallet.sign_transaction(tx, None) # SecretToASecret('\x11'*16, True) print tx
def test_simple_wallet(): global network, hot_wallet set_testnet() keystore = ImportedKeyStore({}) keystore = ImportedKeyStore(keystore.dump()) pubkey = keystore.import_key(SecretToASecret('\x20\x12\x10\x09' + '\x09' * 28, True), None) address = public_key_to_p2pkh(pubkey.decode('hex')) pubkey2 = ImportedKeyStore({}).import_key( SecretToASecret('\x20\x14\x12\x05' + '\x09' * 28, True), None) address2 = public_key_to_p2pkh(pubkey2.decode('hex')) logging.config.fileConfig('logging.conf') # drop() init() network = NetWorkManager() network.start_ioloop() network.start_client() @gen.coroutine def prt1(msg_id, msg, result): print msg_id, msg, result print 'hahahaha' print 'hahahaha' print 'hahahaha' print 'hahahaha' @gen.coroutine def prt2(params): print params print 'hehehehe' print 'hehehehe' print 'hehehehe' print 'hehehehe' network.add_message(Version(["2.8.2", "0.10"])) # network.client.add_message(Banner([])) # network.client.add_message(DonationAddress([])) # network.client.add_message(peer_subscribe([])) # # network.client.add_message(address_subscribe(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # network.client.add_message(GetHistory(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # network.client.add_message(GetMempool(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # network.client.add_message(GetBalance(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # # network.client.add_message(GetProof(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # not implemented # network.client.add_message(Listunspent(["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"])) # network.client.add_message(GetAddress(["50d958904e0ab7bac04cbc7f81e27d14143306ba2ad04f3770bf36dfa388e059", 0])) # network.client.add_message(GetHeader([461358])) # network.client.add_message(GetChunk([461358 / 2016])) # # network.client.add_message(broadcast([])) # network.client.add_message(GetMerkle(["50d958904e0ab7bac04cbc7f81e27d14143306ba2ad04f3770bf36dfa388e059", 461358])) # network.client.add_message(Get(["50d958904e0ab7bac04cbc7f81e27d14143306ba2ad04f3770bf36dfa388e059"])) # # network.client.add_message({ "id": 6, "method":"blockchain.address.subscribe", "params": ["1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm"] }) # # network.client.add_subscribe(numblocks_subscribe([]), callback=prt1, subscribe=prt2) # do not have id # network.client.add_subscribe(headers_subscribe([]), callback=prt1, subscribe=prt2) # do not have id # # BlockChain().init_header() # SimpleWallet('1ZhouQKMethPQLYaQYcSsqqMNCgbNTYVm').init() # network.init_header(BlockChain().init_header_callback) # network.client.add_message(GetChunk([0,]), Block().connect_chunk2) # print Block().headers[200 * 2016] network.add_message(GetHistory(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(GetMempool(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(GetBalance(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) # network.client.add_message(GetProof(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) # not implemented network.add_message(Listunspent(['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) network.add_message(address_subscribe( ['mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj'])) # 'mmXqJTLjjyD6Xp2tJ7syCeZTcwvRjcojLz' hot_wallet = SimpleWallet(WalletConfig(store_path='wallet.json')) # wallet.add_address('mzSwHcXhWF8bgLtxF7NXE8FF1w8BZhQwSj') # wallet.add_key_store(SimpleKeyStore.create(SecretToASecret('\x20\x12\x10\x09' + '\x09'*28, True), None)) hot_wallet.sync() outputs = [(TYPE_ADDRESS, 'mkp8FGgySzhh5mmmHDcxRxmeS3X5fXm68i', 100000)] tx = hot_wallet.make_unsigned_transaction(hot_wallet.get_utxo(), outputs, {}) hot_wallet.sign_transaction(tx, None)
def setUp(self): super(HowToUseChain, self).setUp() self.manager = NetWorkManager() self.manager.start()
from electrumq.UI import controller from electrumq.UI.controller import EQApplication, EQMainWindow from electrumq.db.sqlite import init from electrumq.net.manager import NetWorkManager from electrumq.wallet import WalletConfig from electrumq.wallet.single import SimpleWallet from electrumq.wallet import EVENT_QUEUE __author__ = 'zhouqi' if __name__ == '__main__': try: app = EQApplication(sys.argv) main = EQMainWindow() main.raise_() main.show() main.activateWindow() signal.signal(signal.SIGTERM, lambda sig, frame: app.quit()) signal.signal(signal.SIGINT, lambda sig, frame: app.quit()) app.exec_() except (KeyboardInterrupt, SystemExit): app.exit() except Exception as ex: print ex traceback.print_exc() finally: NetWorkManager().quit() sys.exit()
def broadcast(self, tx): # todo: handle broadcast failed print Broadcast([str(tx)]) NetWorkManager().add_message(Broadcast([str(tx)]))
def init_header(self): NetWorkManager().init_header(self.init_header_callback)