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

Add sat recursive endpoints with index and pagination #2680

Merged
merged 20 commits into from
Nov 23, 2023
Merged
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
82 changes: 73 additions & 9 deletions src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,35 @@ impl Index {
pub(crate) fn get_inscription_ids_by_sat(&self, sat: Sat) -> Result<Vec<InscriptionId>> {
let rtx = self.database.begin_read()?;

let sequence_number_to_inscription_entry =
rtx.open_table(SEQUENCE_NUMBER_TO_INSCRIPTION_ENTRY)?;

let ids = rtx
.open_multimap_table(SAT_TO_SEQUENCE_NUMBER)?
.get(&sat.n())?
.map(|result| {
result
.and_then(|sequence_number| {
let sequence_number = sequence_number.value();
sequence_number_to_inscription_entry
.get(sequence_number)
.map(|entry| InscriptionEntry::load(entry.unwrap().value()).id)
})
.map_err(|err| err.into())
})
.collect::<Result<Vec<InscriptionId>>>()?;

Ok(ids)
}

pub(crate) fn get_inscription_ids_by_sat_paginated(
&self,
sat: Sat,
page_size: u64,
page_index: u64,
) -> Result<(Vec<InscriptionId>, bool)> {
let rtx = self.database.begin_read()?;

let sequence_number_to_inscription_entry =
rtx.open_table(SEQUENCE_NUMBER_TO_INSCRIPTION_ENTRY)?;

Expand All @@ -1053,20 +1082,55 @@ impl Index {
let sequence_number = sequence_number.value();
sequence_number_to_inscription_entry
.get(sequence_number)
.map(|entry| {
(
sequence_number,
InscriptionEntry::load(entry.unwrap().value()).id,
)
})
.map(|entry| InscriptionEntry::load(entry.unwrap().value()).id)
})
.map_err(|err| err.into())
})
.collect::<Result<Vec<(u32, InscriptionId)>>>()?;
.skip(page_index.saturating_mul(page_size).try_into().unwrap())
.take(page_size.saturating_add(1).try_into().unwrap())
.collect::<Result<Vec<InscriptionId>>>()?;

let more = ids.len() > page_size.try_into().unwrap();

if more {
ids.pop();
}

Ok((ids, more))
}

pub(crate) fn get_inscription_id_by_sat_indexed(
&self,
sat: Sat,
inscription_index: isize,
) -> Result<Option<InscriptionId>> {
let rtx = self.database.begin_read()?;

let sequence_number_to_inscription_entry =
rtx.open_table(SEQUENCE_NUMBER_TO_INSCRIPTION_ENTRY)?;

ids.sort_by_key(|(sequence_number, _id)| *sequence_number);
let sat_to_sequence_number = rtx.open_multimap_table(SAT_TO_SEQUENCE_NUMBER)?;

Ok(ids.into_iter().map(|(_sequence_number, id)| id).collect())
if inscription_index < 0 {
sat_to_sequence_number
.get(&sat.n())?
.nth_back((inscription_index + 1).abs_diff(0))
} else {
sat_to_sequence_number
.get(&sat.n())?
.nth(inscription_index.abs_diff(0))
}
.map(|result| {
result
.and_then(|sequence_number| {
let sequence_number = sequence_number.value();
sequence_number_to_inscription_entry
.get(sequence_number)
.map(|entry| InscriptionEntry::load(entry.unwrap().value()).id)
})
.map_err(|err| anyhow!(err.to_string()))
})
.transpose()
}

pub(crate) fn get_inscription_id_by_sequence_number(
Expand Down
43 changes: 42 additions & 1 deletion src/subcommand/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use {
InscriptionsJson, OutputHtml, OutputJson, PageContent, PageHtml, PreviewAudioHtml,
PreviewCodeHtml, PreviewFontHtml, PreviewImageHtml, PreviewMarkdownHtml, PreviewModelHtml,
PreviewPdfHtml, PreviewTextHtml, PreviewUnknownHtml, PreviewVideoHtml, RangeHtml, RareTxt,
RuneHtml, RunesHtml, SatHtml, SatJson, TransactionHtml,
RuneHtml, RunesHtml, SatHtml, SatInscriptionJson, SatInscriptionsJson, SatJson,
TransactionHtml,
},
},
axum::{
Expand Down Expand Up @@ -238,6 +239,9 @@ impl Server {
.route("/r/blockheight", get(Self::block_height))
.route("/r/blocktime", get(Self::block_time))
.route("/r/metadata/:inscription_id", get(Self::metadata))
.route("/r/sat/:sat", get(Self::sat_inscriptions))
.route("/r/sat/:sat/:page", get(Self::sat_inscriptions_paginated))
.route("/r/sat/:sat/at/:index", get(Self::sat_inscription_at_index))
.route("/range/:start/:end", get(Self::range))
.route("/rare.txt", get(Self::rare_txt))
.route("/rune/:rune", get(Self::rune))
Expand Down Expand Up @@ -1441,6 +1445,43 @@ impl Server {
})
}

async fn sat_inscriptions(
Extension(index): Extension<Arc<Index>>,
Path(DeserializeFromStr(sat)): Path<DeserializeFromStr<Sat>>,
) -> ServerResult<Json<SatInscriptionsJson>> {
Self::sat_inscriptions_paginated(Extension(index), Path((DeserializeFromStr(sat), 0))).await
}

async fn sat_inscriptions_paginated(
Extension(index): Extension<Arc<Index>>,
Path((DeserializeFromStr(sat), page)): Path<(DeserializeFromStr<Sat>, u64)>,
) -> ServerResult<Json<SatInscriptionsJson>> {
if !index.has_sat_index() {
return Err(ServerError::NotFound(
"this server has no sat index".to_string(),
));
}

let (ids, more) = index.get_inscription_ids_by_sat_paginated(sat, 100, page)?;

Ok(Json(SatInscriptionsJson { ids, more, page }))
}

async fn sat_inscription_at_index(
Extension(index): Extension<Arc<Index>>,
Path((DeserializeFromStr(sat), inscription_index)): Path<(DeserializeFromStr<Sat>, isize)>,
) -> ServerResult<Json<SatInscriptionJson>> {
if !index.has_sat_index() {
return Err(ServerError::NotFound(
"this server has no sat index".to_string(),
));
}

let id = index.get_inscription_id_by_sat_indexed(sat, inscription_index)?;

Ok(Json(SatInscriptionJson { id }))
}

async fn redirect_http_to_https(
Extension(mut destination): Extension<String>,
uri: Uri,
Expand Down
2 changes: 1 addition & 1 deletion src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub(crate) use {
rare::RareTxt,
rune::RuneHtml,
runes::RunesHtml,
sat::{SatHtml, SatJson},
sat::{SatHtml, SatInscriptionJson, SatInscriptionsJson, SatJson},
transaction::TransactionHtml,
};

Expand Down
12 changes: 12 additions & 0 deletions src/templates/sat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ pub struct SatJson {
pub inscriptions: Vec<InscriptionId>,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct SatInscriptionsJson {
pub ids: Vec<InscriptionId>,
pub more: bool,
pub page: u64,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct SatInscriptionJson {
pub id: Option<InscriptionId>,
}

impl PageContent for SatHtml {
fn title(&self) -> String {
format!("Sat {}", self.sat)
Expand Down
38 changes: 36 additions & 2 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ use {
inscription_id::InscriptionId,
rarity::Rarity,
templates::{
block::BlockJson, inscription::InscriptionJson, inscriptions::InscriptionsJson,
output::OutputJson, sat::SatJson,
block::BlockJson,
inscription::InscriptionJson,
inscriptions::InscriptionsJson,
output::OutputJson,
sat::{SatInscriptionJson, SatInscriptionsJson, SatJson},
},
SatPoint,
},
Expand Down Expand Up @@ -67,6 +70,37 @@ fn inscribe(rpc_server: &test_bitcoincore_rpc::Handle) -> (InscriptionId, Txid)
(output.inscriptions[0].id, output.reveal)
}

fn reinscribe(rpc_server: &test_bitcoincore_rpc::Handle, n: usize) -> Vec<InscriptionId> {
let mut inscriptions = Vec::new();

let mut output = CommandBuilder::new("wallet inscribe --fee-rate 1 --file foo.txt")
.write("foo.txt", "FOO")
.rpc_server(rpc_server)
.run_and_deserialize_output::<Inscribe>();

inscriptions.push(output.inscriptions[0].id);

rpc_server.mine_blocks(1);

for _ in 1..n {
output = CommandBuilder::new(format!(
"wallet inscribe --reinscribe --satpoint {} --fee-rate 1 --file foo.txt",
output.inscriptions[0].location
))
.write("foo.txt", "FOO")
.rpc_server(rpc_server)
.run_and_deserialize_output::<Inscribe>();

inscriptions.push(output.inscriptions[0].id);

rpc_server.mine_blocks(1);
}

assert_eq!(inscriptions.len(), n);

inscriptions
}

fn envelope(payload: &[&[u8]]) -> bitcoin::Witness {
let mut builder = bitcoin::script::Builder::new()
.push_opcode(bitcoin::opcodes::OP_FALSE)
Expand Down
142 changes: 142 additions & 0 deletions tests/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,145 @@ fn all_endpoints_in_recursive_directory_return_json() {

assert!(server.request("/blockhash/2").json::<String>().is_err());
}

#[test]
#[ignore]
fn sat_recursive_endpoints() {
raphjaph marked this conversation as resolved.
Show resolved Hide resolved
let rpc_server = test_bitcoincore_rpc::spawn();

create_wallet(&rpc_server);

rpc_server.mine_blocks(1);

let server = TestServer::spawn_with_args(&rpc_server, &["--index-sats"]);

assert_eq!(
server
.request("/r/sat/nvtcsezkbth")
.json::<SatInscriptionsJson>()
.unwrap(),
SatInscriptionsJson {
ids: vec![],
page: 0,
more: false
}
);

assert_eq!(
server
.request("/r/sat/5000000000")
.json::<SatInscriptionsJson>()
.unwrap(),
SatInscriptionsJson {
ids: vec![],
page: 0,
more: false
}
);

assert_eq!(
server
.request("/r/sat/5000000000/at/0")
.json::<SatInscriptionJson>()
.unwrap(),
SatInscriptionJson { id: None }
);

let inscriptions = reinscribe(&rpc_server, 111);

let server = TestServer::spawn_with_args(&rpc_server, &["--index-sats"]);

let paginated_response = server
.request("/r/sat/5000000000")
.json::<SatInscriptionsJson>()
.unwrap();

let equivalent_paginated_response = server
.request("/r/sat/nvtcsezkbth/0")
.json::<SatInscriptionsJson>()
.unwrap();

assert_eq!(paginated_response.ids.len(), 100);
assert!(paginated_response.more);
assert_eq!(paginated_response.page, 0);

assert_eq!(
paginated_response.ids.len(),
equivalent_paginated_response.ids.len()
);
assert_eq!(paginated_response.more, equivalent_paginated_response.more);
assert_eq!(paginated_response.page, equivalent_paginated_response.page);

let paginated_response = server
.request("/r/sat/5000000000/1")
.json::<SatInscriptionsJson>()
.unwrap();

assert_eq!(paginated_response.ids.len(), 11);
assert!(!paginated_response.more);
assert_eq!(paginated_response.page, 1);

assert_eq!(
server
.request("/r/sat/nvtcsezkbth/at/0")
.json::<SatInscriptionJson>()
.unwrap()
.id,
Some(inscriptions[0])
);

assert_eq!(
server
.request("/r/sat/5000000000/at/-111")
.json::<SatInscriptionJson>()
.unwrap()
.id,
Some(inscriptions[0])
);

assert_eq!(
server
.request("/r/sat/5000000000/at/110")
.json::<SatInscriptionJson>()
.unwrap()
.id,
Some(inscriptions[110])
);

assert_eq!(
server
.request("/r/sat/0°1′1″0‴/at/-1")
.json::<SatInscriptionJson>()
.unwrap()
.id,
Some(inscriptions[110])
);

assert!(server
.request("/r/sat/5000000000/at/111")
.json::<SatInscriptionJson>()
.unwrap()
.id
.is_none());
}

#[test]
fn sat_recursive_endpoints_without_sat_index_return_404() {
let rpc_server = test_bitcoincore_rpc::spawn();

create_wallet(&rpc_server);

rpc_server.mine_blocks(1);

let server = TestServer::spawn_with_args(&rpc_server, &[""]);

assert_eq!(
server.request("/r/sat/5000000000").status(),
StatusCode::NOT_FOUND,
);

assert_eq!(
server.request("/r/sat/5000000000/at/1").status(),
StatusCode::NOT_FOUND,
);
}
Loading