Skip to content

Commit

Permalink
Update getrollout method
Browse files Browse the repository at this point in the history
Incorporate changes from PR #20
Closes #19
Co-authored-by: Alex Tsokurov <[email protected]>
  • Loading branch information
buffrr committed Nov 17, 2024
1 parent 524ce01 commit 8f1edf7
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 63 deletions.
49 changes: 7 additions & 42 deletions node/src/bin/space-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use protocol::{
bitcoin::{Amount, FeeRate, OutPoint, Txid},
hasher::{KeyHasher},
slabel::SLabel,
Covenant, FullSpaceOut,
};
use serde::{Deserialize, Serialize};
use spaced::{
Expand Down Expand Up @@ -153,8 +152,8 @@ enum Commands {
#[command(name = "balance")]
Balance,
/// Pre-create outputs that can be auctioned off during the bidding process
#[command(name = "createbidout")]
CreateBidOut {
#[command(name = "createbidouts")]
CreateBidOuts {
/// Number of output pairs to create
/// Each pair can be used to make a bid
pairs: u8,
Expand All @@ -177,8 +176,8 @@ enum Commands {
outpoint: OutPoint,
},
/// Get the estimated rollout batch for the specified interval
#[command(name = "getrolloutestimate")]
GetRolloutEstimate {
#[command(name = "getrollout")]
GetRollout {
// Get the estimated rollout for the target interval. Every ~144 blocks (a rollout interval),
// 10 spaces are released for auction. Specify 0 [default] for the coming interval, 1
// for the interval after and so on.
Expand Down Expand Up @@ -377,44 +376,10 @@ async fn handle_commands(
command: Commands,
) -> std::result::Result<(), ClientError> {
match command {
Commands::GetRolloutEstimate {
Commands::GetRollout {
target_interval: target,
} => {
let hashes = cli.client.get_rollout(target).await?;
let mut spaceouts = Vec::with_capacity(hashes.len());
for (priority, spacehash) in hashes {
let outpoint = cli
.client
.get_space_owner(&hex::encode(spacehash.as_slice()))
.await?;

if let Some(outpoint) = outpoint {
if let Some(spaceout) = cli.client.get_spaceout(outpoint).await? {
spaceouts.push((
priority,
FullSpaceOut {
txid: outpoint.txid,
spaceout,
},
));
}
}
}

let data: Vec<_> = spaceouts
.into_iter()
.map(|(priority, spaceout)| {
let space = spaceout.spaceout.space.unwrap();
(
space.name.to_string(),
match space.covenant {
Covenant::Bid { .. } => priority,
_ => 0,
},
)
})
.collect();

let data = cli.client.get_rollout(target).await?;
println!("{}", serde_json::to_string_pretty(&data)?);
}
Commands::EstimateBid { target } => {
Expand Down Expand Up @@ -486,7 +451,7 @@ async fn handle_commands(
)
.await?
}
Commands::CreateBidOut { pairs, fee_rate } => {
Commands::CreateBidOuts { pairs, fee_rate } => {
cli.send_request(None, Some(pairs), fee_rate).await?
}
Commands::Register {
Expand Down
11 changes: 7 additions & 4 deletions node/src/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::store::RolloutEntry;
use std::{
collections::BTreeMap, fs, io::Write, net::SocketAddr, path::PathBuf, str::FromStr, sync::Arc,
};
Expand Down Expand Up @@ -58,6 +59,8 @@ pub struct ServerInfo {
pub tip: ChainAnchor,
}



pub enum ChainStateCommand {
GetTip {
resp: Responder<anyhow::Result<ChainAnchor>>,
Expand Down Expand Up @@ -89,7 +92,7 @@ pub enum ChainStateCommand {
},
GetRollout {
target: usize,
resp: Responder<anyhow::Result<Vec<(u32, SpaceKey)>>>,
resp: Responder<anyhow::Result<Vec<RolloutEntry>>>,
},
}

Expand Down Expand Up @@ -117,7 +120,7 @@ pub trait Rpc {
async fn estimate_bid(&self, target: usize) -> Result<u64, ErrorObjectOwned>;

#[method(name = "getrollout")]
async fn get_rollout(&self, target: usize) -> Result<Vec<(u32, SpaceKey)>, ErrorObjectOwned>;
async fn get_rollout(&self, target: usize) -> Result<Vec<RolloutEntry>, ErrorObjectOwned>;

#[method(name = "getblockmeta")]
async fn get_block_meta(
Expand Down Expand Up @@ -613,7 +616,7 @@ impl RpcServer for RpcServerImpl {
Ok(info)
}

async fn get_rollout(&self, target: usize) -> Result<Vec<(u32, SpaceKey)>, ErrorObjectOwned> {
async fn get_rollout(&self, target: usize) -> Result<Vec<RolloutEntry>, ErrorObjectOwned> {
let rollouts = self
.store
.get_rollout(target)
Expand Down Expand Up @@ -932,7 +935,7 @@ impl AsyncChainState {
resp_rx.await?
}

pub async fn get_rollout(&self, target: usize) -> anyhow::Result<Vec<(u32, SpaceKey)>> {
pub async fn get_rollout(&self, target: usize) -> anyhow::Result<Vec<RolloutEntry>> {
let (resp, resp_rx) = oneshot::channel();
self.sender
.send(ChainStateCommand::GetRollout { target, resp })
Expand Down
58 changes: 41 additions & 17 deletions node/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ use std::{

use anyhow::Result;
use bincode::{config, Decode, Encode};
use protocol::{
bitcoin::OutPoint,
constants::{ChainAnchor, ROLLOUT_BATCH_SIZE},
hasher::{BidKey, KeyHash, OutpointKey, SpaceKey},
prepare::DataSource,
FullSpaceOut, SpaceOut,
};
use jsonrpsee::core::Serialize;
use serde::Deserialize;
use protocol::{bitcoin::OutPoint, constants::{ChainAnchor, ROLLOUT_BATCH_SIZE}, hasher::{BidKey, KeyHash, OutpointKey, SpaceKey}, prepare::DataSource, Covenant, FullSpaceOut, SpaceOut};
use spacedb::{
db::{Database, SnapshotIterator},
fs::FileBackend,
tx::{KeyIterator, ReadTransaction, WriteTransaction},
Configuration, Hash, NodeHasher, Sha256Hasher,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RolloutEntry {
pub space: String,
pub value: u32
}

type SpaceDb = Database<Sha256Hasher>;
type ReadTx = ReadTransaction<Sha256Hasher>;
pub type WriteTx<'db> = WriteTransaction<'db, Sha256Hasher>;
Expand Down Expand Up @@ -256,7 +258,7 @@ impl LiveSnapshot {
.insert(key, Some(value));
}

fn update_snapshot(&mut self, version: u32) -> anyhow::Result<()> {
fn update_snapshot(&mut self, version: u32) -> Result<()> {
if self.snapshot.0 != version {
self.snapshot.1 = self.db.begin_read()?;
let anchor: ChainAnchor = self.snapshot.1.metadata().try_into().map_err(|_| {
Expand Down Expand Up @@ -315,27 +317,49 @@ impl LiveSnapshot {
Ok(())
}

pub fn estimate_bid(&mut self, target: usize) -> anyhow::Result<u64> {
pub fn estimate_bid(&mut self, target: usize) -> Result<u64> {
let rollout = self.get_rollout(target)?;
if rollout.is_empty() {
return Ok(0);
}
let (priority, _) = rollout.last().unwrap();
Ok(*priority as u64)
let entry = rollout.last().unwrap();
Ok(entry.value as u64)
}

pub fn get_rollout(&mut self, target: usize) -> anyhow::Result<Vec<(u32, SpaceKey)>> {
pub fn get_rollout(&mut self, target: usize) -> Result<Vec<RolloutEntry>> {
let skip = target * ROLLOUT_BATCH_SIZE;
let entries = self.get_rollout_entries(Some(ROLLOUT_BATCH_SIZE), skip)?;
let rollouts = self.get_rollout_entries(Some(ROLLOUT_BATCH_SIZE), skip)?;
let mut spaceouts = Vec::with_capacity(rollouts.len());
for (priority, spacehash) in rollouts {
let outpoint = self.get_space_outpoint(&spacehash)?;
if let Some(outpoint) = outpoint {
if let Some(spaceout) = self.get_spaceout(&outpoint)? {
spaceouts.push((priority, FullSpaceOut { txid: outpoint.txid, spaceout }));
}
}
}

Ok(entries)
let data: Vec<_> = spaceouts
.into_iter()
.map(|(priority, spaceout)| {
let space = spaceout.spaceout.space.unwrap();
RolloutEntry {
space: space.name.to_string(),
value: match space.covenant {
Covenant::Bid { .. } => priority,
_ => 0,
},
}
})
.collect();
Ok(data)
}

pub fn get_rollout_entries(
&mut self,
limit: Option<usize>,
skip: usize,
) -> anyhow::Result<Vec<(u32, SpaceKey)>> {
) -> Result<Vec<(u32, SpaceKey)>> {
// TODO: this could use some clean up
let rlock = self.staged.read().expect("acquire lock");
let mut deleted = BTreeSet::new();
Expand Down Expand Up @@ -387,10 +411,10 @@ impl LiveSnapshot {
}
}

impl protocol::prepare::DataSource for LiveSnapshot {
impl DataSource for LiveSnapshot {
fn get_space_outpoint(
&mut self,
space_hash: &protocol::hasher::SpaceKey,
space_hash: &SpaceKey,
) -> protocol::errors::Result<Option<OutPoint>> {
let result: Option<EncodableOutpoint> = self
.get(*space_hash)
Expand Down

0 comments on commit 8f1edf7

Please sign in to comment.