Skip to content

Commit

Permalink
Merge pull request #61 from nervina-labs/remove-ccid
Browse files Browse the repository at this point in the history
Remove registry  ccid
  • Loading branch information
duanyytop authored Dec 2, 2022
2 parents 9eb7870 + 2081874 commit 217f0f5
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 186 deletions.
31 changes: 16 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cota-registry-aggregator"
version = "0.5.0"
version = "0.6.0"
edition = "2018"

[dependencies]
Expand All @@ -17,7 +17,7 @@ diesel = { version = "1.4.8", features = ["mysql", "r2d2", "numeric"] }
dotenv = "0.15.0"
molecule = "0.7.2"
serde = { version = "1.0", features = [ "derive" ] }
sparse-merkle-tree = "0.5.3"
sparse-merkle-tree = "0.6.1"
ckb-types = "=0.104.0"
ckb-jsonrpc-types = ">=0.104.0"
parking_lot = "0.12.1"
Expand Down
30 changes: 5 additions & 25 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
use crate::db::{
check_lock_hashes_registered, get_50_registered_lock_hashes, get_syncer_tip_block_number,
RegistryState,
};
use crate::smt::db::db::RocksDB;
use crate::db::{check_lock_hashes_registered, get_syncer_tip_block_number};
use crate::smt::entry::generate_registry_smt;
use crate::utils::{parse_request_param, Inserter};
use jsonrpc_http_server::jsonrpc_core::serde_json::Map;
use jsonrpc_http_server::jsonrpc_core::{Error, Params, Value};
use log::info;

pub async fn register_rpc(params: Params, db: &RocksDB) -> Result<Value, Error> {
pub async fn register_rpc(params: Params) -> Result<Value, Error> {
info!("Register cota cells request: {:?}", params);
let registries: Vec<Value> = Params::parse(params)?;
let lock_hashes = parse_request_param::<32>(registries).map_err(|err| err.into())?;
let (root_hash, registry_entry, output_account_num) = generate_registry_smt(db, lock_hashes)
let (root_hash, registry_entry) = generate_registry_smt(lock_hashes)
.await
.map_err(|err| err.into())?;
let block_number = get_syncer_tip_block_number().map_err(|err| err.into())?;
let mut response = Map::new();
response.insert_str("smt_root_hash", root_hash);
response.insert_str("registry_smt_entry", registry_entry);
response.insert_u64("output_account_num", output_account_num);
response.insert_u64("block_number", block_number);
Ok(Value::Object(response))
}
Expand All @@ -29,25 +24,10 @@ pub async fn check_registered_rpc(params: Params) -> Result<Value, Error> {
info!("Check registered request: {:?}", params);
let registries: Vec<Value> = Params::parse(params)?;
let lock_hashes = parse_request_param::<32>(registries).map_err(|err| err.into())?;
let (registry_state, block_height) =
let (registered, block_height) =
check_lock_hashes_registered(lock_hashes).map_err(|err| err.into())?;
let mut response = Map::new();
response.insert_bool("registered", registry_state != RegistryState::Unregister);
response.insert_bool("registered", registered);
response.insert_u64("block_number", block_height);
Ok(Value::Object(response))
}

pub async fn update_ccid_rpc(db: &RocksDB) -> Result<Value, Error> {
info!("Update registered ccid request");
let lock_hashes = get_50_registered_lock_hashes().map_err(|err| err.into())?;
let (root_hash, registry_entry, output_account_num) = generate_registry_smt(db, lock_hashes)
.await
.map_err(|err| err.into())?;
let block_number = get_syncer_tip_block_number().map_err(|err| err.into())?;
let mut response = Map::new();
response.insert_str("smt_root_hash", root_hash);
response.insert_str("registry_smt_entry", registry_entry);
response.insert_u64("output_account_num", output_account_num);
response.insert_u64("block_number", block_number);
Ok(Value::Object(response))
}
52 changes: 7 additions & 45 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ use crate::schema::check_infos::dsl::block_number;
use crate::schema::check_infos::dsl::check_infos;
use crate::utils::parse_bytes_n;
use crate::POOL;
use cota_smt::smt::H256;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::*;
use jsonrpc_http_server::jsonrpc_core::serde_json::from_str;
use log::error;
use serde::{Deserialize, Serialize};
use sparse_merkle_tree::H256;
use std::env;

pub type SqlConnectionPool = Pool<ConnectionManager<MysqlConnection>>;
Expand Down Expand Up @@ -57,33 +57,20 @@ pub fn get_registered_lock_hashes_and_ccids() -> Result<Vec<(H256, u64)>, Error>
Ok(leaves)
}

#[derive(PartialEq, Clone, Copy)]
pub enum RegistryState {
Unregister,
WithCCID,
NoCCID,
}
pub fn check_lock_hashes_registered(
lock_hashes: Vec<[u8; 32]>,
) -> Result<(RegistryState, u64), Error> {
pub fn check_lock_hashes_registered(lock_hashes: Vec<[u8; 32]>) -> Result<(bool, u64), Error> {
let conn = &POOL.clone().get().expect("Mysql pool connection error");
let lock_hash_vec: Vec<String> = lock_hashes.iter().map(hex::encode).collect();
let ccids = register_cota_kv_pairs
.select(cota_cell_id)
let regsitered_count = register_cota_kv_pairs
.filter(lock_hash.eq_any(lock_hash_vec))
.load::<u64>(conn)
.count()
.get_result::<i64>(conn)
.map_err(|e| {
error!("Query registry state error: {}", e.to_string());
Error::DatabaseQueryError(e.to_string())
})?;
let block_height = get_syncer_tip_block_number()?;
if ccids.len() < lock_hashes.len() {
Ok((RegistryState::Unregister, block_height))
} else if ccids.into_iter().any(|ccid| ccid == u64::MAX) {
Ok((RegistryState::NoCCID, block_height))
} else {
Ok((RegistryState::WithCCID, block_height))
}
let all_registered = lock_hashes.len() == regsitered_count as usize;
Ok((all_registered, block_height))
}

pub fn get_syncer_tip_block_number() -> Result<u64, Error> {
Expand All @@ -98,24 +85,6 @@ pub fn get_syncer_tip_block_number() -> Result<u64, Error> {
})
}

pub fn get_50_registered_lock_hashes() -> Result<Vec<[u8; 32]>, Error> {
let conn = &POOL.clone().get().expect("Mysql pool connection error");
let lock_hashes = register_cota_kv_pairs
.select(lock_hash)
.order(id.asc())
.filter(cota_cell_id.eq(u64::MAX))
.limit(50)
.load::<String>(conn)
.map_or_else(
|e| {
error!("Query 50 registered lock hash error: {}", e.to_string());
Err(Error::DatabaseQueryError(e.to_string()))
},
|hashes| Ok(parse_lock_hashes(hashes)),
)?;
Ok(lock_hashes)
}

fn parse_registries(registries: Vec<Registry>) -> Vec<(H256, u64)> {
registries
.into_iter()
Expand All @@ -127,10 +96,3 @@ fn parse_registries(registries: Vec<Registry>) -> Vec<(H256, u64)> {
})
.collect()
}

fn parse_lock_hashes(hashes: Vec<String>) -> Vec<[u8; 32]> {
hashes
.into_iter()
.map(|hash| parse_bytes_n::<32>(hash).unwrap())
.collect()
}
8 changes: 3 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ pub enum Error {
)]
RequestParamHexInvalid(String),

#[fail(display = "The lock_hash has registered with CCID")]
LockHashHasRegisteredWithCCID,
#[fail(display = "The lock_hash has registered")]
LockHashHasRegistered,

#[fail(display = "Database '{}' query error", _0)]
DatabaseQueryError(String),
Expand All @@ -32,9 +32,7 @@ impl Error {
"Request lock_hash '{}' must be 32bytes hex string starting with 0x",
msg
),
Self::LockHashHasRegisteredWithCCID => {
"The lock_hash has registered with CCID".to_string()
}
Self::LockHashHasRegistered => "The lock_hash has registered".to_string(),
Self::CKBIndexerError(msg) => format!("CKB Indexer error: {}", msg),
Self::DatabaseQueryError(msg) => format!("Database query error: {}", msg),
Self::SMTError(msg) => format!("SMT error: {}", msg),
Expand Down
41 changes: 9 additions & 32 deletions src/indexer/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,37 +12,7 @@ const MAINNET_REGISTRY_COTA_CODE_HASH: &str =
"0x90ca618be6c15f5857d3cbd09f9f24ca6770af047ba9ee70989ec3b229419ac7";
const MAINNET_REGISTRY_COTA_ARGS: &str = "0x563631b49cee549f3585ab4dde5f9d590f507f1f";

pub struct RegistryInfo {
pub smt_root: [u8; 32],
pub account_num: u64,
}

impl RegistryInfo {
pub fn from(data: &[u8]) -> Result<Self, Error> {
if data.len() != 33 && data.len() != 41 {
return Err(Error::CKBIndexerError(
"Registry cell data length error".to_owned(),
));
}
let mut smt_root = [0u8; 32];
smt_root.copy_from_slice(&data[1..33]);

let account_num = if data.len() == 33 {
0u64
} else {
let mut num = [0u8; 8];
num.copy_from_slice(&data[33..41]);
u64::from_be_bytes(num)
};
let registry = RegistryInfo {
smt_root,
account_num,
};
Ok(registry)
}
}

pub async fn get_registry_info() -> Result<RegistryInfo, Error> {
pub async fn get_registry_root_hash() -> Result<[u8; 32], Error> {
let ckb_indexer_url = env::var("CKB_INDEXER")
.map_err(|_e| Error::CKBIndexerError("CKB_INDEXER must be set".to_owned()))?;

Expand Down Expand Up @@ -80,7 +50,14 @@ pub async fn get_registry_info() -> Result<RegistryInfo, Error> {
));
}
let cell_data = result.objects.first().unwrap().output_data.as_bytes();
RegistryInfo::from(cell_data)
if cell_data.len() != 33 && cell_data.len() != 41 {
return Err(Error::CKBIndexerError(
"Registry cell data length error".to_owned(),
));
}
let mut smt_root = [0u8; 32];
smt_root.copy_from_slice(&cell_data[1..33]);
Ok(smt_root)
}

fn generate_params() -> Result<Value, Error> {
Expand Down
7 changes: 3 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
extern crate diesel;
extern crate dotenv;

use crate::api::{check_registered_rpc, register_rpc, update_ccid_rpc};
use crate::api::{check_registered_rpc, register_rpc};
use crate::db::{init_connection_pool, SqlConnectionPool};
use crate::smt::db::db::RocksDB;
use dotenv::dotenv;
Expand All @@ -20,7 +20,7 @@ mod smt;
mod utils;

lazy_static! {
static ref DB: RocksDB = RocksDB::default().expect("RocksDB open error");
static ref ROCKS_DB: RocksDB = RocksDB::default().expect("RocksDB open error");
static ref POOL: SqlConnectionPool = init_connection_pool();
}

Expand All @@ -31,8 +31,7 @@ fn main() {
.init();

let mut io = IoHandler::default();
io.add_method("register_cota_cells", |req| register_rpc(req, &DB));
io.add_method("update_registered_ccid", |_req| update_ccid_rpc(&DB));
io.add_method("register_cota_cells", register_rpc);
io.add_method("check_registered_lock_hashes", check_registered_rpc);

let server = ServerBuilder::new(io)
Expand Down
Loading

0 comments on commit 217f0f5

Please sign in to comment.