Example #1
0
	def __init__(self, network):

		self.__network = network

		if self.__network == "mainnet":
			self.rpc_interface = LightningRpc(expanduser("~")+"/.mainnet/lightning-rpc")


			self.rpc_interface.connect("02f6725f9c1c40333b67faea92fd211c183050f28df32cac3f9d69685fe9665432@104.198.32.198:9735")
			#self.rpc_interface.connect("030fe6f75d41d7112afee0f6f0e230095d9036abf19c7f88f416cc7b9ab9e9ef3e@203.206.164.188:9735")
			#self.rpc_interface.connect("03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e@52.15.79.245:9735")
			#self.rpc_interface.connect("03cb7983dc247f9f81a0fa2dfa3ce1c255365f7279c8dd143e086ca333df10e278@46.28.204.21:9735")
			#self.rpc_interface.connect("03e50492eab4107a773141bb419e107bda3de3d55652e6e1a41225f06a0bbf2d56@35.172.33.197:9735")

		else:
			self.rpc_interface = LightningRpc(expanduser("~")+"/.lightning/lightning-rpc")

			self.rpc_interface.connect("03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016@50.116.3.223:9734")
			#self.rpc_interface.connect("03782bb858e1ec9c0a4a5ac665ed658c97ced02e723eafc3c56137ab4e2e3caebf@52.8.119.71:9736")
			#self.rpc_interface.connect("02ec66fb12dd5d4943d63e7a1a35d063aec015e1c8b89cee6c9f2db3faf0f6687f@3.93.159.131:19735")
			#self.rpc_interface.connect("0218b92d19de937ef740154d20d3a6f37c44e6381ca72b95789295073664cfdd36@5.95.80.47:9735")

		print(type(self.rpc_interface.getinfo()))

		print(self.rpc_interface.listpeers())
Example #2
0
    def __init__(self):
        if LightningRpc is None:  # pragma: nocover
            raise ImportError(
                "The `pylightning` library must be installed to use `CLightningWallet`."
            )

        self.rpc = getenv("CLIGHTNING_RPC")
        self.ln = LightningRpc(self.rpc)

        # check description_hash support (could be provided by a plugin)
        self.supports_description_hash = False
        try:
            answer = self.ln.help("invoicewithdescriptionhash")
            if answer["help"][0]["command"].startswith(
                    "invoicewithdescriptionhash msatoshi label description_hash",
            ):
                self.supports_description_hash = True
        except:
            pass

        # check last payindex so we can listen from that point on
        self.last_pay_index = 0
        invoices = self.ln.listinvoices()
        for inv in invoices["invoices"][::-1]:
            if "pay_index" in inv:
                self.last_pay_index = inv["pay_index"]
                break
Example #3
0
    def get_node(self, legacy=True):
        node_id = self.next_id
        self.next_id += 1

        lightning_dir = os.path.join(TEST_DIR, self.func._testMethodName,
                                     "lightning-{}/".format(node_id))

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        port = 16330 + node_id
        if legacy:
            daemon = utils.LegacyLightningD(lightning_dir,
                                            bitcoind.bitcoin_dir,
                                            port=port)
            rpc = LegacyLightningRpc(socket_path, self.executor)
        else:
            daemon = utils.LightningD(lightning_dir,
                                      bitcoind.bitcoin_dir,
                                      port=port)
            rpc = LightningRpc(socket_path, self.executor)

        node = utils.LightningNode(daemon, rpc, bitcoind, self.executor)
        self.nodes.append(node)
        if VALGRIND:
            node.daemon.cmd_line = [
                'valgrind', '-q', '--error-exitcode=7',
                '--log-file={}/valgrind-errors'.format(
                    node.daemon.lightning_dir)
            ] + node.daemon.cmd_line

        node.daemon.start()
        # Cache `getinfo`, we'll be using it a lot
        node.info = node.rpc.getinfo()
        return node
Example #4
0
    def __init__(self):
        if LightningRpc is None:  # pragma: nocover
            raise ImportError(
                "The `pylightning` library must be installed to use `CLightningWallet`."
            )

        self.l1 = LightningRpc(getenv("CLIGHTNING_RPC"))
    def __init__(self, path, input=None, dont_store=None):
        self.__add_clogger()

        self.__rpc_interface = LightningRpc(path)
        self.__clogger.info("connection to RPC interface successful")

        G = None
        if input:
            try:
                self.__clogger.info("Try to load graph from file system at:" +
                                    input)
                with open(input, "rb") as infile:
                    G = pickle.load(infile)
                    self.__clogger.info(
                        "Successfully restored the lightning network graph from data/networkx_graph"
                    )
            except FileNotFoundError:
                self.__clogger.info(
                    "input file not found. Load the graph from the peers of the lightning network"
                )
                G = self.__download_graph()
        else:
            self.__clogger.info("no input specified download graph from peers")
            G = self.__download_graph()

        if dont_store is None:
            with open("lightning_networkx_graph.pickle", "wb") as outfile:
                pickle.dump(G, outfile, pickle.HIGHEST_PROTOCOL)

        Autopilot.__init__(self, G)
    def __init__(self,
                 lightning_dir,
                 lightning_port,
                 btc,
                 executor=None,
                 node_id=0):
        self.bitcoin = btc
        self.executor = executor
        self.daemon = LightningD(lightning_dir,
                                 self.bitcoin,
                                 port=lightning_port)
        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        self.invoice_count = 0
        self.logger = logging.getLogger(
            'lightning-node({})'.format(lightning_port))

        self.rpc = LightningRpc(socket_path, self.executor)

        orig_call = self.rpc._call

        def rpc_call(method, args):
            self.logger.debug("Calling {} with arguments {}".format(
                method, json.dumps(args, indent=4, sort_keys=True)))
            r = orig_call(method, args)
            self.logger.debug("Call returned {}".format(
                json.dumps(r, indent=4, sort_keys=True)))
            return r

        self.rpc._call = rpc_call
        self.myid = None
def init(options, configuration, plugin):
    global rpc, our_nodeid
    plugin.log("feereport init")
    path = join(configuration["lightning-dir"], configuration["rpc-file"])
    rpc = LightningRpc(path)
    info = rpc.getinfo()
    our_nodeid = info["id"]
    def get_node(self, disconnect=None):
        node_id = self.next_id
        self.next_id += 1

        lightning_dir = os.path.join(TEST_DIR, self.func._testMethodName,
                                     "lightning-{}/".format(node_id))

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        port = 16330 + node_id
        daemon = utils.LightningD(lightning_dir,
                                  bitcoind.bitcoin_dir,
                                  port=port)
        # If we have a disconnect string, dump it to a file for daemon.
        if disconnect:
            with open(os.path.join(lightning_dir, "dev_disconnect"), "w") as f:
                f.write("\n".join(disconnect))
            daemon.cmd_line.append("--dev-disconnect=dev_disconnect")
        rpc = LightningRpc(socket_path, self.executor)

        node = utils.LightningNode(daemon, rpc, bitcoind, self.executor)
        self.nodes.append(node)
        if VALGRIND:
            node.daemon.cmd_line = [
                'valgrind', '-q', '--trace-children=yes',
                '--trace-children-skip=*bitcoin-cli*', '--error-exitcode=7',
                '--log-file={}/valgrind-errors.%p'.format(
                    node.daemon.lightning_dir)
            ] + node.daemon.cmd_line

        node.daemon.start()
        # Cache `getinfo`, we'll be using it a lot
        node.info = node.rpc.getinfo()
        return node
def init(options, configuration, plugin):
    global rpc_interface

    # connect to the rpc interface
    rpc_interface = LightningRpc(
        join(configuration['lightning-dir'], configuration['rpc-file']))
    plugin.log("Plugin csvexportpays.py initialized")
Example #10
0
def index(request):
    # Bitcoin RPC Credentials (you need to change these)
    rpc_port = "8332"
    rpc_user = "******"
    rpc_password = "******"

    # LIGHTNING NETWORK

    # Lightning Network Socket file (you might need to change this)
    ln = LightningRpc("/home/pi/.lightning/lightning-rpc")

    try:
        l_info = ln.getinfo()
        l = LightningViewData(True)
        l.block_height = l_info["blockheight"]
        l.version = l_info["version"]
        l.version = l.version.replace("v", "")

        l_peers = ln.listpeers()
        l.peer_count = len(l_peers["peers"])

        l_funds = ln.listfunds()
        l.channel_count = len(l_funds["channels"])
    except:
        l = LightningViewData(False)

# BITCOIN

    b = BitcoinViewData(True)

    try:
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%s" %
                                          (rpc_user, rpc_password, rpc_port))
        b_conn_count = rpc_connection.getconnectioncount()
        if b_conn_count > 0:
            b.online = True
    except Exception as e:
        b.running = False

    if b.running == True:
        try:
            b.block_height = rpc_connection.getblockcount()
            b_network_info = rpc_connection.getnetworkinfo()
            b.peer_count = b_network_info["connections"]
            b.version = b_network_info["subversion"]
            b.version = b.version.replace("/", "")
            b.version = b.version.replace("Satoshi:", "")
        except Exception as e:
            b.message = str(e)


# RETURN VIEW DATA

    return render(request, 'dashboard/index.html', {
        'lightning': l,
        'bitcoin': b
    })
Example #11
0
    def get_node(self,
                 name=None,
                 disconnect=None,
                 options=None,
                 may_fail=False,
                 may_reconnect=False,
                 random_hsm=False,
                 feerates=(15000, 7500, 3750),
                 start=True,
                 log_all_io=False):
        with self.lock:
            node_id = self.next_id
            self.next_id += 1

        if not name:
            name = "node-{}".format(node_id)

        port = self.get_next_port()

        lightning_dir = os.path.join(self.directory,
                                     "lightning-{}/".format(node_id))

        if os.path.exists(lightning_dir):
            shutil.rmtree(lightning_dir)

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        daemon = LightningD(lightning_dir,
                            self.bitcoind,
                            port=port,
                            random_hsm=random_hsm,
                            node_id=node_id)
        # If we have a disconnect string, dump it to a file for daemon.
        if options is not None:
            daemon.opts.update(options)
        daemon.opts['alias'] = name

        rpc = LightningRpc(socket_path, self.executor)

        node = LightningNode(daemon,
                             rpc,
                             self.bitcoind,
                             self.executor,
                             may_fail=may_fail,
                             may_reconnect=may_reconnect)

        node.name = name
        self.nodes.append(node)
        if start:
            try:
                node.start()
            except Exception:
                node.daemon.stop()
                raise
        return node
    def _init(self, options, configuration, request):
        self.rpc_filename = configuration['rpc-file']
        self.lightning_dir = configuration['lightning-dir']
        path = os.path.join(self.lightning_dir, self.rpc_filename)
        self.rpc = LightningRpc(path)
        for name, value in options.items():
            self.options[name]['value'] = value

        # Dispatch the plugin's init handler if any
        if self.child_init:
            return self._exec_func(self.child_init, request)
        return None
Example #13
0
    def _init(self, options, configuration, request):
        self.rpc_filename = configuration['rpc-file']
        self.lightning_dir = configuration['lightning-dir']
        path = os.path.join(self.lightning_dir, self.rpc_filename)
        self.rpc = LightningRpc(path)
        for name, value in options.items():
            self.options[name]['value'] = value

        # Swap the registered `init` method handler back in and
        # re-dispatch
        if self.init:
            self.methods['init'], _ = self.init
            self.init = None
            return self._exec_func(self.methods['init'], request)
        return None
 def __init__(self,
              lightning_dir,
              lightning_port,
              btc,
              executor=None,
              node_id=0):
     self.bitcoin = btc
     self.executor = executor
     self.daemon = LightningD(lightning_dir,
                              btc.bitcoin_dir,
                              port=lightning_port)
     socket_path = os.path.join(lightning_dir,
                                "lightning-rpc").format(node_id)
     self.invoice_count = 0
     self.rpc = LightningRpc(socket_path, self.executor)
     self.logger = logging.getLogger(
         'lightning-node({})'.format(lightning_port))
Example #15
0
    def current_status(self):
        if self.status == "unpaid":
            try:
                inv = LightningRpc(settings.LIGHTNING_RPC).listinvoices(self.label)

                inv_ln = inv['invoices'][0]
                if inv_ln['status'] == "expired":
                    self.status = inv_ln['status']
                if inv_ln['status'] == "paid":
                    self.status = inv_ln['status']
                    self.paid_at = datetime.fromtimestamp(inv_ln['paid_at'], timezone.utc)
                    self.pay_index = inv_ln['pay_index']
                self.save()
                return self.status
            except:
                return '-'
        else:
            return self.status
Example #16
0
def init(options, configuration, plugin, **kwargs):
    global lightning_rpc, bitcoin_rpc, rpc_settings
    print(configuration)
    # setup lightning rpc
    lightning_dir, rpc_file = configuration['lightning-dir'], configuration['rpc-file']
    path = Path(f"{lightning_dir}/{rpc_file}")
    lightning_rpc = LightningRpc(str(path))

    # setup bitcoin rpc
    config = lightning_rpc.listconfigs()
    rpc_settings['user'] = config['bitcoin-rpcuser']
    rpc_settings['password'] = config['bitcoin-rpcpassword']
    rpc_settings['port'] = config['bitcoin-rpcport']
    rpc_settings['host'] = config['bitcoin-rpcconnect']
    network = config['network']

    template = "http://{user}:{password}@{host}:{port}"
    uri = template.format(**rpc_settings)
    bitcoin_rpc = AuthServiceProxy(uri)

    # check that it works
    bitcoin_rpc.getblockchaininfo()
Example #17
0
    def get_node(self, legacy=True):
        node_id = self.next_id
        self.next_id += 1

        lightning_dir = os.path.join(TEST_DIR, self.func._testMethodName,
                                     "lightning-{}/".format(node_id))

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        port = 16330 + node_id
        if legacy:
            daemon = utils.LegacyLightningD(lightning_dir,
                                            bitcoind.bitcoin_dir,
                                            port=port)
            rpc = LegacyLightningRpc(socket_path, self.executor)
        else:
            daemon = utils.LightningD(lightning_dir,
                                      bitcoind.bitcoin_dir,
                                      port=port)
            # TODO(cdecker) Move into LIGHTNINGD_CONFIG once legacy daemon was removed
            daemon.cmd_line.append("--dev-broadcast-interval=1000")
            rpc = LightningRpc(socket_path, self.executor)

        node = utils.LightningNode(daemon, rpc, bitcoind, self.executor)
        self.nodes.append(node)
        if VALGRIND:
            node.daemon.cmd_line = [
                'valgrind', '-q', '--trace-children=yes',
                '--trace-children-skip=*bitcoin-cli*', '--error-exitcode=7',
                '--log-file={}/valgrind-errors'.format(
                    node.daemon.lightning_dir)
            ] + node.daemon.cmd_line

        node.daemon.start()
        # Cache `getinfo`, we'll be using it a lot
        node.info = node.rpc.getinfo()
        return node
Example #18
0
import pprint
from uuid import uuid4

from lightning import LightningRpc, RpcError


"""
Challenge:
rpc3 generates an invoice and returns details to rpc1. rpc1 then does a sendpay only to
*rpc2*, who, upon not recognising the payment hash will generate an onion which forwards
the payment to rpc3.
"""


rpc1 = LightningRpc("/tmp/l1-regtest/regtest/lightning-rpc")
rpc2 = LightningRpc("/tmp/l2-regtest/regtest/lightning-rpc")
rpc3 = LightningRpc("/tmp/l3-regtest/regtest/lightning-rpc")


# rpc3 adds an invoice and returns the decoded invoice
try:
    inv = rpc3.decodepay(rpc3.invoice(10000, uuid4().hex, uuid4().hex)["bolt11"])
except RpcError:
    raise


# get rpc2 node_id
rpc2_node_id = rpc2.getinfo()["id"]

# rpc1 gets a route to rpc2
# we add 10 satoshi to amount (10 hops max x 1 satoshi fee each)
Example #19
0
auth = HTTPBasicAuth()
app = Flask(__name__)
api = Api(app)

USER_DATA = {"bAxX0zoh8ObADbAD0": "bAxX0zoh8ObADbAD0"}

telegram_bot_token = '60423423281:Ac2lUjuOPX0NAc2lUjuOPHxpbADxhxyQc'
atomic_tipbot = '8834534558:AAc2lUt7BoPi7P3t7BoPi7P3t7BoPi7PurwOP0zEw'
telegram_bot = telegram.Bot(telegram_bot_token)
userbot = telegram.Bot(atomic_tipbot)

dbclient = pymongo.MongoClient('192.168.0.43')
mongo_db = "tipdb"
mongo = dbclient[mongo_db]

lnltc = LightningRpc("/home/ltc/.lightning/lightning-rpc")
lnbtc = LightningRpc("/home/payer/.lightning/lightning-rpc")


def sendTele(msg):
    telegram_bot.send_message(chat_id='admin_user_id',
                              text="paylightning.py:\n " + msg)


def sendNBpic(userid, msg):
    userbot.send_animation(userid,
                           animation="https://i.imgur.com/UY8I7ow.gif",
                           caption=msg)


def notifyUser(userid, msg):
def init(options, configuration, plugin):
    global rpc
    plugin.log("walletbalance init")
    path = join(configuration["lightning-dir"], configuration["rpc-file"])
    rpc = LightningRpc(path)
Example #21
0
def generate_invoice():
    # Generate the invoice
    l1 = LightningRpc("/home/admin/.lightning/lightning-rpc")
    invoice = l1.invoice(10000,"1n1{}".format(random.random()),"static-discharge")
    return invoice['bolt11']
Example #22
0
 def __init__(self, path):
     super().__init__()
     self.path = path
     print("rpc path: %s" % self.path)
     self.rpc = LightningRpc(self.path)
Example #23
0
 def __init__(self):
     self.l1 = LightningRpc(getenv("CLIGHTNING_RPC"))
 def _connect(self):
     self._connection = LightningRpc(self.rpclocation)
Example #25
0
        assert(len(hh) == 6)
        rr = int(hh[0:2], 16)
        gg = int(hh[2:4], 16)
        bb = int(hh[4:6], 16)
        return f'\x1b[38;2;{rr};{gg};{bb}m'
    reset = '\x1b[0m' # reset to terminal defaults

def colorize(color, colorthis):
    '''
    Convert a something (color) to a terminal-colorized string.
    '''
    return T.rgb(color) + colorthis + T.reset

T = TermColors()

node = LightningRpc(os.path.join(os.getenv("HOME"), ".lightning/bitcoin/lightning-rpc"))

peers = node.listpeers()

for peer in peers['peers']:
    if len(peer['channels']) > 0:
        chan_status = peer['channels'][0]['state']
        chan_color = node.listnodes(peer["id"])['nodes'][0]['color']
        try:
            peerAlias = node.listnodes(peer["id"])['nodes'][0]['alias']
        except IndexError:
            peerAlias = "????????????????"
        except KeyError:
            peerAlias = "????????????????"
        print(peer['connected'], str(round((peer["channels"][0]["msatoshi_total"]/100000000), 1)) + " mBTC", peer["id"], colorize(chan_color, peerAlias), chan_status, str(round((peer["channels"][0]["msatoshi_to_us"]/100000000), 1)))
    else:
Example #26
0
    def get_node(self,
                 disconnect=None,
                 options=None,
                 may_fail=False,
                 may_reconnect=False,
                 random_hsm=False,
                 feerates=(15000, 7500, 3750),
                 start=True,
                 fake_bitcoin_cli=False,
                 log_all_io=False):
        with self.lock:
            node_id = self.next_id
            self.next_id += 1
        port = self.get_next_port()

        lightning_dir = os.path.join(self.directory,
                                     "lightning-{}/".format(node_id))

        if os.path.exists(lightning_dir):
            shutil.rmtree(lightning_dir)

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        daemon = LightningD(lightning_dir,
                            self.bitcoind.bitcoin_dir,
                            port=port,
                            random_hsm=random_hsm,
                            node_id=node_id)
        # If we have a disconnect string, dump it to a file for daemon.
        if disconnect:
            daemon.disconnect_file = os.path.join(lightning_dir,
                                                  "dev_disconnect")
            with open(daemon.disconnect_file, "w") as f:
                f.write("\n".join(disconnect))
            daemon.opts["dev-disconnect"] = "dev_disconnect"
        if log_all_io:
            assert DEVELOPER
            daemon.env["LIGHTNINGD_DEV_LOG_IO"] = "1"
            daemon.opts["log-level"] = "io"
        if DEVELOPER:
            daemon.opts["dev-fail-on-subdaemon-fail"] = None
            daemon.env["LIGHTNINGD_DEV_MEMLEAK"] = "1"
            if VALGRIND:
                daemon.env["LIGHTNINGD_DEV_NO_BACKTRACE"] = "1"
            if not may_reconnect:
                daemon.opts["dev-no-reconnect"] = None

        cli = os.path.join(lightning_dir, "fake-bitcoin-cli")
        with open(cli, "w") as text_file:
            text_file.write(
                '#! /bin/sh\n'
                '! [ -x bitcoin-cli-fail ] || exec ./bitcoin-cli-fail "$@"\n'
                'for a in "$@"; do\n'
                '\t! [ -x bitcoin-cli-fail-"$a" ] || exec ./bitcoin-cli-fail-"$a" "$@"\n'
                'done\n'
                'exec bitcoin-cli "$@"\n')
        os.chmod(cli, os.stat(cli).st_mode | stat.S_IEXEC)
        daemon.opts['bitcoin-cli'] = cli

        if options is not None:
            daemon.opts.update(options)

        rpc = LightningRpc(socket_path, self.executor)

        node = LightningNode(daemon,
                             rpc,
                             self.bitcoind,
                             self.executor,
                             may_fail=may_fail,
                             may_reconnect=may_reconnect)

        # Regtest estimatefee are unusable, so override.
        node.set_feerates(feerates, False)

        self.nodes.append(node)
        if VALGRIND:
            node.daemon.cmd_prefix = [
                'valgrind', '-q', '--trace-children=yes',
                '--trace-children-skip=*bitcoin-cli*', '--error-exitcode=7',
                '--log-file={}/valgrind-errors.%p'.format(
                    node.daemon.lightning_dir)
            ]

        if start:
            try:
                node.start()
            except Exception:
                node.daemon.stop()
                raise
        return node
Example #27
0
    def get_node(self,
                 disconnect=None,
                 options=None,
                 may_fail=False,
                 may_reconnect=False,
                 random_hsm=False,
                 feerates=(15000, 7500, 3750),
                 start=True,
                 log_all_io=False,
                 dbfile=None,
                 node_id=None):
        if not node_id:
            node_id = self.get_node_id()

        port = self.get_next_port()

        lightning_dir = os.path.join(self.directory,
                                     "lightning-{}/".format(node_id))

        if os.path.exists(lightning_dir):
            shutil.rmtree(lightning_dir)

        socket_path = os.path.join(lightning_dir,
                                   "lightning-rpc").format(node_id)
        daemon = LightningD(lightning_dir,
                            bitcoindproxy=self.bitcoind.get_proxy(),
                            port=port,
                            random_hsm=random_hsm,
                            node_id=node_id)
        # If we have a disconnect string, dump it to a file for daemon.
        if disconnect:
            daemon.disconnect_file = os.path.join(lightning_dir,
                                                  "dev_disconnect")
            with open(daemon.disconnect_file, "w") as f:
                f.write("\n".join(disconnect))
            daemon.opts["dev-disconnect"] = "dev_disconnect"
        if log_all_io:
            assert DEVELOPER
            daemon.env["LIGHTNINGD_DEV_LOG_IO"] = "1"
            daemon.opts["log-level"] = "io"
        if DEVELOPER:
            daemon.opts["dev-fail-on-subdaemon-fail"] = None
            daemon.env["LIGHTNINGD_DEV_MEMLEAK"] = "1"
            if os.getenv("DEBUG_SUBD"):
                daemon.opts["dev-debugger"] = os.getenv("DEBUG_SUBD")
            if VALGRIND:
                daemon.env["LIGHTNINGD_DEV_NO_BACKTRACE"] = "1"
            if not may_reconnect:
                daemon.opts["dev-no-reconnect"] = None

        if options is not None:
            daemon.opts.update(options)

        rpc = LightningRpc(socket_path, self.executor)

        node = LightningNode(daemon,
                             rpc,
                             self.bitcoind,
                             self.executor,
                             may_fail=may_fail,
                             may_reconnect=may_reconnect)

        # Regtest estimatefee are unusable, so override.
        node.set_feerates(feerates, False)

        self.nodes.append(node)
        if VALGRIND:
            node.daemon.cmd_prefix = [
                'valgrind', '-q', '--trace-children=yes',
                '--trace-children-skip=*python*,*bitcoin-cli*',
                '--error-exitcode=7',
                '--log-file={}/valgrind-errors.%p'.format(
                    node.daemon.lightning_dir)
            ]

        if dbfile:
            out = open(
                os.path.join(node.daemon.lightning_dir, 'lightningd.sqlite3'),
                'xb')
            with lzma.open(os.path.join('tests/data', dbfile), 'rb') as f:
                out.write(f.read())

        if start:
            try:
                node.start()
            except Exception:
                node.daemon.stop()
                raise
        return node
Example #28
0
 def __init__(self, daemon_rpc):
     self.rpc = LightningRpc(daemon_rpc)
Example #29
0
from lightning import LightningRpc
from flask import Flask, request, render_template
import random
import qrcode
import json
import re
import ast
app = Flask(__name__)

# Connect to local LN node
ln = LightningRpc("/tmp/lightning-rpc")

@app.route("/")
def fulmo():
	return render_template('index.html')

@app.route("/newaddr/")
def new_address():
	addr_type = request.args.get('type')
	make_qr = request.args.get('qr')

	try:
		addr = ln.newaddr(addr_type)
		result = {}
		result["address"] = addr["address"]

		if make_qr is not None:
			result["qr"] = qr(addr['address'])

	except ValueError, e:
		result = parse_exception(e)
Example #30
0
        return list(reversed(route))

    def __init__(self, network):
        self.__network = network

    def compute_fee_for_path(self, amount, path):
        channels = self.__node_id_path_to_channels(path)
        onion_route = self.__onion_from_channels(amount, channels)
        return onion_route[0]["msatoshi"] - amount
        # print(onion_route)


if __name__ == "__main__":
    pa = PeerAnalyzer()
    exit()
    ln = LightningRpc("/home/rpickhardt/.lightning/lightning-rpc")
    own_channels = None
    try:
        f = open(
            "/Users/rpickhardt/hacken/lightning-helpers/balance-channels/friends20190301.json")
        own_channels = json.load(f)["channels"]
    except:
        own_channels = ln.listfunds()["channels"]

    ego_network = EgoNetwork(own_channels)

    channel_suggester = ChannelSuggester(own_channels, 0.25, 0.5)
    if channel_suggester.is_need_to_balance():
        print("channel balancing is suggested")
        # print("channels with too little outgoing capacity:")
        # for chan in channel_suggester.get_dry_channels():