packages feed

cardano-c-clib-0.1.1.0: vendor/src/transaction_builder/balancing/implicit_coin.c

/**
 * \file implicit_coin.c
 *
 * \author angel.castillo
 * \date   Nov 02, 2024
 *
 * Copyright 2024 Biglup Labs
 *
 * Licensed 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
 *
 *     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.
 */

/* INCLUDES ******************************************************************/

#include <cardano/certs/register_drep_cert.h>
#include <cardano/certs/registration_cert.h>
#include <cardano/certs/stake_registration_delegation_cert.h>
#include <cardano/certs/stake_vote_registration_delegation_cert.h>
#include <cardano/certs/unregister_drep_cert.h>
#include <cardano/certs/unregistration_cert.h>
#include <cardano/certs/vote_registration_delegation_cert.h>
#include <cardano/transaction_builder/balancing/implicit_coin.h>
#include <string.h>

#include "../../string_safe.h"
#include "internals/pool_deposits.h"

/* STATIC FUNCTIONS **********************************************************/

/**
 * \brief Adds a lovelace amount to an implicit coin accumulator.
 *
 * \param[in,out] accumulator A pointer to the accumulator. On failure it is left untouched.
 * \param[in]     amount      The lovelace amount to add.
 *
 * \return \ref CARDANO_SUCCESS if the amount was added, or \ref CARDANO_ERROR_INTEGER_OVERFLOW if the sum
 *         exceeds UINT64_MAX.
 */
static cardano_error_t
add_amount(uint64_t* accumulator, const uint64_t amount)
{
  if (amount > (UINT64_MAX - *accumulator))
  {
    return CARDANO_ERROR_INTEGER_OVERFLOW;
  }

  *accumulator += amount;

  return CARDANO_SUCCESS;
}

/**
 * \brief Accumulates the reward withdrawals of a body into the implicit coin.
 *
 * \param[in]  withdrawals   The withdrawal map of the body, or NULL when the body has none.
 * \param[out] implicit_coin The implicit coin accumulator to update.
 *
 * \return \ref CARDANO_SUCCESS if the withdrawals were accumulated, or an appropriate error code.
 */
static cardano_error_t
compute_withdrawals(
  cardano_withdrawal_map_t* withdrawals,
  cardano_implicit_coin_t*  implicit_coin)
{
  const size_t size = cardano_withdrawal_map_get_length(withdrawals);

  for (size_t i = 0U; i < size; ++i)
  {
    uint64_t amount = 0;

    cardano_error_t result = cardano_withdrawal_map_get_value_at(withdrawals, i, &amount);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    result = add_amount(&implicit_coin->withdrawals, amount);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Determines whether a pool registration certificate registers a pool for the first time in its certificate set.
 *
 * The ledger charges the pool deposit once per pool: a later registration of the same pool in the same set updates
 * the pool parameters and pays no deposit.
 *
 * \param[in]  certificates The certificate set holding the pool registration certificate.
 * \param[in]  index        The position of the pool registration certificate in the set.
 * \param[in]  certificate  The pool registration certificate at `index`.
 * \param[out] is_first     On success, `true` if no certificate before `index` registers the same pool; otherwise, `false`.
 *
 * \return \ref CARDANO_SUCCESS if the certificates were inspected, or an appropriate error code.
 */
static cardano_error_t
is_first_pool_registration(
  cardano_certificate_set_t* certificates,
  const size_t               index,
  cardano_certificate_t*     certificate,
  bool*                      is_first)
{
  cardano_blake2b_hash_t* operator_key_hash = NULL;

  cardano_error_t result = _cardano_get_pool_operator_key_hash(certificate, &operator_key_hash);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  *is_first = true;

  for (size_t i = 0U; (i < index) && *is_first && (result == CARDANO_SUCCESS); ++i)
  {
    cardano_certificate_t* previous = NULL;

    result = cardano_certificate_set_get(certificates, i, &previous);
    cardano_certificate_unref(&previous);

    cardano_cert_type_t type = CARDANO_CERT_TYPE_STAKE_REGISTRATION;

    if (result == CARDANO_SUCCESS)
    {
      result = cardano_cert_get_type(previous, &type);
    }

    if ((result == CARDANO_SUCCESS) && (type == CARDANO_CERT_TYPE_POOL_REGISTRATION))
    {
      cardano_blake2b_hash_t* previous_operator_key_hash = NULL;

      result    = _cardano_get_pool_operator_key_hash(previous, &previous_operator_key_hash);
      *is_first = !cardano_blake2b_hash_equals(operator_key_hash, previous_operator_key_hash);

      cardano_blake2b_hash_unref(&previous_operator_key_hash);
    }
  }

  cardano_blake2b_hash_unref(&operator_key_hash);

  return result;
}

/**
 * \brief Accumulates the deposits and refunds of the Shelley era certificates into the implicit coin.
 *
 * Shelley era certificates do not carry their deposit, so the amounts are taken from the protocol parameters. A pool
 * registration pays the pool deposit unless the same pool is registered earlier in the set, and a pool retirement
 * reclaims nothing, as the ledger returns the pool deposit when the pool retires at an epoch boundary.
 *
 * \param[in]  certificates  The certificate set of the body, or NULL when the body has none.
 * \param[in]  pool_deposit  The pool deposit from the protocol parameters.
 * \param[in]  stake_deposit The stake key deposit from the protocol parameters.
 * \param[out] implicit_coin The implicit coin accumulator to update.
 *
 * \return \ref CARDANO_SUCCESS if the deposits were accumulated, or an appropriate error code.
 */
static cardano_error_t
compute_shelley_deposits(
  cardano_certificate_set_t* certificates,
  const uint64_t             pool_deposit,
  const uint64_t             stake_deposit,
  cardano_implicit_coin_t*   implicit_coin)
{
  const size_t size = cardano_certificate_set_get_length(certificates);

  // Remark: For the case of deregistration (CARDANO_CERT_TYPE_STAKE_DEREGISTRATION) the code here is not entirely correct
  // as we are assuming the current protocol parameters for the deposits where the same as the ones used when the certificates where issued.
  // This is going to work for now, but to properly implement this we need a way to know when the certificate we are undoing was originally issued
  // and get the protocol parameters for that epoch. However, these parameters in particular have never changed in mainnet and these certificates will be deprecated,
  // so this is probably good for now.
  for (size_t i = 0U; i < size; ++i)
  {
    cardano_certificate_t* certificate = NULL;

    cardano_error_t result = cardano_certificate_set_get(certificates, i, &certificate);
    cardano_certificate_unref(&certificate);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    cardano_cert_type_t type;

    result = cardano_cert_get_type(certificate, &type);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    switch (type)
    {
      case CARDANO_CERT_TYPE_STAKE_REGISTRATION:
      {
        result = add_amount(&implicit_coin->deposits, stake_deposit);
        break;
      }
      case CARDANO_CERT_TYPE_STAKE_DEREGISTRATION:
      {
        result = add_amount(&implicit_coin->reclaim_deposits, stake_deposit);
        break;
      }
      case CARDANO_CERT_TYPE_POOL_REGISTRATION:
      {
        bool is_first = false;

        result = is_first_pool_registration(certificates, i, certificate, &is_first);

        if ((result == CARDANO_SUCCESS) && is_first)
        {
          result = add_amount(&implicit_coin->deposits, pool_deposit);
        }

        break;
      }
      default:
      {
        continue;
      }
    }

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Accumulates the deposits and refunds of the Conway era certificates and proposals into the implicit coin.
 *
 * Conway era certificates and governance proposals carry their own deposit amount.
 *
 * \param[in]  certificates        The certificate set of the body, or NULL when the body has none.
 * \param[in]  proposal_procedures The proposal procedure set of the body, or NULL when the body has none.
 * \param[out] implicit_coin       The implicit coin accumulator to update.
 *
 * \return \ref CARDANO_SUCCESS if the deposits were accumulated, or an appropriate error code.
 */
static cardano_error_t
compute_conway_deposits(
  cardano_certificate_set_t*        certificates,
  cardano_proposal_procedure_set_t* proposal_procedures,
  cardano_implicit_coin_t*          implicit_coin)
{
  const size_t size = cardano_certificate_set_get_length(certificates);

  for (size_t i = 0U; i < size; ++i)
  {
    cardano_certificate_t* certificate = NULL;

    cardano_error_t result = cardano_certificate_set_get(certificates, i, &certificate);
    cardano_certificate_unref(&certificate);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    cardano_cert_type_t type;

    result = cardano_cert_get_type(certificate, &type);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    switch (type)
    {
      case CARDANO_CERT_TYPE_REGISTRATION:
      {
        cardano_registration_cert_t* registration = NULL;
        result                                    = cardano_certificate_to_registration(certificate, &registration);
        cardano_registration_cert_unref(&registration);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->deposits, cardano_registration_cert_get_deposit(registration));

        break;
      }
      case CARDANO_CERT_TYPE_STAKE_REGISTRATION_DELEGATION:
      {
        cardano_stake_registration_delegation_cert_t* stake_registration = NULL;
        result                                                           = cardano_certificate_to_stake_registration_delegation(certificate, &stake_registration);
        cardano_stake_registration_delegation_cert_unref(&stake_registration);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->deposits, cardano_stake_registration_delegation_cert_get_deposit(stake_registration));

        break;
      }
      case CARDANO_CERT_TYPE_VOTE_REGISTRATION_DELEGATION:
      {
        cardano_vote_registration_delegation_cert_t* vote_registration = NULL;
        result                                                         = cardano_certificate_to_vote_registration_delegation(certificate, &vote_registration);
        cardano_vote_registration_delegation_cert_unref(&vote_registration);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->deposits, cardano_vote_registration_delegation_cert_get_deposit(vote_registration));

        break;
      }
      case CARDANO_CERT_TYPE_STAKE_VOTE_REGISTRATION_DELEGATION:
      {
        cardano_stake_vote_registration_delegation_cert_t* stake_vote_registration = NULL;
        result                                                                     = cardano_certificate_to_stake_vote_registration_delegation(certificate, &stake_vote_registration);
        cardano_stake_vote_registration_delegation_cert_unref(&stake_vote_registration);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->deposits, cardano_stake_vote_registration_delegation_cert_get_deposit(stake_vote_registration));

        break;
      }
      case CARDANO_CERT_TYPE_UNREGISTRATION:
      {
        cardano_unregistration_cert_t* unregistration = NULL;
        result                                        = cardano_certificate_to_unregistration(certificate, &unregistration);
        cardano_unregistration_cert_unref(&unregistration);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->reclaim_deposits, cardano_unregistration_cert_get_deposit(unregistration));

        break;
      }
      case CARDANO_CERT_TYPE_DREP_REGISTRATION:
      {
        cardano_register_drep_cert_t* register_drep = NULL;
        result                                      = cardano_certificate_to_register_drep(certificate, &register_drep);
        cardano_register_drep_cert_unref(&register_drep);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->deposits, cardano_register_drep_cert_get_deposit(register_drep));

        break;
      }
      case CARDANO_CERT_TYPE_DREP_UNREGISTRATION:
      {
        cardano_unregister_drep_cert_t* unregister_drep = NULL;
        result                                          = cardano_certificate_to_unregister_drep(certificate, &unregister_drep);
        cardano_unregister_drep_cert_unref(&unregister_drep);

        if (result != CARDANO_SUCCESS)
        {
          return result;
        }

        result = add_amount(&implicit_coin->reclaim_deposits, cardano_unregister_drep_cert_get_deposit(unregister_drep));

        break;
      }
      default:
      {
        continue;
      }
    }

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  const size_t proposal_size = cardano_proposal_procedure_set_get_length(proposal_procedures);

  for (size_t i = 0U; i < proposal_size; ++i)
  {
    cardano_proposal_procedure_t* proposal_procedure = NULL;

    cardano_error_t result = cardano_proposal_procedure_set_get(proposal_procedures, i, &proposal_procedure);
    cardano_proposal_procedure_unref(&proposal_procedure);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    result = add_amount(&implicit_coin->deposits, cardano_proposal_procedure_get_deposit(proposal_procedure));

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Computes the implicit coin from the certificates, withdrawals and proposals of a body.
 *
 * \param[in]  certificates        The certificate set of the body, or NULL when the body has none.
 * \param[in]  withdrawals         The withdrawal map of the body, or NULL when the body has none.
 * \param[in]  proposal_procedures The proposal procedure set of the body, or NULL when the body has none.
 * \param[in]  protocol_params     The protocol parameters supplying the Shelley era deposit amounts.
 * \param[out] implicit_coin       The implicit coin accumulator to update.
 *
 * \return \ref CARDANO_SUCCESS if the implicit coin was computed, or an appropriate error code.
 */
static cardano_error_t
compute_implicit_coin(
  cardano_certificate_set_t*        certificates,
  cardano_withdrawal_map_t*         withdrawals,
  cardano_proposal_procedure_set_t* proposal_procedures,
  cardano_protocol_parameters_t*    protocol_params,
  cardano_implicit_coin_t*          implicit_coin)
{
  const uint64_t pool_deposit  = cardano_protocol_parameters_get_pool_deposit(protocol_params);
  const uint64_t stake_deposit = cardano_protocol_parameters_get_key_deposit(protocol_params);

  cardano_error_t result = compute_withdrawals(withdrawals, implicit_coin);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  result = compute_shelley_deposits(certificates, pool_deposit, stake_deposit, implicit_coin);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  result = compute_conway_deposits(certificates, proposal_procedures, implicit_coin);

  return result;
}

/* IMPLEMENTATION ************************************************************/

cardano_error_t
cardano_compute_implicit_coin(
  cardano_transaction_t*         tx,
  cardano_protocol_parameters_t* protocol_params,
  cardano_implicit_coin_t*       implicit_coin)
{
  if (tx == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  if (protocol_params == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  if (implicit_coin == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_certificate_set_t* certificates = cardano_transaction_body_get_certificates(body);
  cardano_certificate_set_unref(&certificates);

  cardano_withdrawal_map_t* withdrawals = cardano_transaction_body_get_withdrawals(body);
  cardano_withdrawal_map_unref(&withdrawals);

  cardano_proposal_procedure_set_t* proposal_procedures = cardano_transaction_body_get_proposal_procedures(body);
  cardano_proposal_procedure_set_unref(&proposal_procedures);

  return compute_implicit_coin(certificates, withdrawals, proposal_procedures, protocol_params, implicit_coin);
}

cardano_error_t
cardano_compute_sub_transaction_implicit_coin(
  cardano_sub_transaction_t*     sub_tx,
  cardano_protocol_parameters_t* protocol_params,
  cardano_implicit_coin_t*       implicit_coin)
{
  if (sub_tx == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  if (protocol_params == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  if (implicit_coin == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  cardano_sub_transaction_body_t* body = cardano_sub_transaction_get_body(sub_tx);
  cardano_sub_transaction_body_unref(&body);

  cardano_certificate_set_t* certificates = cardano_sub_transaction_body_get_certificates(body);
  cardano_certificate_set_unref(&certificates);

  cardano_withdrawal_map_t* withdrawals = cardano_sub_transaction_body_get_withdrawals(body);
  cardano_withdrawal_map_unref(&withdrawals);

  cardano_proposal_procedure_set_t* proposal_procedures = cardano_sub_transaction_body_get_proposal_procedures(body);
  cardano_proposal_procedure_set_unref(&proposal_procedures);

  return compute_implicit_coin(certificates, withdrawals, proposal_procedures, protocol_params, implicit_coin);
}