let () =
  let cli_args = Base.Sys.get_argv () in
  let port = int_of_string cli_args.(1) in
  let discovery_port =
    if Array.length cli_args = 3 then int_of_string_opt cli_args.(2) else None
  in
  let config = default_p2p_config port discovery_port in
  Lwt_main.run
    ( Internal_event_unix.init () >>= fun () ->
      Node_Event.(emit p2p_event) "bootstrapping" >>= fun () ->
      P2p.create ~config ~limits:default_p2p_limits peer_metadata_cfg
        (connection_metadata_cfg (init_connection_metadata (Some config) true))
        msg_config
      >>= function
      | Ok p2p ->
          Lwt.return (P2p.activate p2p) >>= fun () ->
          let peer_id = P2p.peer_id p2p in
          Node_Event.(emit show_peer_id) peer_id >>= fun () ->
          let rec loop () : unit =
            let _ =
              P2p.on_new_connection p2p (fun _ conn ->
                  let rec conn_loop () =
                    (fun () ->
                      
                      Format.eprintf "hello\n@.";
                      P2p.send p2p conn (Pong peer_id) >>= function
                      | _ -> (
                          P2p.recv p2p conn >>= function
                          | Ok msg -> (
                              match msg with
                              | Ping ->
                                  Format.eprintf "Received a Ping!\n@.";
                                  Lwt.return_unit
                              | Pong id ->
                                  Format.eprintf "Received a Pong!@.";
                                  Node_Event.(emit received_pong) id)
                          | Error _ -> Lwt.return_unit))
                    |> Lwt.async;
                    conn_loop ()
                  in
                  conn_loop ())
            in
            loop ();
          in
          loop ();
          Lwt.return_unit
      | Error _ ->
          Format.printf "error@.";
          Node_Event.(emit error) () >>= fun () -> Internal_event_unix.close ()
    )