Skip to content

Commit

Permalink
update btc domain to many names (#50)
Browse files Browse the repository at this point in the history
Co-authored-by: linfeng.yuan <[email protected]>
  • Loading branch information
DogLi and linfeng.yuan authored Sep 25, 2024
1 parent 573ef8f commit 2b2caaa
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 68 deletions.
2 changes: 0 additions & 2 deletions src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,6 @@ pub struct Index {
path: PathBuf,
started: DateTime<Utc>,
unrecoverably_reorged: AtomicBool,
pub domain_list: Vec<String>,
}

impl Index {
Expand Down Expand Up @@ -423,7 +422,6 @@ impl Index {
path,
started: Utc::now(),
unrecoverably_reorged: AtomicBool::new(false),
domain_list: options.btc_domain_list.clone(),
})
}

Expand Down
10 changes: 3 additions & 7 deletions src/index/rtx.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use crate::okx::datastore::ord::btc_name::BtcName;
use crate::okx::datastore::ord::btc_name::BtcDomain;

pub(crate) struct Rtx<'a>(pub(crate) redb::ReadTransaction<'a>);

Expand Down Expand Up @@ -175,13 +175,9 @@ impl Rtx<'_> {
get_collection_inscription_id(&table, &district.to_collection_key())
}

pub(crate) fn btc_name_to_inscription_id(
&self,
btc_name: &str,
domain_list: &[String],
) -> Result<Option<InscriptionId>> {
pub(crate) fn btc_name_to_inscription_id(&self, btc_name: &str) -> Result<Option<InscriptionId>> {
let btc_name_raw = btc_name.as_bytes().to_vec();
let domain = BtcName::parse(&btc_name_raw, domain_list)?;
let domain = BtcDomain::parse(&btc_name_raw)?;
let table = self.0.open_table(COLLECTIONS_KEY_TO_INSCRIPTION_ID)?;
get_collection_inscription_id(&table, &domain.to_collection_key())
}
Expand Down
46 changes: 27 additions & 19 deletions src/okx/datastore/ord/btc_name.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
use {super::*, anyhow::anyhow, regex::Regex};

const BTC_DOMAIN_KEY: &str = r"BTC_NAME";
const BTC_DOMAIN_KEY: &str = r"BTC_DOMAIN";

pub struct BtcName {
pub struct BtcDomain {
pub name: String,
pub domain: String,
pub collection_kind: CollectionKind,
}

const DEFAULT_DOMAIN_LIST: [&str; 4] = ["btc", "unisat", "sats", "x"];
impl BtcName {
pub fn parse(bytes: &[u8], domain_list: &[String]) -> Result<Self> {
let domains = if domain_list.is_empty() {
DEFAULT_DOMAIN_LIST.join("|")
} else {
domain_list.join("|")
};
impl BtcDomain {
pub fn parse(bytes: &[u8]) -> Result<Self> {
let domains = DEFAULT_DOMAIN_LIST.join("|");
let pattern = format!(r"^(?<name>.+)\.(?<domain>{domains})$");
let content = std::str::from_utf8(bytes)?;
let re = Regex::new(&pattern).unwrap();
Expand All @@ -25,6 +22,7 @@ impl BtcName {
return Ok(Self {
name: name.to_string(),
domain: domain.to_string(),
collection_kind: CollectionKind::try_from(domain).unwrap(),
});
}
}
Expand All @@ -48,7 +46,7 @@ impl BtcName {
}

pub fn to_collection_key(&self) -> String {
format!("{}_{}_{}", BTC_DOMAIN_KEY, self.name, self.domain)
format!("{}_{}_{}", BTC_DOMAIN_KEY, self.domain, self.name)
}
}

Expand All @@ -58,7 +56,6 @@ mod tests {

#[test]
fn validate_regex() {
let domain_list = vec![];
let invalid_domains = [
"abc.bitmap",
"btc.com.btc",
Expand All @@ -71,10 +68,11 @@ mod tests {
"\njack.btc",
"hi\njack.btc",
"\njack.btc\n",
"abc.aaa",
r#"{ "p":"sns", "op":"reg", "name":"jack.btc"}"#,
];
for domain in invalid_domains {
let btc_name = BtcName::parse(domain.as_bytes(), &domain_list);
let btc_name = BtcDomain::parse(domain.as_bytes());
assert!(btc_name.is_err());
}

Expand All @@ -90,20 +88,30 @@ mod tests {
"\tjack.btc",
];
for domain in valid_domains {
let btc_name = BtcName::parse(domain.as_bytes(), &domain_list);
let btc_name = BtcDomain::parse(domain.as_bytes());
assert!(btc_name.is_ok());
assert!(matches!(
btc_name.unwrap().collection_kind,
CollectionKind::BtcName
));
}

// test "unisat", "sats", "x"
let valid_domain = "abcdef.unisat";
let unisat_name = BtcDomain::parse(valid_domain.as_bytes()).unwrap();
assert_eq!(unisat_name.collection_kind, CollectionKind::UnisatName);
let valid_domain = "abcdef.sats";
let sats_name = BtcDomain::parse(valid_domain.as_bytes()).unwrap();
assert_eq!(sats_name.collection_kind, CollectionKind::SatsName);
let valid_domain = "abcdef.x";
let x_name = BtcDomain::parse(valid_domain.as_bytes()).unwrap();
assert_eq!(x_name.collection_kind, CollectionKind::XName);

for d in DEFAULT_DOMAIN_LIST {
let s = format!("abc.{d}");
let btc_name = BtcName::parse(s.as_bytes(), &domain_list).unwrap();
let btc_name = BtcDomain::parse(s.as_bytes()).unwrap();
assert!(DEFAULT_DOMAIN_LIST.contains(&btc_name.domain.as_str()));
assert_eq!(btc_name.name, "abc");
}
// new domain list
let domain_list = vec!["aaa".to_string(), "bbb".to_string()];
let btc_name = BtcName::parse("abc.aaa".as_bytes(), &domain_list).unwrap();
assert_eq!(btc_name.name, "abc");
assert_eq!(btc_name.domain, "aaa");
}
}
21 changes: 20 additions & 1 deletion src/okx/datastore/ord/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ pub enum CollectionKind {
BitMap,
BRC20,
BtcName,
UnisatName,
SatsName,
XName,
}
impl Display for CollectionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand All @@ -15,9 +18,25 @@ impl Display for CollectionKind {
"{}",
match self {
CollectionKind::BitMap => String::from("bitmap"),
CollectionKind::BtcName => String::from("btc_name"),
CollectionKind::BRC20 => String::from("brc20"),
CollectionKind::BtcName => String::from("btc_name"),
CollectionKind::UnisatName => String::from("unisat_name"),
CollectionKind::SatsName => String::from("sats_name"),
CollectionKind::XName => String::from("x_name"),
}
)
}
}

impl TryFrom<&str> for CollectionKind {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"btc" => Ok(CollectionKind::BtcName),
"unisat" => Ok(CollectionKind::UnisatName),
"sats" => Ok(CollectionKind::SatsName),
"x" => Ok(CollectionKind::XName),
_ => Err(()),
}
}
}
2 changes: 0 additions & 2 deletions src/okx/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ pub struct ProtocolConfig {
enable_ord_receipts: bool,
enable_index_bitmap: bool,
enable_index_domain: bool,
btc_domain_list: Vec<String>,
}

impl ProtocolConfig {
Expand All @@ -41,7 +40,6 @@ impl ProtocolConfig {
enable_ord_receipts: options.enable_save_ord_receipts,
enable_index_bitmap: options.enable_index_bitmap,
enable_index_domain: options.enable_index_domain,
btc_domain_list: options.btc_domain_list.clone(),
}
}
}
21 changes: 9 additions & 12 deletions src/okx/protocol/ord/btc_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use crate::okx::protocol::context::Context;
use {
crate::{
okx::datastore::ord::{
btc_name::BtcName,
collections::CollectionKind,
btc_name::BtcDomain,
operation::{Action, InscriptionOp},
},
Inscription, InscriptionId, Result,
Expand All @@ -14,10 +13,9 @@ use {
std::collections::HashMap,
};

pub fn index_btc_name(
pub fn index_btc_domain(
context: &mut Context,
operations: &HashMap<Txid, Vec<InscriptionOp>>,
domain_list: &[String],
) -> Result<u64> {
let mut count = 0;

Expand All @@ -37,12 +35,12 @@ pub fn index_btc_name(
for op in positive_inscriptions.into_iter() {
match op.action {
Action::New { inscription, .. } => {
if let Some((inscription_id, btc_name)) =
do_index_btc_name(context, inscription, op.inscription_id, domain_list)?
if let Some((inscription_id, btc_domain)) =
do_index_btc_domain(context, inscription, op.inscription_id)?
{
let key = btc_name.to_collection_key();
let key = btc_domain.to_collection_key();
context.set_inscription_by_collection_key(&key, &inscription_id)?;
context.add_inscription_attributes(&inscription_id, CollectionKind::BtcName)?;
context.add_inscription_attributes(&inscription_id, btc_domain.collection_kind)?;
count += 1;
}
}
Expand All @@ -52,14 +50,13 @@ pub fn index_btc_name(
Ok(count)
}

fn do_index_btc_name(
fn do_index_btc_domain(
context: &mut Context,
inscription: Inscription,
inscription_id: InscriptionId,
domain_list: &[String],
) -> Result<Option<(InscriptionId, BtcName)>> {
) -> Result<Option<(InscriptionId, BtcDomain)>> {
if let Some(content) = inscription.body() {
if let Ok(btc_name) = BtcName::parse(content, domain_list) {
if let Ok(btc_name) = BtcDomain::parse(content) {
let collection_key = btc_name.to_collection_key();

if context
Expand Down
3 changes: 1 addition & 2 deletions src/okx/protocol/protocol_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ impl ProtocolManager {
bitmap_count = ord_proto::bitmap::index_bitmap(context, &operations)?;
}
if self.config.enable_index_domain {
btc_domain_count =
ord_proto::btc_name::index_btc_name(context, &operations, &self.config.btc_domain_list)?;
btc_domain_count = ord_proto::btc_name::index_btc_domain(context, &operations)?;
}
let cost4 = bitmap_start.elapsed().as_millis();

Expand Down
13 changes: 0 additions & 13 deletions src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,6 @@ pub struct Options {
// OKX defined options.
#[arg(long, help = "Enable Index all of BRC20 Protocol")]
pub(crate) enable_index_brc20: bool,
#[arg(long, use_value_delimiter=true, value_delimiter = ',', num_args=0..,
help = "BTC domain list, default are btc,unisat,sats,x")]
pub(crate) btc_domain_list: Vec<String>,
#[arg(
long,
help = "Don't look for BRC20 messages below <FIRST_BRC20_HEIGHT>."
Expand Down Expand Up @@ -905,14 +902,4 @@ mod tests {
"cookie file `/foo/bar/baz/qux/.cookie` does not exist"
);
}

#[test]
fn test_domain_list() {
let arguments =
Arguments::try_parse_from(["ord", "--btc-domain-list=aaa,bbb", "index", "update"]).unwrap();
assert_eq!(
arguments.options.btc_domain_list,
vec!["aaa".to_string(), "bbb".to_string()]
);
}
}
4 changes: 2 additions & 2 deletions src/subcommand/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,8 @@ impl Server {
get(ord::ord_debug_bitmap_district),
)
.route(
"/ord/debug/btc/name/:btc_name",
get(ord::ord_debug_btc_name),
"/ord/debug/btc/domain/:btc_name",
get(ord::ord_debug_btc_domain),
)
.route("/brc20/tick/:tick", get(brc20::brc20_tick_info))
.route("/brc20/tick", get(brc20::brc20_all_tick_info))
Expand Down
16 changes: 8 additions & 8 deletions src/subcommand/server/ord/inscription.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,20 +249,20 @@ pub(crate) async fn ord_debug_bitmap_district(
}

// ord/debug/btc_nam/:btc_name
pub(crate) async fn ord_debug_btc_name(
pub(crate) async fn ord_debug_btc_domain(
Extension(index): Extension<Arc<Index>>,
Path(btc_name): Path<String>,
Path(btc_domain): Path<String>,
) -> ApiResult<InscriptionId> {
log::debug!("rpc: get ord_debug_btc_name:{btc_name}");
log::info!("rpc: get ord_debug_btc_domain:{btc_domain}");

let rtx = index.begin_read()?;
let inscription_id = rtx
.btc_name_to_inscription_id(&btc_name, &index.domain_list)?
.ok_or_api_not_found(format!("district {btc_name} not found."))?;
.btc_name_to_inscription_id(&btc_domain)?
.ok_or_api_not_found(format!("btc domain {btc_domain} not found."))?;

log::debug!(
"rpc: get ord_debug_bitmap_district: {:?} {:?}",
btc_name,
log::info!(
"rpc: get ord_debug_btc_domain: {:?} {:?}",
btc_domain,
inscription_id
);

Expand Down

0 comments on commit 2b2caaa

Please sign in to comment.