def verifyOther(self, txId): otherProxy = authproxy.AuthServiceProxy(self.config['other']['node']) try: time.sleep(60) verified = otherProxy.gettransaction(txId) block = otherProxy.getblock(verified['blockhash']) if block['height'] > 0: values = ("Other", txId, block['height']) cursor = self.dbCon.cursor() cursor.execute('INSERT INTO verified ("chain", "tx", "block") VALUES (?, ?, ?)', values) self.dbCon.commit() print('tx to other verified!') else: values = ("Other", txId, 0) cursor = self.dbCon.cursor() cursor.execute('INSERT INTO verified ("chain", "tx", "block") VALUES (?, ?, ?)', values) self.dbCon.commit() print('tx to other not verified!') except: values = ("Other", txId, 0) cursor = self.dbCon.cursor() cursor.execute('INSERT INTO verified ("chain", "tx", "block") VALUES (?, ?, ?)', values) self.dbCon.commit() print('tx to other not verified!')
def __init__(self, config: wg.GatewayConfigFile) -> None: print(dir(config)) super(BitcoinGateway, self).__init__(config) self.proxy = wg.ProxyGuard(authproxy.AuthServiceProxy(config.coin_node), max_parallel_access=1) self.address_factory = lib.BitcoinAddressFactory(self.proxy) self.chain_query_service = lib.BitcoinChainQueryService(self.proxy) self.transaction_service = lib.BitcoinTransactionService(self.proxy, self.chain_query_service) self.integer_converter_service = lib.BitcoinIntegerConverterService(config.coin_factor, config.coin_precision) self.address_validation_service = lib.BitcoinAddressValidationService(self.proxy) self.gateway = wg.Gateway( coin_address_factory = self.address_factory, coin_chain_query_service = self.chain_query_service, coin_transaction_service = self.transaction_service, gateway_waves_address_secret = config.gateway_waves_address_secret, gateway_coin_address_secret = config.gateway_coin_address_secret, mongo_database = self.mongo_client.get_database(config.mongo_database), managed_loggers = ["BitcoinRPC"], logging_handlers = self.logging_handlers, custom_currency_name = config.coin_name, coin_integer_converter_service = self.integer_converter_service, asset_integer_converter_service = wg.IntegerConverterService(), waves_chain = config.waves_chain, waves_asset_id = config.waves_asset_id, waves_node = config.waves_node, gateway_owner_address = config.gateway_owner_address, fee_service = self.fee_service, only_one_transaction_receiver = False, coin_transaction_web_link = config.transaction_explorer_link, coin_address_web_link = config.address_explorer_link, host = config.gateway_host, port = config.gateway_port, coin_address_validation_service = self.address_validation_service, coin_last_block_distance=5)
async def createTunnel(targetAddress): pwTN = PyCWaves.PyCWaves() pwTN.setNode(node=config['tn']['node'], chain=config['tn']['network'], chain_id='L') if not pwTN.validateAddress(targetAddress): return {'successful': '0'} dbCon = sqlite.connect('gateway.db') instance = authproxy.AuthServiceProxy(config['other']['node']) sourceAddress = instance.getnewaddress() targetAddress = re.sub('[\W_]+', '', targetAddress) values = (sourceAddress, targetAddress) result = dbCon.cursor().execute( 'SELECT sourceAddress FROM tunnel WHERE targetAddress = ?', (targetAddress, )).fetchall() if len(result) == 0: dbCon.cursor().execute( 'INSERT INTO TUNNEL ("sourceAddress", "targetAddress") VALUES (?, ?)', values) dbCon.commit() return {'successful': 1, 'address': sourceAddress} else: return {'successful': 2, 'address': result[0][0]}
def get_ltcd_op_return_hexes(queue, address, txid, results, key, conf, testnet=False): try: #print("ltcd start") url = conf['full_url'] rpc_conn = proxy.AuthServiceProxy(url) all_relevant_txs = rpc_conn.searchrawtransactions( address, 1, 0, 10000000, 0, True) data_before_issuance = [] data_after_issuance = [] found_issuance = False for tx in all_relevant_txs: # only consider txs that have at least one confirmation # note that tx will be None if confirmations is 0 if not tx.get('confirmations', 0): continue # tx hash needs to be identical with txid from proof and that is the # actual issuance if tx['txid'] == txid: found_issuance = True outs = tx['vout'] for o in outs: # get op_return_hex, if any, and exit if o['scriptPubKey']['hex'].startswith('6a'): data = get_op_return_data_from_script( o['scriptPubKey']['hex']) if not found_issuance: # to check certs revocations we can iterate this list in reverse! data_after_issuance.append(data) else: # current issuance is actually the first element of this list! # to check for addr revocations we can iterate this list as is data_before_issuance.append(data) if not found_issuance: raise ValueError( "Txid for issuance not found in address' transactions") results[key]['before'] = data_before_issuance results[key]['after'] = data_after_issuance results[key]['success'] = True #print("ltcd end") except Exception as e: log.error("Ltcd Thread:" + sys.exc_info().__str__()) # add to queue to be visible to parent queue.put(["Ltcd Thread:", sys.exc_info()])
def get_otherBalance(): # try: # balance = otc.currentBalance() # except: # balance = 0 myProxy = authproxy.AuthServiceProxy(config['other']['node']) balance = myProxy.z_getbalance(config['other']['gatewayAddress']) return balance
def currentBlock(self): try: result = self.myProxy.getblock(self.myProxy.getbestblockhash()) except: self.myProxy = authproxy.AuthServiceProxy( self.config['other']['node']) result = self.myProxy.getblock(self.myProxy.getbestblockhash()) return result['height']
def main(args): BITCOIN_RPC_URL = 'http://%s:%s@%s:%s/' % (args.username, args.password, args.host, args.port) bitcoin = authproxy.AuthServiceProxy(BITCOIN_RPC_URL) msc_msg = MastercoinMultisigMessage(None, None, None) data = msc_msg.broadcast(bitcoin) return addresses = {} balances = {} results = bitcoin.listreceivedbyaddress() print "Your addresses, and balance (in BTC):" index = -1 for result in results: index += 1 addr, amount = result['address'], result['amount'] balances[addr] = amount addresses[str(index)] = addr print "\t%s) %s\t%s BTC" % (index, addr, amount) if index == -1: print "You don't have any funds in any address. Please fund your Mastercoin address and retry." return print "" print "Select address to send from the list (%s-%s) and press ENTER. (default = 0)" % ( 0, index) selected_id = raw_input() or "0" sender = addresses.get(selected_id) if not sender: print "Error selecting address. Now exiting." return print "Please enter a recipient bitcoin address and press ENTER." recipient = raw_input() or "mkHz6UY7AjURz8wK4dYBzcGHaKmmSAPA3d" recover_bytes_from_address(recipient) # checking if address is valid print "Which currency do you wish to send? (MasterCoin = 1, TestCoin = 2) (default = TestCoin)" currency_id = int(raw_input() or CURR_ID_TESTCOIN) if currency_id not in CURRENCIES: print "Error selecting currency. Now exiting." return print "How many %ss do you wish to send? (default = 1)" % ( CURRENCY_NAME[currency_id]) ammount = long(float(raw_input() or 1) * DACOINMINISTERS_IN_MSC) msc_msg = MastercoinAddressMessage.simple_send(sender, recipient, currency_id, ammount) data = msc_msg.broadcast(bitcoin) print "Mastercoin message broadcasted. Info:" print data
def getCurrentBlock(self): try: latestBlock = self.myProxy.getblock( self.myProxy.getbestblockhash()) except: self.myProxy = authproxy.AuthServiceProxy( self.config['other']['node']) latestBlock = self.myProxy.getblock( self.myProxy.getbestblockhash()) return latestBlock['height']
def currentBalance(self): try: balance = self.myProxy.z_getbalance( self.config['other']['gatewayAddress']) except: self.myProxy = authproxy.AuthServiceProxy( self.config['other']['node']) balance = self.myProxy.z_getbalance( self.config['other']['gatewayAddress']) return balance
def initialisedb(config): #get current TN block: tnlatestBlock = requests.get(config['tn']['node'] + '/blocks/height').json()['height'] - 1 #get current ETH block: if config['other']['node'].startswith('http'): instance = authproxy.AuthServiceProxy(config['other']['node']) else: instance = authproxy.AuthServiceProxy() latestBlock = instance.getblock(instance.getbestblockhash()) otherlatestBlock = latestBlock['height'] con = sqlite.connect('gateway.db') cursor = con.cursor() cursor.execute( 'INSERT INTO heights ("chain", "height") VALUES ("Other", ' + str(otherlatestBlock) + ')') cursor.execute('INSERT INTO heights ("chain", "height") VALUES ("TN", ' + str(tnlatestBlock) + ')') con.commit() con.close()
def __init__(self, config, db=None): self.config = config if db == None: if self.config['main']['use-pg']: self.db = dbPGCalls(config) else: self.db = dbCalls(config) else: self.db = db self.myProxy = authproxy.AuthServiceProxy(self.config['other']['node']) self.lastScannedBlock = self.db.lastScannedBlock("Other")
def __init__(self, config: wg.GatewayConfigFile, kore_round_precision: int = DEFAULT_KORE_ROUND_PRECISION, kore_factor: int = DEFAULT_KORE_FACTOR, transaction_web_link: str = DEFAULT_TRANSACTION_WEB_LINK, address_web_link: str = DEFAULT_ADDRESS_WEB_LINK) -> None: kore_proxy = wg.ProxyGuard(authproxy.AuthServiceProxy( config.coin_node), max_parallel_access=1) kore_address_factory = lib.KoreAddressFactory(kore_proxy) kore_chain_query_service = lib.KoreChainQueryService(kore_proxy) kore_transaction_service = lib.KoreTransactionService( kore_proxy, kore_chain_query_service) kore_integer_converter_service = lib.KoreIntegerConverterService( kore_factor, kore_round_precision) kore_address_validation_service = lib.KoreAddressValidationService( kore_proxy) mongo_client = pymongo.MongoClient(host=config.mongo_host, port=config.mongo_port) fee_service = wg.ConstantFeeServiceImpl(config.gateway_fee, config.coin_fee) logging_handlers = self._init_logging_handlers(config.environment) self._gateway = wg.Gateway( coin_address_factory=kore_address_factory, coin_chain_query_service=kore_chain_query_service, coin_transaction_service=kore_transaction_service, gateway_waves_address_secret=config.gateway_waves_address_secret, gateway_coin_address_secret=config.gateway_coin_address_secret, mongo_database=mongo_client.get_database(config.mongo_database), managed_loggers=["BitcoinRPC"], logging_handlers=logging_handlers, custom_currency_name=KoreGateway.WEB_CURRENCY_NAME, coin_integer_converter_service=kore_integer_converter_service, asset_integer_converter_service=wg.IntegerConverterService(), waves_chain=config.waves_chain, waves_asset_id=KoreGateway.WAVES_ASSET_ID, waves_node=config.waves_node, gateway_owner_address=config.gateway_owner_address, fee_service=fee_service, only_one_transaction_receiver=False, coin_transaction_web_link=transaction_web_link, coin_address_web_link=address_web_link, host=config.gateway_host, port=config.gateway_port, coin_address_validation_service=kore_address_validation_service, coin_last_block_distance=5)
def __init__(self, config): self.config = config self.dbCon = sqlite.connect('gateway.db') self.myProxy = authproxy.AuthServiceProxy(self.config['other']['node']) self.pwTN = PyCWaves.PyCWaves() self.pwTN.setNode(node=self.config['tn']['node'], chain=self.config['tn']['network'], chain_id='L') self.pwTN.THROW_EXCEPTION_ON_ERROR = True seed = os.getenv(self.config['tn']['seedenvname'], self.config['tn']['gatewaySeed']) self.tnAddress = self.pwTN.Address(seed=seed) self.tnAsset = self.pwTN.Asset(self.config['tn']['assetId']) self.verifier = verifier(config) cursor = self.dbCon.cursor() self.lastScannedBlock = cursor.execute( 'SELECT height FROM heights WHERE chain = "Other"').fetchall( )[0][0]
from bitcoinrpc import authproxy login_coin = 'test' password_coin = 'test' ip_coin = '127.0.0.1' port_coin = '11030' coin = authproxy.AuthServiceProxy("http://{}:{}@{}:{}".format( login_coin, password_coin, ip_coin, port_coin))
def __init__(self, url): self.bitcoind = authproxy.AuthServiceProxy(url) self.cur_height = None
def checkBlock(self, heightToCheck): #check content of the block for valid transactions block = requests.get(self.node + '/blocks/at/' + str(heightToCheck)).json() for transaction in block['transactions']: if self.checkTx(transaction): targetAddress = base58.b58decode( transaction['attachment']).decode() otherProxy = authproxy.AuthServiceProxy( self.config['other']['node']) valAddress = otherProxy.validateaddress(targetAddress) if not (valAddress['isvalid']): self.faultHandler(transaction, "txerror") else: amount = transaction['amount'] / pow( 10, self.config['tn']['decimals']) amount -= self.config['other']['fee'] if amount <= 0: self.faultHandler(transaction, "senderror", e='under minimum amount') else: try: passphrase = os.getenv( self.config['other']['passenvname'], self.config['other']['passphrase']) if len(passphrase) > 0: otherProxy.walletpassphrase(passphrase, 30) txId = otherProxy.sendtoaddress( targetAddress, amount) if len(passphrase) > 0: otherProxy.walletlock() if 'error' in txId: self.faultHandler(transaction, "senderror", e=txId) else: print("send tx: " + txId) cursor = self.dbCon.cursor() #amount /= pow(10, self.config['other']['decimals']) cursor.execute( 'INSERT INTO executed ("sourceAddress", "targetAddress", "tnTxId", "otherTxId", "amount", "amountFee") VALUES ("' + transaction['sender'] + '", "' + targetAddress + '", "' + transaction['id'] + '", "' + txId + '", "' + str(round(amount)) + '", "' + str(self.config['other']['fee']) + '")') self.dbCon.commit() print(self.config['main']['name'] + ' tokens withdrawn from tn!') except Exception as e: self.faultHandler(transaction, "txerror", e=e) self.verifier.verifyOther(txId)
def get_otherBalance(): otherProxy = authproxy.AuthServiceProxy(config['other']['node']) balance = otherProxy.getbalance() return int(round(balance))
def _get_rpc_connection(self): # XXX it seems that the connection is not kept alive. return authproxy.AuthServiceProxy( _FAIRCOIN_RPC_URL.format(os.environ.get('FAIRCOIN_RPC_USER'), os.environ.get('FAIRCOIN_RPC_PASSWORD')))