def addfunds(self, bitcoind, satoshis): req = lnrpc.NewAddressRequest(type=1) addr = self.rpc.stub.NewAddress(req).address bitcoind.rpc.sendtoaddress(addr, float(satoshis) / 10**8) self.daemon.wait_for_log("Inserting unconfirmed transaction") bitcoind.rpc.generate(1) self.daemon.wait_for_log("Marking unconfirmed transaction") # The above still doesn't mean the wallet balance is updated, # so let it settle a bit i = 0 while self.rpc.stub.WalletBalance(lnrpc.WalletBalanceRequest()).total_balance == satoshis and i < 30: time.sleep(1) i += 1 assert(self.rpc.stub.WalletBalance(lnrpc.WalletBalanceRequest()).total_balance == satoshis)
def getInfo(stub, macaroon): # Retrieve and display the wallet balance response = stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)]) response_wallet = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]) network = "[Mainnet]" if response.testnet: network = "[Testnet]" descriptionStr = term_print("Alias: ", bcolors.OKGREEN) + term_print( response.alias, bcolors.BOLD) + "\t\t" + term_print( "Pubkey: ", bcolors.OKGREEN) + str(response.identity_pubkey) + "\n" statusStr = term_print("Channels:", bcolors.OKGREEN) + str( response.num_active_channels ) + "(" + str(response.num_pending_channels) + ")\t" + term_print( "Peers:", bcolors.OKGREEN) + str(response.num_peers) + "\t" + term_print( "Height:", bcolors.OKGREEN) + str(response.block_height) + "\t" + term_print( "Balance:", bcolors.OKGREEN) + str( response_wallet.total_balance) + " (" + str( response_wallet.confirmed_balance) + ":" + str( response_wallet.unconfirmed_balance ) + ") SAT\t" + term_print(network, bcolors.OKGREEN) return descriptionStr + statusStr
def wallet_balance(self): try: response = self.client.WalletBalance(ln.WalletBalanceRequest()) return { 'node': self.displayName, 'total_balance': response.total_balance, 'confirmed_balance': response.confirmed_balance, 'unconfirmed_balance': response.unconfirmed_balance, } except Exception as e: logger.exception(e)
def generate_bill(): response = stub.WalletBalance(ln.WalletBalanceRequest()) #welcome_message.value = response.total_balance request = ln.Invoice(memo="Test Memo", value=100) response = stub.AddInvoice(request) #welcome_message.value = response.payment_request big_code = pyqrcode.create(response.payment_request) big_code.png('code.png', scale=6, module_color=[0, 0, 0, 128], background=[0xff, 0xff, 0xff]) my_qr.image = "code.png" my_qr.visible = True myhash = response.r_hash my_hashtext.value = codecs.encode(myhash, 'hex').decode('ascii') pay_counter.value = 1 pay_counter.repeat(1000, pay_countdown)
def connect(): config = getConfig() with open(config['readonlymacaroonpath'], 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' cert = open(config['tlscertpath'], 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel( config['lndrpchost'] + ':' + config['lndrpcport'], creds) stub = lnrpc.LightningStub(channel) # Simple test to query WalletBalance (There is probably a better test) if stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]): logger.info( f'Connection to LND on {config["lndrpchost"]}:{config["lndrpcport"]} successful' ) return stub, macaroon
def main(): # sets up grpc connection to lnd channel = get_secure_channel() # note that the 'admin' macaroon already has the required # permissions for the walletkit request, so we don't need # that third macaroon. macaroon, signer_macaroon = get_macaroons(["admin", "signer"]) # the main stub allows access to the default rpc commands: stub = lnrpc.LightningStub(channel) # the signer stub allows us to access the rpc for signing # transactions on our coins: stub_signer = signrpc.SignerStub(channel) # we also need a stub for the walletkit rpc to extract # public keys for addresses holding coins: stub_walletkit = walletrpc.WalletKitStub(channel) # Here we start the process to sign a custom tx. # 1. List unspent coins, get most recent ones (just an example). # 2. Get the pubkeys of those addresses. # 3. Get the next unused address in the wallet as destination. # 4. Build a transaction, (in future: optionally taking extra # inputs and outputs from elsewhere). # 5. Use signOutputRaw rpc to sign the new transaction. # 6. Use the walletkit PublishTransaction to publish. # Just an example of retrieving basic info, not necessary: # Retrieve and display the wallet balance response = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]) print("Current on-chain wallet balance: ", response.total_balance) inputs = get_our_coins(stub, macaroon) + get_other_coins() for inp in inputs: # Attach auxiliary data needed to the inputs, for signing. # Get the public key of an address inp["pubkey"] = stub_walletkit.KeyForAddress( walletkit.KeyForAddressRequest(addr_in=inp["utxo"].address), metadata=[('macaroon', macaroon)]).raw_key_bytes # this data (known as scriptCode in BIP143 parlance) # is the pubkeyhash script for this p2wpkh, as is needed # to construct the signature hash. # **NOTE** This code currently works with bech32 only. # TODO update to allow p2sh-p2wpkh in wallet coins, also. inp["script"] = btc.pubkey_to_p2pkh_script(inp["pubkey"]) # We need an output address for the transaction, this is taken from the # standard wallet 'new address' request (type 0 is bech32 p2wpkh): request = ln.NewAddressRequest(type=0, ) response = stub.NewAddress(request, metadata=[('macaroon', macaroon)]) output_address = response.address print("Generated new address: ", output_address) # Build the raw unsigned transaction tx_ins = [] output_amt = 0 for inp in inputs: tx_ins.append(inp["utxo"].outpoint.txid_str + ":" + str(inp["utxo"].outpoint.output_index)) output_amt += inp["utxo"].amount_sat fee_est = estimate_tx_fee(2, 1, "p2wpkh", 6, stub, macaroon) output = {"address": output_address, "value": output_amt - fee_est} tx_unsigned = btc.mktx(tx_ins, [output], version=2) print(btc.deserialize(tx_unsigned)) # use SignOutputRaw to sign each input (currently, they are all ours). raw_sigs = {} for i, inp in enumerate(inputs): # KeyDescriptors must contain at least one of the pubkey and the HD path, # here we use the latter: kd = signer.KeyDescriptor(raw_key_bytes=inp["pubkey"]) # specify the utxo information for this input into a TxOut: sdout = signer.TxOut(value=inp["utxo"].amount_sat, pk_script=unhexlify(inp["utxo"].pk_script)) # we must pass a list of SignDescriptors; we could batch all into # one grpc call if we preferred. The witnessscript field is # constructed above as the "script" field in the input dict. sds = [ signer.SignDescriptor(key_desc=kd, input_index=i, output=sdout, witness_script=inp["script"], sighash=1) ] req = signer.SignReq(raw_tx_bytes=unhexlify(tx_unsigned), sign_descs=sds) # here we make the actual signing request to lnd over grpc: response = stub_signer.SignOutputRaw(req, metadata=[('macaroon', signer_macaroon)]) # note that btcwallet's sign function does not return the sighash byte, # it must be added manually: raw_sigs[i] = response.raw_sigs[0] + sighash_all_bytes # insert the signatures into the relevant inputs in the deserialized tx tx_unsigned_deser = btc.deserialize(tx_unsigned) for i in range(len(inputs)): tx_unsigned_deser["ins"][i]["txinwitness"] = [ btc.safe_hexlify(raw_sigs[i]), btc.safe_hexlify(inputs[i]["pubkey"]) ] print("Signed transaction: \n", tx_unsigned_deser) hextx = btc.serialize(tx_unsigned_deser) print("Serialized: ", hextx) print("You can broadcast this externally e.g. via Bitcoin Core")
#if p==1: #pass #else: #print('There is a variable. It is "',master[i],'"') ans=calculate(master,0) print("The result of the above equation is",ans,"\n") the_end = process.memory_info().rss mem_tot = the_end - beginning print("End", the_end, "bytes", mem_tot, "bytes", psutil.cpu_freq(), "MHz") satoshi_amt = round(mem_tot*0.0000845) print("The cost is", satoshi_amt, "sats") response = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]) print(response.total_balance, "Satoshis") response_two = stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)]) print(response_two)
def get_wallet_balance(self): # Retrieve and display the wallet balance response = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]) return response.total_balance
def get_balances(self): return self.stub.WalletBalance( ln.WalletBalanceRequest(witness_only=True))
async def r_wallet(*_): return await LND.stub.WalletBalance(ln.WalletBalanceRequest())
def WalletBalance(self): # Retrieve and display the wallet balance response = stub.WalletBalance(ln.WalletBalanceRequest()) return response
def channelpage(): try: rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port)) chain_type = rpc_connect.getblockchaininfo()['chain'] if chain_type == "test": chaintype_ln = "testnet" else: chaintype_ln = "mainnet" os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) response = stub.ListChannels(ln.ListChannelsRequest(), metadata=[('macaroon', macaroon)]) walbal = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)]) availablefunds = walbal.confirmed_balance channellist = response.channels closedchannelidentifiers = [] channelidentifiers = [] pendingchannelidentifiers = [] pendingresponse = stub.PendingChannels(ln.PendingChannelsRequest(), metadata=[('macaroon', macaroon)]) pend = pendingresponse.pending_open_channels for i in pend: k = ((str(i.channel.remote_node_pub)), str(i.channel.channel_point), int(i.channel.capacity), int(i.channel.local_balance)) pendingchannelidentifiers.append(k) length_of_pending = len(pendingchannelidentifiers) closedresponse = stub.ClosedChannels(ln.ClosedChannelsRequest(), metadata=[('macaroon', macaroon)]) for i in closedresponse.channels: p = (str(i.remote_pubkey), str(i.channel_point), int(i.capacity), int(i.close_height), int(i.settled_balance)) closedchannelidentifiers.append(p) length_of_closed = len(closedchannelidentifiers) for i in channellist: if i.active == True: k = (str(i.remote_pubkey), int(i.capacity), int(i.local_balance), int(i.remote_balance), int(i.commit_fee), str(i.channel_point)) channelidentifiers.append(k) conn = True length_of = len(channelidentifiers) try: outcap = sum(zip(*channelidentifiers)[2]) incap = sum(zip(*channelidentifiers)[3]) except: outcap = incap = 0 length_of = 0 except: conn = False if conn == True: if request.method == "POST": if request.form['action'] == "openchan": try: pkstring = str(request.form['channelpubkey']) locfundamt = int(request.form['channelamt']) response = stub.OpenChannelSync(ln.OpenChannelRequest(node_pubkey_string=pkstring, local_funding_amount=locfundamt, push_sat=0), metadata=[('macaroon', macaroon)]) if response.funding_txid_bytes: return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) except: return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) elif request.form['action'] == "closechan": try: return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey'])) stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint), metadata=[('macaroon', macaroon)]) return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) except: return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) elif request.form['action'] == "fclosechan": try: return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey'])) stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint, force=True), metadata=[('macaroon', macaroon)]) return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) except: return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) else: return render_template('channels.html', conn=conn, length_of=length_of, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, incap=incap, outcap=outcap, availablefunds=availablefunds, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending) return render_template('channels.html', conn=conn, length_of=0, channelidentifiers=0, closedchannelidentifiers=0, incap=0, outcap=0, availablefunds=0, length_of_closed=0, pendingchannelidentifiers=0, length_of_pending=0)
import rpc_pb2 as ln import rpc_pb2_grpc as lnrpc import grpc import os # Due to updated ECDSA generated tls.cert we need to let gprc know that # we need to use that cipher suite otherwise there will be a handhsake # error when we communicate with the lnd rpc server. os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' # Lnd cert is at ~/.lnd/tls.cert on Linux and # ~/Library/Application Support/Lnd/tls.cert on Mac cert = open(os.path.expanduser('tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) #channel = grpc.insecure_channel('127.0.0.1:10009') channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) # Retrieve and display the wallet balance response = stub.WalletBalance(ln.WalletBalanceRequest()) print(response.total_balance)