<commit_before>/*
 *  Copyright (C) 2017, Nayuta, Inc. All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
/** @file   ln_establish.c
 *  @brief  ln_establish
 */
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <assert.h>

#include "utl_str.h"
#include "utl_buf.h"
#include "utl_dbg.h"
#include "utl_time.h"
#include "utl_int.h"

#include "btc_crypto.h"
#include "btc_script.h"
#include "btc_sw.h"

#include "ln_db.h"
#include "ln_signer.h"
#include "ln_commit_tx.h"
#include "ln_commit_tx_util.h"
#include "ln_derkey.h"
#include "ln_script.h"
#include "ln.h"
#include "ln_msg_establish.h"
#include "ln_local.h"
#include "ln_setupctl.h"
#include "ln_close.h"
#include "ln_establish.h"


/**************************************************************************
 * macros
 **************************************************************************/

//feerate: receive open_channel
// #define M_FEERATE_CHK_MIN_OK(local,remote)   ( 0.5 * (local) < 1.0 * (remote))  ///< feerate_per_kwのmin判定
// #define M_FEERATE_CHK_MAX_OK(local,remote)   (10.0 * (local) > 1.0 * (remote))  ///< feerate_per_kwのmax判定
#define M_FEERATE_CHK_MIN_OK(local,remote)      (true)  ///< feerate_per_kwのmin判定(ALL OK)
#define M_FEERATE_CHK_MAX_OK(local,remote)      (true)  ///< feerate_per_kwのmax判定(ALL OK)

#define M_FUNDING_INDEX                         (0)     ///< funding_txのvout


/**************************************************************************
 * prototypes
 **************************************************************************/

static bool check_peer_node(ln_channel_t *pChannel);

static void start_funding_wait(ln_channel_t *pChannel, bool bSendTx);
static bool create_funding_tx(ln_channel_t *pChannel, bool bSign);


/**************************************************************************
 * public functions
 **************************************************************************/

bool /*HIDDEN*/ ln_open_channel_send(
    ln_channel_t *pChannel, uint64_t FundingSat, uint64_t PushMSat, uint32_t FeeRate,
    uint8_t PrivChannel)
{
    if (!M_INIT_FLAG_EXCHNAGED(pChannel->init_flag)) {
        M_SET_ERR(pChannel, LNERR_INV_STATE, "no init finished.");
        return false;
    }
    if (!check_peer_node(pChannel)) {
        M_SET_ERR(pChannel, LNERR_NO_PEER, "no peer node_id");
        return false;
    }
    if (ln_funding_info_funding_now(&pChannel->funding_info)) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already funding");
        return false;
    }
    if (FeeRate < LN_FEERATE_PER_KW_MIN) {
        //feerate_per_kw too low
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "feerate_per_kw too low");
        return false;
    }
    if (FundingSat < LN_FUNDING_SATOSHIS_MIN) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "funding_satoshis too low");
        return false;
    } else if (FundingSat > LN_FUNDING_SATOSHIS_MAX) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "funding_satoshis too high");
        return false;
    }
    if (LN_SATOSHI2MSAT(FundingSat) < PushMSat) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "push_msat too high");
        return false;
    }

    //temporary_channel_id
    btc_rng_rand(pChannel->channel_id, LN_SZ_CHANNEL_ID);

    //open_channel
    ln_msg_open_channel_t msg;
    msg.p_chain_hash = ln_genesishash_get();
    msg.p_temporary_channel_id = pChannel->channel_id;
    msg.funding_satoshis = FundingSat;
    msg.push_msat = PushMSat;
    msg.dust_limit_satoshis = pChannel->establish.param.dust_limit_sat;
    if (pChannel->establish.param.max_htlc_value_in_flight_msat > LN_SATOSHI2MSAT(msg.funding_satoshis)) {
        msg.max_htlc_value_in_flight_msat = LN_SATOSHI2MSAT(msg.funding_satoshis);
    } else {
        msg.max_htlc_value_in_flight_msat = pChannel->establish.param.max_htlc_value_in_flight_msat;
    }
    msg.channel_reserve_satoshis = pChannel->establish.param.channel_reserve_sat;
    msg.htlc_minimum_msat = pChannel->establish.param.htlc_minimum_msat;
    msg.feerate_per_kw = FeeRate;
    msg.to_self_delay = pChannel->establish.param.to_self_delay;
    msg.max_accepted_htlcs = pChannel->establish.param.max_accepted_htlcs;
    msg.p_funding_pubkey = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_FUNDING];
    msg.p_revocation_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_REVOCATION];
    msg.p_payment_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_PAYMENT];
    msg.p_delayed_payment_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_DELAYED];
    msg.p_htlc_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_HTLC];
    msg.p_first_per_commitment_point = pChannel->keys_local.per_commitment_point;
    if (PrivChannel != 0) {
        LOGD("private channel\n");
        msg.channel_flags = 0;
    } else {
        msg.channel_flags = CHANNEL_FLAGS_ANNOCNL;
    }
    msg.shutdown_len = 0;
    msg.p_shutdown_scriptpubkey = NULL;
    utl_buf_t buf = UTL_BUF_INIT;
    ln_msg_open_channel_write(&buf, &msg);
    ln_callback(pChannel, LN_CB_TYPE_SEND_MESSAGE, &buf);
    utl_buf_free(&buf);

    pChannel->commit_info_local.dust_limit_sat = msg.dust_limit_satoshis;
    pChannel->commit_info_local.max_htlc_value_in_flight_msat = msg.max_htlc_value_in_flight_msat;
    pChannel->commit_info_local.channel_reserve_sat = msg.channel_reserve_satoshis;
    pChannel->commit_info_local.htlc_minimum_msat = msg.htlc_minimum_msat;
    pChannel->commit_info_local.max_accepted_htlcs = msg.max_accepted_htlcs;
    pChannel->commit_info_local.local_msat =
        pChannel->commit_info_remote.remote_msat =
        LN_SATOSHI2MSAT(msg.funding_satoshis) - msg.push_msat;
    pChannel->commit_info_local.remote_msat =
        pChannel->commit_info_remote.local_msat =
        msg.push_msat;
    pChannel->funding_info.funding_satoshis = msg.funding_satoshis;
    if (!ln_update_info_set_initial_fee_send(&pChannel->update_info, msg.feerate_per_kw)) return false;
    pChannel->commit_info_remote.to_self_delay = msg.to_self_delay;

    pChannel->funding_info.state =
        (ln_funding_state_t)(
            ((msg.channel_flags & CHANNEL_FLAGS_MASK) ? LN_FUNDING_STATE_STATE_NO_ANNO_CH : 0) |
            LN_FUNDING_STATE_STATE_FUNDING);
    pChannel->funding_info.role = LN_FUNDING_ROLE_FUNDER;
    return true;
}


bool HIDDEN ln_open_channel_recv(ln_channel_t *pChannel, const uint8_t *pData, uint16_t Len)
{
    LOGD("BEGIN\n");

    if (ln_funding_info_is_funder(&pChannel->funding_info, true)) {
        M_SET_ERR(pChannel, LNERR_INV_SIDE, "not fundee");
        return false;
    }
    if (ln_funding_info_funding_now(&pChannel->funding_info)) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already funding");
        return false;
    }
    if (pChannel->short_channel_id != 0) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already established");
        return false;
    }

    ln_msg_open_channel_t msg;
    if (!ln_msg_open_channel_read(&msg, pData, Len)) {
        M_SET_ERR(pChannel, LNERR_MSG_READ, "read message");
        return false;
    }
    memcpy(pChannel->channel_id, msg.p_temporary_channel_id, LN_SZ_CHANNEL_ID);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_FUNDING], msg.p_funding_pubkey, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_REVOCATION], msg.p_revocation_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_PAYMENT], msg.p_payment_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_DELAYED], msg.p_delayed_payment_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_HTLC], msg.p_htlc_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.per_commitment_point, msg.p_first_per_commitment_point, BTC_SZ_PUBKEY);
<commit_msg>open_channel: through if open_channel received on opened socket.<commit_after>/*
 *  Copyright (C) 2017, Nayuta, Inc. All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
/** @file   ln_establish.c
 *  @brief  ln_establish
 */
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <assert.h>

#include "utl_str.h"
#include "utl_buf.h"
#include "utl_dbg.h"
#include "utl_time.h"
#include "utl_int.h"

#include "btc_crypto.h"
#include "btc_script.h"
#include "btc_sw.h"

#include "ln_db.h"
#include "ln_signer.h"
#include "ln_commit_tx.h"
#include "ln_commit_tx_util.h"
#include "ln_derkey.h"
#include "ln_script.h"
#include "ln.h"
#include "ln_msg_establish.h"
#include "ln_local.h"
#include "ln_setupctl.h"
#include "ln_close.h"
#include "ln_establish.h"


/**************************************************************************
 * macros
 **************************************************************************/

//feerate: receive open_channel
// #define M_FEERATE_CHK_MIN_OK(local,remote)   ( 0.5 * (local) < 1.0 * (remote))  ///< feerate_per_kwのmin判定
// #define M_FEERATE_CHK_MAX_OK(local,remote)   (10.0 * (local) > 1.0 * (remote))  ///< feerate_per_kwのmax判定
#define M_FEERATE_CHK_MIN_OK(local,remote)      (true)  ///< feerate_per_kwのmin判定(ALL OK)
#define M_FEERATE_CHK_MAX_OK(local,remote)      (true)  ///< feerate_per_kwのmax判定(ALL OK)

#define M_FUNDING_INDEX                         (0)     ///< funding_txのvout


/**************************************************************************
 * prototypes
 **************************************************************************/

static bool check_peer_node(ln_channel_t *pChannel);

static void start_funding_wait(ln_channel_t *pChannel, bool bSendTx);
static bool create_funding_tx(ln_channel_t *pChannel, bool bSign);


/**************************************************************************
 * public functions
 **************************************************************************/

bool /*HIDDEN*/ ln_open_channel_send(
    ln_channel_t *pChannel, uint64_t FundingSat, uint64_t PushMSat, uint32_t FeeRate,
    uint8_t PrivChannel)
{
    if (!M_INIT_FLAG_EXCHNAGED(pChannel->init_flag)) {
        M_SET_ERR(pChannel, LNERR_INV_STATE, "no init finished.");
        return false;
    }
    if (!check_peer_node(pChannel)) {
        M_SET_ERR(pChannel, LNERR_NO_PEER, "no peer node_id");
        return false;
    }
    if (ln_funding_info_funding_now(&pChannel->funding_info)) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already funding");
        return false;
    }
    if (FeeRate < LN_FEERATE_PER_KW_MIN) {
        //feerate_per_kw too low
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "feerate_per_kw too low");
        return false;
    }
    if (FundingSat < LN_FUNDING_SATOSHIS_MIN) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "funding_satoshis too low");
        return false;
    } else if (FundingSat > LN_FUNDING_SATOSHIS_MAX) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "funding_satoshis too high");
        return false;
    }
    if (LN_SATOSHI2MSAT(FundingSat) < PushMSat) {
        M_SET_ERR(pChannel, LNERR_INV_VALUE, "push_msat too high");
        return false;
    }

    //temporary_channel_id
    btc_rng_rand(pChannel->channel_id, LN_SZ_CHANNEL_ID);

    //open_channel
    ln_msg_open_channel_t msg;
    msg.p_chain_hash = ln_genesishash_get();
    msg.p_temporary_channel_id = pChannel->channel_id;
    msg.funding_satoshis = FundingSat;
    msg.push_msat = PushMSat;
    msg.dust_limit_satoshis = pChannel->establish.param.dust_limit_sat;
    if (pChannel->establish.param.max_htlc_value_in_flight_msat > LN_SATOSHI2MSAT(msg.funding_satoshis)) {
        msg.max_htlc_value_in_flight_msat = LN_SATOSHI2MSAT(msg.funding_satoshis);
    } else {
        msg.max_htlc_value_in_flight_msat = pChannel->establish.param.max_htlc_value_in_flight_msat;
    }
    msg.channel_reserve_satoshis = pChannel->establish.param.channel_reserve_sat;
    msg.htlc_minimum_msat = pChannel->establish.param.htlc_minimum_msat;
    msg.feerate_per_kw = FeeRate;
    msg.to_self_delay = pChannel->establish.param.to_self_delay;
    msg.max_accepted_htlcs = pChannel->establish.param.max_accepted_htlcs;
    msg.p_funding_pubkey = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_FUNDING];
    msg.p_revocation_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_REVOCATION];
    msg.p_payment_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_PAYMENT];
    msg.p_delayed_payment_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_DELAYED];
    msg.p_htlc_basepoint = pChannel->keys_local.basepoints[LN_BASEPOINT_IDX_HTLC];
    msg.p_first_per_commitment_point = pChannel->keys_local.per_commitment_point;
    if (PrivChannel != 0) {
        LOGD("private channel\n");
        msg.channel_flags = 0;
    } else {
        msg.channel_flags = CHANNEL_FLAGS_ANNOCNL;
    }
    msg.shutdown_len = 0;
    msg.p_shutdown_scriptpubkey = NULL;
    utl_buf_t buf = UTL_BUF_INIT;
    ln_msg_open_channel_write(&buf, &msg);
    ln_callback(pChannel, LN_CB_TYPE_SEND_MESSAGE, &buf);
    utl_buf_free(&buf);

    pChannel->commit_info_local.dust_limit_sat = msg.dust_limit_satoshis;
    pChannel->commit_info_local.max_htlc_value_in_flight_msat = msg.max_htlc_value_in_flight_msat;
    pChannel->commit_info_local.channel_reserve_sat = msg.channel_reserve_satoshis;
    pChannel->commit_info_local.htlc_minimum_msat = msg.htlc_minimum_msat;
    pChannel->commit_info_local.max_accepted_htlcs = msg.max_accepted_htlcs;
    pChannel->commit_info_local.local_msat =
        pChannel->commit_info_remote.remote_msat =
        LN_SATOSHI2MSAT(msg.funding_satoshis) - msg.push_msat;
    pChannel->commit_info_local.remote_msat =
        pChannel->commit_info_remote.local_msat =
        msg.push_msat;
    pChannel->funding_info.funding_satoshis = msg.funding_satoshis;
    if (!ln_update_info_set_initial_fee_send(&pChannel->update_info, msg.feerate_per_kw)) return false;
    pChannel->commit_info_remote.to_self_delay = msg.to_self_delay;

    pChannel->funding_info.state =
        (ln_funding_state_t)(
            ((msg.channel_flags & CHANNEL_FLAGS_MASK) ? LN_FUNDING_STATE_STATE_NO_ANNO_CH : 0) |
            LN_FUNDING_STATE_STATE_FUNDING);
    pChannel->funding_info.role = LN_FUNDING_ROLE_FUNDER;
    return true;
}


bool HIDDEN ln_open_channel_recv(ln_channel_t *pChannel, const uint8_t *pData, uint16_t Len)
{
    LOGD("BEGIN\n");

    if (ln_funding_info_is_funder(&pChannel->funding_info, true)) {
        M_SET_ERR(pChannel, LNERR_INV_SIDE, "not fundee");
        return false;
    }
    if (ln_funding_info_funding_now(&pChannel->funding_info)) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already funding");
        LOGD("BUT! DO! NOTHING!\n");
        return true;
    }
    if (pChannel->short_channel_id != 0) {
        M_SET_ERR(pChannel, LNERR_ALREADY_FUNDING, "already established");
        return false;
    }

    ln_msg_open_channel_t msg;
    if (!ln_msg_open_channel_read(&msg, pData, Len)) {
        M_SET_ERR(pChannel, LNERR_MSG_READ, "read message");
        return false;
    }
    memcpy(pChannel->channel_id, msg.p_temporary_channel_id, LN_SZ_CHANNEL_ID);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_FUNDING], msg.p_funding_pubkey, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_REVOCATION], msg.p_revocation_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_PAYMENT], msg.p_payment_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_DELAYED], msg.p_delayed_payment_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.basepoints[LN_BASEPOINT_IDX_HTLC], msg.p_htlc_basepoint, BTC_SZ_PUBKEY);
    memcpy(pChannel->keys_remote.per_commitment_point, msg.p_first_per_commitment_point, BTC_SZ_PUBKEY);

{'fraction_non_alphanumeric': 0.14722206328317217, 'fraction_numerical': 0.004463008525490645, 'mean_word_length': 4.59296, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 105, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3258998', 'n_tokens_mistral': 6586, 'n_tokens_neox': 6255, 'n_words': 990}