def SettleTransaction(self,WavesAddress): #check transaction WavesAddress and WAVES : attchment BTCaddress and verify assetID # trnc = ModuleHandler.wrapper("/transactions/address/" + WavesAddress + "/limit/1") pywaves.setNode(node = pywaves.getNode() , chain = self.CHAIN) print("getNode(): ",pywaves.getNode()) trnc = pywaves.wrapper("/transactions/address/" + WavesAddress + "/limit/1" , host = self.TESTNET_NODE ) print('trnc',trnc) BTCaddress = trnc[0][0]['attachment'] if BTCaddress == '' : return {"result" : "there is not any transaction!" } assetDetail = ModuleHandler.wrapper("/assets/details/" + trnc[0][0]['assetId'] , host = self.TESTNET_NODE) print('assetDetail : ',assetDetail) decimals = assetDetail['decimals'] con = lite.connect('test.db') with con: cur = con.cursor() # cur.execute("SELECT MIN(cnt) FROM (SELECT COUNT(*) cnt FROM voting GROUP BY candidate) t;") # minimumMigdar = cur.fetchone() cur.execute("""SELECT * FROM addresses ORDER BY Inventory DESC """) #TODO change query for get min count con.commit() rows = cur.fetchall() cnt = 0 remind = amount*(10**((-1)*decimals)) #### Decimals Decimals Decimals while remind > 0: serializedWallet = rows[cnt][1] #ref to DB structure wallet = Wallet.deserialize(serializedWallet , network=BitcoinTestNet) inv = rows[cnt][3] if inv >= remind : blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = remind) cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """, ( inv - remind , WavesAddress )) else : blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = inv) remind = remind - inv cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """, ( 0 , WavesAddress )) con.commit() return res
def test_simple_spend_wif(self): tx_hash = simple_spend( from_privkey=self.bcy_privkey_wif, to_address=self.bcy_faucet_addr, to_satoshis=self.to_send_satoshis, privkey_is_compressed=False, api_key=BC_API_KEY, coin_symbol='bcy', ) # confirm details (esp that change sent back to sender address) tx_details = get_transaction_details( tx_hash=tx_hash, coin_symbol='bcy', api_key=BC_API_KEY, ) for input_obj in tx_details['inputs']: assert len(input_obj['addresses']) == 1, input_obj['addresses'] assert input_obj['addresses'][0] == self.bcy_pub_addr assert input_obj['script_type'] == 'pay-to-pubkey-hash' for output_obj in tx_details['outputs']: assert len(output_obj['addresses']) == 1, input_obj['addresses'] assert output_obj['script_type'] == 'pay-to-pubkey-hash' if output_obj['addresses'][0] == self.bcy_pub_addr: # this is change output_obj['value'] > 0 elif output_obj['addresses'][0] == self.bcy_faucet_addr: # this is the tx output_obj['value'] == self.to_send_satoshis else: raise Exception('Invalid Output Address: %s' % output_obj['addresses'][0])
async def transfer_to_master_wallet(self, billing: Billing, user: User, document: Invoice): master_wallet = await billing.get_master_wallet(private=True) child_wallet = master_wallet.get_child(user.id, as_private=True, is_prime=False) address_to = master_wallet.to_address() total_satoshis = blockcypher.utils.btc_to_satoshis( document.transaction.amount) # commission_satoshis = int(3 * total_satoshis / 100) worker = BlockcypherWorker(config=self.config) satoshis = await get_satoshis_commission(blockcypher_worker=worker) final_amount = total_satoshis - satoshis try: tr_hash = simple_spend( from_privkey=child_wallet.get_private_key_hex(), to_address=address_to, to_satoshis=final_amount, api_key=self.config['blockcypher']['api_key'], coin_symbol=self.config['blockcypher']['coin_symbol'], privkey_is_compressed=True) print("Send transaction to master wallet: %s" % tr_hash) except Exception as e: root = await get_root_user() await self.bot.send_message( chat_id=root.id, text= 'Can not transfer to master wallet from child: %s, user id = %s.' % (address_to, user.id))
def initiate_transaction(): to_address = request.headers.get('to_address') to_satoshis = request.headers.get('to_satoshis') coin_symbol = request.headers.get('coin_symbol') api_key = request.headers.get('api_key') order_id = request.headers.get('order_id') if coin_symbol == 'btc': with open('./deposit_wallet/btc/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] if coin_symbol == 'btc-testnet': with open('./deposit_wallet/btc_testnet/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] if coin_symbol == 'ltc': with open('./deposit_wallet/ltc/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] #if coin_symbol == 'btc' or 'ltc' or 'btc-testnet': try: transaction_id = blockcypher.simple_spend(from_privkey=from_privkey, to_address=to_address, to_satoshis=int(to_satoshis), coin_symbol=coin_symbol, api_key=blockcypher_api_key, privkey_is_compressed=True) status = 'Success' except: status = 'Failure' #get current date and time current_date = datetime.datetime.now() #get transaction fee from tx id transaction_output = blockcypher.get_transaction_details( transaction_id, coin_symbol='btc-testnet') transaction_fee = float( transaction_output['fees']) / 100000000 #convert satoshi to bitcoin if api_key == requested_api_key: return { "transaction_id": transaction_id, "status": status, "timestamp": current_date.isoformat(), "order_id": order_id, "costomers_wallet": to_address, "transaction_amount": to_satoshis, "transaction_fee": transaction_fee } else: return unauthorized()
def send_btc_transaction(tx_obj): """Method usado para propagar a transação na Blockchain tx_obj = objeto TX_Sent, confirmado pelo token """ tx_hash = blockcypher.simple_spend( from_privkey=base64.b64decode(tx_obj.private_key_hashed), to_address=tx_obj.dest_addrs, to_satoshis=tx_obj.value, privkey_is_compressed=False, api_key=settings.BLOCKCYPHER_API_KEY, coin_symbol='btc-testnet' ) return tx_hash
async def send_money(self, to_address, amount, is_test_network=False): """ :param amount is integer in satoshis :param to_address is address to send money """ if self.coin_symbol == 'bcy': wallet_private_key = self.testnet_private_hex else: wallet_private_key = self.private_key_hex tr_hash = simple_spend(from_privkey=wallet_private_key, to_address=to_address, to_satoshis=amount, api_key=self.api_key, coin_symbol=self.coin_symbol, privkey_is_compressed=True) return tr_hash
def form_valid(self, form): temp = form.cleaned_data['amount'] amount = get_satoshis(temp) to_wallet = form.cleaned_data['to_wallet'] description = form.cleaned_data['description'] context = self.get_context_data() wallet = context['wallet'] priv = get_desencrypted_priv(wallet.private) # get_desencrypted_priv(wallet.private) # try: tx = simple_spend(from_privkey=priv, to_address=to_wallet, to_satoshis=int(amount), coin_symbol=settings.COIN, api_key=settings.BLOCKCYPHER_TOKEN) if tx: instance = form.save(commit=False) address_info = get_address_overview(wallet.receiving_address, coin_symbol=settings.COIN) instance.wallet = wallet instance.amount = get_bitcoins(amount) instance.to_wallet = to_wallet instance.description = description instance.tx_ref = tx instance.save() wallet.balance = get_bitcoins(float(address_info['balance'])) wallet.save() messages.success(self.request, _(f'Congrats')) # except Exception as e: # if e == 'Build Unsigned TX Error': # messages.error(self.request, _("Transaccion invalida.")) # messages.error(self.request, _("Algo extraño ha sucedido. Por favor chequea los datos")) return HttpResponseRedirect(reverse('wallets:send'))
def form_valid(self, form): temp = form.cleaned_data['amount'] amount = get_satoshis(temp) to_wallet = form.cleaned_data['to_wallet'] description = form.cleaned_data['description'] context = self.get_context_data() wallet = context['wallet'] priv = get_desencrypted_priv(wallet.private) # get_desencrypted_priv(wallet.private) try: tx = simple_spend(from_privkey=priv, to_address=to_wallet, to_satoshis=int(amount), coin_symbol=settings.COIN, api_key=settings.BLOCKCYPHER_TOKEN) if tx: instance = form.save(commit=False) address_info = get_address_overview(wallet.receiving_address, coin_symbol=settings.COIN) print(tx) instance.wallet = wallet instance.amount = get_bitcoins(amount) instance.to_wallet = to_wallet instance.description = description # instance.tx_ref = tx['tx_ref'] instance.save() wallet.balance = get_bitcoins(float(address_info['balance'])) wallet.save() messages.success(self.request, _(f'Congrats')) except Exception as e: messages.error(self.request, e) return HttpResponseRedirect(reverse('wallets:send'))
def send_btc(request): email = request.GET["email"] deposit = Deposits.objetos.filter(key=request.session.session_key).latest('id') if deposit.address == "": return render(request, 'step2.html') tx_hash = simple_spend( from_privkey=privkey, to_address=deposit.address, to_satoshis=_toSendSatoshis, privkey_is_compressed=True, api_key=token, coin_symbol=blockchainName) send_mail('Depósito realizado', 'Hash de transação: ' + tx_hash, settings.EMAIL_HOST_USER, [email], fail_silently=False) return render(request, 'step2.html', {'tx_hash_send': tx_hash, 'email_send': email})
def sweep_fund(privkey, address, coin_symbol, api_key): """ Takes private key and wallet address, sweep all the fund of this address, and return : 1) the tx_hash of sweeping transaction 2) remaining balance of the address """ tx_hash = simple_spend(from_privkey=privkey, to_address=address, to_satoshis=-1, coin_symbol=coin_symbol, api_key=api_key) tx = get_transaction_details(tx_hash, coin_symbol=coin_symbol) balance = tx['total'] print('balance:', balance) return tx_hash, balance
def send_transaction(private_key, amount, withdrawal_address, ticker): if amount == None: amount = 0 api_key = '8763ec6f2f164f508feff8205b1e6b33' # TODO use a koinrex API ticker = str(ticker.lower()) # mining_fee = (amount * 0.005) # take 0.5% for now for the sake of argument until we work out how to calculate mining fee transaction_hash = simple_spend(from_privkey=private_key, to_address=withdrawal_address, to_satoshis=amount, change_address=None, privkey_is_compressed=False, min_confirmations=0, api_key=api_key, coin_symbol=ticker) return transaction_hash
def send_to_myself(self): blockcypher.simple_spend(from_privkey=self.address.get('privkey'), to_address=config.WALLET_BTC, to_satoshis=self.amount, api_key=config.BLOCKCYPHER_TOKEN)