Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add estimate_fee_rate rpc #4465

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions rpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1.
* [Module Pool](#module-pool) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Pool&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/json/pool_rpc_doc.json)

* [Method `send_transaction`](#pool-send_transaction)
* [Method `estimate_fee_rate`](#pool-estimate_fee_rate)
* [Method `test_tx_pool_accept`](#pool-test_tx_pool_accept)
* [Method `remove_transaction`](#pool-remove_transaction)
* [Method `tx_pool_info`](#pool-tx_pool_info)
Expand Down Expand Up @@ -4422,6 +4423,53 @@ Response
}
```

<a id="pool-estimate_fee_rate"></a>
#### Method `estimate_fee_rate`
* `estimate_fee_rate(target_to_be_committed)`
* `target_to_be_committed`: [`Uint64`](#type-uint64)
* result: [`Uint64`](#type-uint64)

Estimate fee rate for a transaction to be committed within target block number by using a simple strategy.

Since CKB transaction confirmation involves a two-step process—1) propose and 2) commit, it is complex to
predict the transaction fee accurately with the expectation that it will be included within a certain block height.

This method relies on two assumptions and uses a simple strategy to estimate the transaction fee: 1) all transactions
in the pool are waiting to be proposed, and 2) no new transactions will be added to the pool.

In practice, this simple method should achieve good accuracy fee rate and running performance.

###### Params

* `target_to_be_committed` - The target block number to be committed, minimum value is 3 and maximum value is 131.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rpc parameter target_to_be_committed is limited to 3~131, because the minimum value of the proposal window is 2, which is equivalent to predicting the height of current_tip + 1 ~ 128.

128+2=130


###### Returns

The estimated fee rate in shannons per kilobyte.

###### Examples

```json
{
"id": 42,
"jsonrpc": "2.0",
"method": "estimate_fee_rate",
"params": [
"0x4"
]
}
```

Response

```json
{
"id": 42,
"jsonrpc": "2.0",
"result": "0x3e8"
}
```

<a id="pool-test_tx_pool_accept"></a>
#### Method `test_tx_pool_accept`
* `test_tx_pool_accept(tx, outputs_validator)`
Expand Down
65 changes: 64 additions & 1 deletion rpc/src/module/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use async_trait::async_trait;
use ckb_chain_spec::consensus::Consensus;
use ckb_constant::hardfork::{mainnet, testnet};
use ckb_jsonrpc_types::{
EntryCompleted, OutputsValidator, PoolTxDetailInfo, RawTxPool, Script, Transaction, TxPoolInfo,
BlockNumber, EntryCompleted, OutputsValidator, PoolTxDetailInfo, RawTxPool, Script,
Transaction, TxPoolInfo, Uint64,
};
use ckb_logger::error;
use ckb_shared::shared::Shared;
Expand Down Expand Up @@ -110,6 +111,50 @@ pub trait PoolRpc {
outputs_validator: Option<OutputsValidator>,
) -> Result<H256>;

/// Estimate fee rate for a transaction to be committed within target block number by using a simple strategy.
///
/// Since CKB transaction confirmation involves a two-step process—1) propose and 2) commit, it is complex to
/// predict the transaction fee accurately with the expectation that it will be included within a certain block height.
///
/// This method relies on two assumptions and uses a simple strategy to estimate the transaction fee: 1) all transactions
/// in the pool are waiting to be proposed, and 2) no new transactions will be added to the pool.
///
/// In practice, this simple method should achieve good accuracy fee rate and running performance.
///
/// ## Params
///
/// * `target_to_be_committed` - The target block number to be committed, minimum value is 3 and maximum value is 131.
///
/// ## Returns
///
/// The estimated fee rate in shannons per kilobyte.
///
/// ## Examples
///
/// ```json
/// {
/// "id": 42,
/// "jsonrpc": "2.0",
/// "method": "estimate_fee_rate",
/// "params": [
/// "0x4"
/// ]
/// }
/// ```
///
/// Response
///
/// ```json
/// {
/// "id": 42,
/// "jsonrpc": "2.0",
/// "result": "0x3e8"
/// }
/// ```
///
#[rpc(name = "estimate_fee_rate")]
fn estimate_fee_rate(&self, target_to_be_committed: BlockNumber) -> Result<Uint64>;

/// Test if a transaction can be accepted by the transaction pool without inserting it into the pool or rebroadcasting it to peers.
/// The parameters and errors of this method are the same as `send_transaction`.
///
Expand Down Expand Up @@ -604,6 +649,24 @@ impl PoolRpc for PoolRpcImpl {
}
}

fn estimate_fee_rate(&self, target_to_be_committed: BlockNumber) -> Result<Uint64> {
let target_to_be_committed = target_to_be_committed.value();
if !(3..=131).contains(&target_to_be_committed) {
return Err(RPCError::invalid_params(
"target to be committed block number must be in range [3, 131]",
));
}
let fee_rate = self
.shared
.tx_pool_controller()
.estimate_fee_rate(target_to_be_committed)
.map_err(|e| {
error!("Send estimate_fee_rate request error {}", e);
RPCError::ckb_internal_error(e)
})?;
Ok(fee_rate.as_u64().into())
}

fn test_tx_pool_accept(
&self,
tx: Transaction,
Expand Down
29 changes: 28 additions & 1 deletion tx-pool/src/component/pool_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::error::Reject;
use crate::TxEntry;
use ckb_logger::{debug, error, trace};
use ckb_types::core::error::OutPointError;
use ckb_types::core::Cycle;
use ckb_types::core::{Cycle, FeeRate};
use ckb_types::packed::OutPoint;
use ckb_types::prelude::*;
use ckb_types::{
Expand Down Expand Up @@ -329,6 +329,33 @@ impl PoolMap {
conflicts
}

pub(crate) fn estimate_fee_rate(
&self,
mut target_blocks: usize,
max_block_bytes: usize,
max_block_cycles: Cycle,
min_fee_rate: FeeRate,
) -> FeeRate {
debug_assert!(target_blocks > 0);
let iter = self.entries.iter_by_score().rev();
let mut current_block_bytes = 0;
let mut current_block_cycles = 0;
for entry in iter {
current_block_bytes += entry.inner.size;
current_block_cycles += entry.inner.cycles;
if current_block_bytes >= max_block_bytes || current_block_cycles >= max_block_cycles {
target_blocks -= 1;
if target_blocks == 0 {
return entry.inner.fee_rate();
}
current_block_bytes = entry.inner.size;
current_block_cycles = entry.inner.cycles;
}
}

min_fee_rate
chenyukang marked this conversation as resolved.
Show resolved Hide resolved
}

// find the pending txs sorted by score, and return their proposal short ids
pub(crate) fn get_proposals(
&self,
Expand Down
56 changes: 56 additions & 0 deletions tx-pool/src/component/tests/estimate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use crate::component::tests::util::build_tx;
use crate::component::{
entry::TxEntry,
pool_map::{PoolMap, Status},
};
use ckb_types::core::{Capacity, Cycle, FeeRate};

#[test]
fn test_estimate_fee_rate() {
let mut pool = PoolMap::new(1000);
for i in 0..1024 {
let tx = build_tx(vec![(&Default::default(), i as u32)], 1);
let entry = TxEntry::dummy_resolve(tx, i + 1, Capacity::shannons(i + 1), 1000);
pool.add_entry(entry, Status::Pending).unwrap();
}

assert_eq!(
FeeRate::from_u64(42),
pool.estimate_fee_rate(1, usize::MAX, Cycle::MAX, FeeRate::from_u64(42))
);

assert_eq!(
FeeRate::from_u64(1024),
pool.estimate_fee_rate(1, 1000, Cycle::MAX, FeeRate::from_u64(1))
);
assert_eq!(
FeeRate::from_u64(1023),
pool.estimate_fee_rate(1, 2000, Cycle::MAX, FeeRate::from_u64(1))
);
assert_eq!(
FeeRate::from_u64(1016),
pool.estimate_fee_rate(2, 5000, Cycle::MAX, FeeRate::from_u64(1))
);

assert_eq!(
FeeRate::from_u64(1024),
pool.estimate_fee_rate(1, usize::MAX, 1, FeeRate::from_u64(1))
);
assert_eq!(
FeeRate::from_u64(1023),
pool.estimate_fee_rate(1, usize::MAX, 2047, FeeRate::from_u64(1))
);
assert_eq!(
FeeRate::from_u64(1015),
pool.estimate_fee_rate(2, usize::MAX, 5110, FeeRate::from_u64(1))
);

assert_eq!(
FeeRate::from_u64(624),
pool.estimate_fee_rate(100, 5000, 5110, FeeRate::from_u64(1))
);
assert_eq!(
FeeRate::from_u64(1),
pool.estimate_fee_rate(1000, 5000, 5110, FeeRate::from_u64(1))
);
}
1 change: 1 addition & 0 deletions tx-pool/src/component/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod chunk;
mod entry;
mod estimate;
mod links;
mod orphan;
mod pending;
Expand Down
12 changes: 11 additions & 1 deletion tx-pool/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use ckb_logger::{debug, error, warn};
use ckb_snapshot::Snapshot;
use ckb_store::ChainStore;
use ckb_types::core::tx_pool::PoolTxDetailInfo;
use ckb_types::core::CapacityError;
use ckb_types::core::{BlockNumber, CapacityError, FeeRate};
use ckb_types::packed::OutPoint;
use ckb_types::{
core::{
Expand Down Expand Up @@ -528,6 +528,16 @@ impl TxPool {
(entries, size, cycles)
}

pub(crate) fn estimate_fee_rate(&self, target_to_be_committed: BlockNumber) -> FeeRate {
self.pool_map.estimate_fee_rate(
(target_to_be_committed - self.snapshot.consensus().tx_proposal_window().closest())
as usize,
self.snapshot.consensus().max_block_bytes() as usize,
self.snapshot.consensus().max_block_cycles(),
self.config.min_fee_rate,
)
}

pub(crate) fn check_rbf(
&self,
snapshot: &Snapshot,
Expand Down
6 changes: 6 additions & 0 deletions tx-pool/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use ckb_snapshot::Snapshot;
use ckb_store::data_loader_wrapper::AsDataLoader;
use ckb_store::ChainStore;
use ckb_types::core::error::OutPointError;
use ckb_types::core::{BlockNumber, FeeRate};
use ckb_types::{
core::{cell::ResolvedTransaction, BlockView, Capacity, Cycle, HeaderView, TransactionView},
packed::{Byte32, ProposalShortId},
Expand Down Expand Up @@ -339,6 +340,11 @@ impl TxPoolService {
}
}

pub(crate) async fn estimate_fee_rate(&self, target_to_be_committed: BlockNumber) -> FeeRate {
let pool = self.tx_pool.read().await;
pool.estimate_fee_rate(target_to_be_committed)
}

pub(crate) async fn test_accept_tx(&self, tx: TransactionView) -> Result<Completed, Reject> {
// non contextual verify first
self.non_contextual_verify(&tx, None)?;
Expand Down
19 changes: 19 additions & 0 deletions tx-pool/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use ckb_network::{NetworkController, PeerIndex};
use ckb_snapshot::Snapshot;
use ckb_stop_handler::new_tokio_exit_rx;
use ckb_types::core::tx_pool::{EntryCompleted, PoolTxDetailInfo, TransactionWithStatus, TxStatus};
use ckb_types::core::{BlockNumber, FeeRate};
use ckb_types::{
core::{
tx_pool::{Reject, TxPoolEntryInfo, TxPoolIds, TxPoolInfo, TRANSACTION_SIZE_LIMIT},
Expand Down Expand Up @@ -91,6 +92,7 @@ pub(crate) enum Message {
BlockTemplate(Request<BlockTemplateArgs, BlockTemplateResult>),
SubmitLocalTx(Request<TransactionView, SubmitTxResult>),
RemoveLocalTx(Request<Byte32, bool>),
EstimateFeeRate(Request<BlockNumber, FeeRate>),
TestAcceptTx(Request<TransactionView, TestAcceptTxResult>),
SubmitRemoteTx(Request<(TransactionView, Cycle, PeerIndex), ()>),
NotifyTxs(Notify<Vec<TransactionView>>),
Expand Down Expand Up @@ -228,6 +230,14 @@ impl TxPoolController {
send_message!(self, SubmitLocalTx, tx)
}

/// Estimate fee rate for a transaction to be committed within target block number by using a simple strategy
pub fn estimate_fee_rate(
&self,
target_to_be_committed: BlockNumber,
) -> Result<FeeRate, AnyError> {
send_message!(self, EstimateFeeRate, target_to_be_committed)
}

/// test if a tx can be accepted by tx-pool
/// Won't be broadcasted to network
/// won't be insert to tx-pool
Expand Down Expand Up @@ -706,6 +716,15 @@ async fn process(mut service: TxPoolService, message: Message) {
error!("Responder sending remove_tx result failed {:?}", e);
};
}
Message::EstimateFeeRate(Request {
responder,
arguments: target_to_be_committed,
}) => {
let fee_rate = service.estimate_fee_rate(target_to_be_committed).await;
if let Err(e) = responder.send(fee_rate) {
error!("Responder sending estimate_fee_rate failed {:?}", e);
};
}
Message::TestAcceptTx(Request {
responder,
arguments: tx,
Expand Down
Loading