Skip to content

Commit

Permalink
WIP - decoupling RPC type aliases (kaspanet#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
aspect authored Jun 29, 2024
1 parent fd8d23d commit 274c866
Show file tree
Hide file tree
Showing 17 changed files with 640 additions and 84 deletions.
6 changes: 6 additions & 0 deletions consensus/core/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ impl Header {
}
}

impl AsRef<Header> for Header {
fn as_ref(&self) -> &Header {
self
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
22 changes: 11 additions & 11 deletions rothschild/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use kaspa_consensus_core::{
use kaspa_core::{info, kaspad_env::version, time::unix_now, warn};
use kaspa_grpc_client::{ClientPool, GrpcClient};
use kaspa_notify::subscription::context::SubscriptionContext;
use kaspa_rpc_core::{api::rpc::RpcApi, notify::mode::NotificationMode};
use kaspa_rpc_core::{api::rpc::RpcApi, notify::mode::NotificationMode, RpcUtxoEntry};
use kaspa_txscript::pay_to_address_script;
use parking_lot::Mutex;
use rayon::prelude::*;
Expand Down Expand Up @@ -323,7 +323,7 @@ async fn populate_pending_outpoints_from_mempool(
for entry in entries {
for entry in entry.sending {
for input in entry.transaction.inputs {
pending_outpoints.insert(input.previous_outpoint, now);
pending_outpoints.insert(input.previous_outpoint.into(), now);
}
}
}
Expand All @@ -337,20 +337,20 @@ async fn fetch_spendable_utxos(
) -> Vec<(TransactionOutpoint, UtxoEntry)> {
let resp = rpc_client.get_utxos_by_addresses(vec![kaspa_addr]).await.unwrap();
let dag_info = rpc_client.get_block_dag_info().await.unwrap();
let mut utxos = Vec::with_capacity(resp.len());
for resp_entry in resp
.into_iter()
.filter(|resp_entry| is_utxo_spendable(&resp_entry.utxo_entry, dag_info.virtual_daa_score, coinbase_maturity))

let mut utxos = resp.into_iter()
.filter(|entry| {
is_utxo_spendable(&entry.utxo_entry, dag_info.virtual_daa_score, coinbase_maturity)
})
.map(|entry| (TransactionOutpoint::from(entry.outpoint), UtxoEntry::from(entry.utxo_entry)))
// Eliminates UTXOs we already tried to spend so we don't try to spend them again in this period
.filter(|utxo| !pending.contains_key(&utxo.outpoint))
{
utxos.push((resp_entry.outpoint, resp_entry.utxo_entry));
}
.filter(|(outpoint,_)| !pending.contains_key(outpoint))
.collect::<Vec<_>>();
utxos.sort_by(|a, b| b.1.amount.cmp(&a.1.amount));
utxos
}

fn is_utxo_spendable(entry: &UtxoEntry, virtual_daa_score: u64, coinbase_maturity: u64) -> bool {
fn is_utxo_spendable(entry: &RpcUtxoEntry, virtual_daa_score: u64, coinbase_maturity: u64) -> bool {
let needed_confs = if !entry.is_coinbase {
10
} else {
Expand Down
2 changes: 1 addition & 1 deletion rpc/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ hex.workspace = true
js-sys.workspace = true
log.workspace = true
paste.workspace = true
rand.workspace = true
serde-wasm-bindgen.workspace = true
serde.workspace = true
smallvec.workspace = true
Expand All @@ -51,7 +52,6 @@ wasm-bindgen.workspace = true
workflow-core.workspace = true
workflow-serializer.workspace = true
workflow-wasm.workspace = true
rand.workspace = true

[dev-dependencies]
serde_json.workspace = true
Expand Down
6 changes: 3 additions & 3 deletions rpc/core/src/convert/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use kaspa_consensus_core::block::{Block, MutableBlock};
impl From<&Block> for RpcBlock {
fn from(item: &Block) -> Self {
Self {
header: (*item.header).clone(),
header: item.header.as_ref().into(),
transactions: item.transactions.iter().map(RpcTransaction::from).collect(),
// TODO: Implement a populating process inspired from kaspad\app\rpc\rpccontext\verbosedata.go
verbose_data: None,
Expand All @@ -21,7 +21,7 @@ impl From<&Block> for RpcBlock {
impl From<&MutableBlock> for RpcBlock {
fn from(item: &MutableBlock) -> Self {
Self {
header: item.header.clone(),
header: item.header.as_ref().into(),
transactions: item.transactions.iter().map(RpcTransaction::from).collect(),
verbose_data: None,
}
Expand All @@ -36,7 +36,7 @@ impl TryFrom<&RpcBlock> for Block {
type Error = RpcError;
fn try_from(item: &RpcBlock) -> RpcResult<Self> {
Ok(Self {
header: Arc::new(item.header.clone()),
header: Arc::new(item.header.as_ref().into()),
transactions: Arc::new(
item.transactions
.iter()
Expand Down
4 changes: 2 additions & 2 deletions rpc/core/src/convert/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl From<&TransactionOutput> for RpcTransactionOutput {
impl From<&TransactionInput> for RpcTransactionInput {
fn from(item: &TransactionInput) -> Self {
Self {
previous_outpoint: item.previous_outpoint,
previous_outpoint: item.previous_outpoint.into(),
signature_script: item.signature_script.clone(),
sequence: item.sequence,
sig_op_count: item.sig_op_count,
Expand Down Expand Up @@ -83,6 +83,6 @@ impl TryFrom<&RpcTransactionOutput> for TransactionOutput {
impl TryFrom<&RpcTransactionInput> for TransactionInput {
type Error = RpcError;
fn try_from(item: &RpcTransactionInput) -> RpcResult<Self> {
Ok(Self::new(item.previous_outpoint, item.signature_script.clone(), item.sequence, item.sig_op_count))
Ok(Self::new(item.previous_outpoint.into(), item.signature_script.clone(), item.sequence, item.sig_op_count))
}
}
6 changes: 3 additions & 3 deletions rpc/core/src/convert/utxo.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::RpcUtxoEntry;
use crate::RpcUtxosByAddressesEntry;
use kaspa_addresses::Prefix;
use kaspa_consensus_core::tx::UtxoEntry;
use kaspa_index_core::indexed_utxos::UtxoSetByScriptPublicKey;
use kaspa_txscript::extract_script_pub_key_address;

Expand All @@ -16,8 +16,8 @@ pub fn utxo_set_into_rpc(item: &UtxoSetByScriptPublicKey, prefix: Option<Prefix>
.iter()
.map(|(outpoint, entry)| RpcUtxosByAddressesEntry {
address: address.clone(),
outpoint: *outpoint,
utxo_entry: UtxoEntry::new(entry.amount, script_public_key.clone(), entry.block_daa_score, entry.is_coinbase),
outpoint: (*outpoint).into(),
utxo_entry: RpcUtxoEntry::new(entry.amount, script_public_key.clone(), entry.block_daa_score, entry.is_coinbase),
})
.collect::<Vec<_>>()
})
Expand Down
38 changes: 35 additions & 3 deletions rpc/core/src/model/address.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,56 @@
use crate::{RpcTransactionOutpoint, RpcUtxoEntry};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use workflow_serializer::prelude::*;

pub type RpcAddress = kaspa_addresses::Address;

/// Represents a UTXO entry of an address returned by the `GetUtxosByAddresses` RPC.
#[derive(Clone, Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcUtxosByAddressesEntry {
pub address: Option<RpcAddress>,
pub outpoint: RpcTransactionOutpoint,
pub utxo_entry: RpcUtxoEntry,
}

impl Serializer for RpcUtxosByAddressesEntry {
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
store!(u8, &1, writer)?; // version
store!(Option<RpcAddress>, &self.address, writer)?;
serialize!(RpcTransactionOutpoint, &self.outpoint, writer)?;
serialize!(RpcUtxoEntry, &self.utxo_entry, writer)
}

fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
let _version: u8 = load!(u8, reader)?;
let address = load!(Option<RpcAddress>, reader)?;
let outpoint = deserialize!(RpcTransactionOutpoint, reader)?;
let utxo_entry = deserialize!(RpcUtxoEntry, reader)?;
Ok(Self { address, outpoint, utxo_entry })
}
}

/// Represents a balance of an address returned by the `GetBalancesByAddresses` RPC.
#[derive(Clone, Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcBalancesByAddressesEntry {
pub address: RpcAddress,

/// Balance of `address` if available
pub balance: Option<u64>,
}

impl Serializer for RpcBalancesByAddressesEntry {
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
store!(u8, &1, writer)?; // version
store!(RpcAddress, &self.address, writer)?;
store!(Option<u64>, &self.balance, writer)
}

fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
let _version: u8 = load!(u8, reader)?;
let address = load!(RpcAddress, reader)?;
let balance = load!(Option<u64>, reader)?;
Ok(Self { address, balance })
}
}
71 changes: 68 additions & 3 deletions rpc/core/src/model/block.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
use crate::prelude::{RpcHash, RpcHeader, RpcTransaction};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use workflow_serializer::prelude::*;

#[derive(Clone, Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcBlock {
pub header: RpcHeader,
pub transactions: Vec<RpcTransaction>,
pub verbose_data: Option<RpcBlockVerboseData>,
}

#[derive(Clone, Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
impl Serializer for RpcBlock {
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
store!(u32, &1, writer)?;
serialize!(RpcHeader, &self.header, writer)?;
serialize!(Vec<RpcTransaction>, &self.transactions, writer)?;
serialize!(Option<RpcBlockVerboseData>, &self.verbose_data, writer)?;

Ok(())
}

fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
let _version = load!(u32, reader)?;
let header = deserialize!(RpcHeader, reader)?;
let transactions = deserialize!(Vec<RpcTransaction>, reader)?;
let verbose_data = deserialize!(Option<RpcBlockVerboseData>, reader)?;

Ok(Self { header, transactions, verbose_data })
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcBlockVerboseData {
pub hash: RpcHash,
Expand All @@ -25,6 +45,51 @@ pub struct RpcBlockVerboseData {
pub is_chain_block: bool,
}

impl Serializer for RpcBlockVerboseData {
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
store!(u8, &1, writer)?;
store!(RpcHash, &self.hash, writer)?;
store!(f64, &self.difficulty, writer)?;
store!(RpcHash, &self.selected_parent_hash, writer)?;
store!(Vec<RpcHash>, &self.transaction_ids, writer)?;
store!(bool, &self.is_header_only, writer)?;
store!(u64, &self.blue_score, writer)?;
store!(Vec<RpcHash>, &self.children_hashes, writer)?;
store!(Vec<RpcHash>, &self.merge_set_blues_hashes, writer)?;
store!(Vec<RpcHash>, &self.merge_set_reds_hashes, writer)?;
store!(bool, &self.is_chain_block, writer)?;

Ok(())
}

fn deserialize<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
let _version = load!(u8, reader)?;
let hash = load!(RpcHash, reader)?;
let difficulty = load!(f64, reader)?;
let selected_parent_hash = load!(RpcHash, reader)?;
let transaction_ids = load!(Vec<RpcHash>, reader)?;
let is_header_only = load!(bool, reader)?;
let blue_score = load!(u64, reader)?;
let children_hashes = load!(Vec<RpcHash>, reader)?;
let merge_set_blues_hashes = load!(Vec<RpcHash>, reader)?;
let merge_set_reds_hashes = load!(Vec<RpcHash>, reader)?;
let is_chain_block = load!(bool, reader)?;

Ok(Self {
hash,
difficulty,
selected_parent_hash,
transaction_ids,
is_header_only,
blue_score,
children_hashes,
merge_set_blues_hashes,
merge_set_reds_hashes,
is_chain_block,
})
}
}

cfg_if::cfg_if! {
if #[cfg(feature = "wasm32-sdk")] {
use wasm_bindgen::prelude::*;
Expand Down
Loading

0 comments on commit 274c866

Please sign in to comment.