Beispiel #1
0
def main():
    # 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'

    start_spy_output = cmd(start_spy[0])

    # open gRPC connection
    cert = open(os.path.expanduser('~/.lnd/tls.cert'), 'rb').read()
    creds = grpc.ssl_channel_credentials(cert)
    channel = grpc.secure_channel('localhost:10002', creds)
    stub = lnrpc.WalletUnlockerStub(channel)

    # unlock wallet
    # request = ln.UnlockWalletRequest(wallet_password="******".encode())
    # response = stub.UnlockWallet(request)

    for line in start_spy_output:
        match_r = re.search("((.*)Received UpdateAddHTLC(.*))", line)
        match_s = re.search("((.*)Sending UpdateAddHTLC(.*))", line)
        if match_r:
            from_addr = line.split(' from ')[1].split('@')[0]
            timestamp = line.split(' [DBG] ')[0]
            from_amt = line.split(', ')[2].split('=')[1]

            print(from_addr + ' - ' + from_amt + ' - ' + timestamp)
        elif match_s:
            print("asdsad")

    return
Beispiel #2
0
def create_wallet(container):
    channel = get_channel(container)
    stub = lnrpc.WalletUnlockerStub(channel)
    request = ln.InitWalletRequest(
        wallet_password=PASSWORD.encode(),
        cipher_seed_mnemonic=gen_seed(container),
    )
    response = stub.InitWallet(request)
    print(response)
Beispiel #3
0
 def start(self):
     super().start()
     self.wait_for_log('RPC server listening on')
     self.unlocker_stub = lnrpc_grpc.WalletUnlockerStub(self.make_channel())
     seed = self.unlocker_stub.GenSeed(lnrpc.GenSeedRequest())
     self.unlocker_stub.InitWallet(
         lnrpc.InitWalletRequest(
             wallet_password=b"password",
             recovery_window=0,
             cipher_seed_mnemonic=seed.cipher_seed_mnemonic))
     self.wait_for_log('Done catching up block hashes')
     time.sleep(5)
     # need to remake the channel, otherwise the Lightning gRPC service might not be there yet
     self.stub = lnrpc_grpc.LightningStub(self.make_channel())
     logging.info('LND started (pid: {})'.format(self.proc.pid))
Beispiel #4
0
def main():
    if len(sys.argv) < 3:
        # missing num nodes
        print("Usage:")
        print("     py lnd-cluster.py <NUM_NODES> <GRAPH_TYPE> <ROUTING_TYPE>")
        print("     Graph types: tree, central, ring")
        print("     Routing types: random, merchant")
        exit(1)

    NUM_NODES = int(sys.argv[1])
    GRAPH_TYPE = sys.argv[2]
    ROUTING_TYPE = sys.argv[3]
    WALLET_PASS = bytes('00000000', 'utf-8')
    MINNING_ADDR = "SY6RbmrfYo2Vg9P9RuTreucM7G1SyVqhhb"

    ### ARG Checking ###
    if GRAPH_TYPE not in graphs.graph_types:
        print("ERROR: invalid graph type -> " + GRAPH_TYPE)
        exit()
    if ROUTING_TYPE not in routing.routing_types:
        print("ERROR: invalid routing type -> " + ROUTING_TYPE)
        exit()

    ### Create BTCD dir ###
    if os.path.exists(BTCD_DIR) == False:
        os.makedirs(BTCD_DIR)

    ### Create Nodes dir ###
    if os.path.exists(NODES_DIR) == False:
        os.makedirs(NODES_DIR)

    ### Clean Nodes dir ###
    dir_list = os.listdir(NODES_DIR)
    for node_id in dir_list:
        node_dir = NODES_DIR + '/' + str(node_id)
        shutil.rmtree(node_dir)

    ### Thread data ###

    # btcd thread proc
    btcd = None

    # Stores all node data
    # {
    #   id,
    #   thread,
    #   stub_wal,
    #   addr
    # }
    nodes = []

    ### Start Threads ###

    # start btcd thread
    btcd = Process(target=btcd_start_node)
    btcd.start()

    # start lnd threads
    for node_id in range(0, NUM_NODES):
        nodes.append({
            "id": node_id,
            "thread": Process(target=ln_start_node, args=(node_id, ))
        })
        nodes[node_id]["thread"].start()
    time.sleep(1)

    os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'

    ### init RPC stubs ###
    for node_id in range(0, NUM_NODES):
        while True:
            try:
                print("Node {} reading cert file...".format(str(node_id)))
                cert = open(NODES_DIR + '/' + str(node_id) + '/tls.cert',
                            'rb').read()
                break
            except:
                print("ERROR: cannot find cert file: " +
                      str(NODES_DIR + '/' + str(node_id) + '/tls.cert'))

        ssl_creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel('localhost:' + str(10000 + node_id),
                                      ssl_creds)

        stub_wal = lnrpc.WalletUnlockerStub(channel)

        nodes[node_id]["stub_wal"] = stub_wal

    ### Init a node ###
    for node_id in range(0, NUM_NODES):
        stub_wal = nodes[node_id]['stub_wal']

        # Gen Seed
        request = None
        if node_id == 0:
            # use same seed for first node
            # keeps minning address constant
            request = ln.GenSeedRequest(seed_entropy=bytes(node_seed))
        else:
            request = ln.GenSeedRequest()
        response = stub_wal.GenSeed(request)

        cipher_seed_mnemonic = response.cipher_seed_mnemonic
        print(bytes(node_seed))
        print(response)

        # Init Wallet
        request = ln.InitWalletRequest(
            wallet_password=WALLET_PASS,
            cipher_seed_mnemonic=cipher_seed_mnemonic)
        response = stub_wal.InitWallet(request)

        print(response)

    ### wait for rpc servers to init ###
    for node_id in range(0, NUM_NODES):
        while True:
            output = cmd_async(
                lncli_cmd.format(str(node_id), str(10000 + node_id),
                                 "getinfo"))
            try:
                # if rpc server is active,
                # the response will be json
                info_output = json.loads(output)
                nodes[node_id]['id_pubkey'] = info_output["identity_pubkey"]
                print(info_output)
                break
            except:
                print("======== ERROR: RPC server not active yet ========")
                print("========             node_id: {}           ========".
                      format(node_id))

            time.sleep(1)

        # New Address
        output = cmd_async(
            lncli_cmd.format(str(node_id), str(10000 + node_id),
                             "newaddress np2wkh"))
        nodes[node_id]["addr"] = json.loads(output)["address"]

    ### Fund All Nodes ###
    COINS_PER_NODE = " 100000000"

    output_node_0_balance = cmd_async(
        lncli_cmd.format("0", "10000", "walletbalance"))
    print(output_node_0_balance)

    # Mine coins
    output_mining = cmd_async(btcctl_cmd.format("generate 200"))
    time.sleep(5)  # Wait for mining

    # Send Coins
    for node_id in range(1, NUM_NODES):
        lnc_command = lncli_cmd.format(
            "0", "10000",
            "sendcoins " + nodes[node_id]['addr'] + COINS_PER_NODE)
        output_sendcoins = cmd_async(lnc_command)
        print(output_sendcoins)

    # Mine transactions
    cmd_async(btcctl_cmd.format("generate 100"))
    time.sleep(5)  # Wait for mining

    ### Connect Peers and Create Channels ###

    # create graph
    graph = graphs.graph_types[GRAPH_TYPE](NUM_NODES)

    # connect peers and open channels
    for node_id in range(0, NUM_NODES):
        peers = graph[node_id]
        for peer_i in range(0, len(peers)):
            peer = nodes[peers[peer_i]]

            # connect peers
            lnc_command = lncli_cmd.format(
                str(node_id), str(10000 + node_id), "connect " +
                peer["id_pubkey"] + "@localhost:" + str(20000 + peer['id']))
            output_connect = cmd_async(lnc_command)
            print(output_connect)

            # open channels
            lnc_command = lncli_cmd.format(
                str(node_id), str(10000 + node_id), "openchannel --node_key=" +
                peer["id_pubkey"] + " --local_amt=1000000 --push_amt=100000")
            output_channel = cmd_async(lnc_command)
            print(output_channel)

    # Mine channels
    output_mining = cmd_async(btcctl_cmd.format("generate 20"))
    time.sleep(5)  # Wait for mining

    ### Simulate Routing ###
    routing.routing_types[ROUTING_TYPE](NUM_NODES)

    return
    return key


def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)


def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)


url = "https://enteryourawsurlhere.com/dev"

if __name__ == '__main__':
    # Send a post request to specified secret URL, which responds with the encrypted passphrase
    wallet_pass_enc = requests.post(url).text.encode("UTF-8")
    with open(os.path.expanduser("~") + "/atestkey.key", 'rb') as f:
        mykey = f.read()

    wallet_pass = decrypt(wallet_pass_enc, mykey)
    # wallet_pass = bytes(os.environ["LND_PASS"],"UTF-8")
    os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
    cert = open('/root/.lnd/tls.cert', 'rb').read()
    ssl_creds = grpc.ssl_channel_credentials(cert)
    channel = grpc.secure_channel('localhost:10009', ssl_creds)
    stub = lnrpc.WalletUnlockerStub(channel)
    # This is not how we should do this long term

    request = ln.UnlockWalletRequest(wallet_password=wallet_pass)
    response = stub.UnlockWallet(request)
    print(response)
Beispiel #6
0
def gen_seed(container):
    channel = get_channel(container)
    stub = lnrpc.WalletUnlockerStub(channel)
    request = ln.GenSeedRequest()
    response = stub.GenSeed(request)
    return response.cipher_seed_mnemonic