This commit is contained in:
Hossein Zoda 2026-04-27 04:19:53 +03:00
parent 988426e485
commit aa99f775da

View file

@ -222,9 +222,9 @@ pub enum IdoState {
/*UNUSED
fn script_concat(script: Script, v: &[u8]) -> Script {
let mut bytes = script.to_bytes();
bytes.extend_from_slice(v);
Script::from(bytes)
let mut bytes = script.to_bytes();
bytes.extend_from_slice(v);
Script::from(bytes)
}
*/
fn build_p2nfth_script(nfthash: &[u8]) -> Script {
@ -561,7 +561,8 @@ pub async fn prepare_tables(pool: &SqlitePool) {
state BLOB NOT NULL,
txchain_entrypoint INTEGER NULL,
txchain_head INTEGER NULL,
is_valid INTEGER NOT NULL
is_valid INTEGER NOT NULL,
is_token_created_at_preinit INTEGER NOT NULL
)",
)
.execute(pool)
@ -650,6 +651,7 @@ pub struct IdoDBRecord {
txchain_entrypoint: Option<i64>,
txchain_head: Option<i64>,
is_valid: bool,
is_token_created_at_preinit: bool,
}
impl IdoDBRecord {
fn from_row(row: &sqlx::sqlite::SqliteRow) -> Result<Self> {
@ -666,6 +668,7 @@ impl IdoDBRecord {
txchain_entrypoint: row.get(9),
txchain_head: row.get(10),
is_valid: row.get(11),
is_token_created_at_preinit: row.get(12),
})
}
}
@ -750,7 +753,7 @@ async fn ido_lookup(
) -> Result<Option<IdoDBRecord>> {
let row = sqlx::query(
"SELECT id, preinit_txid, init_txid, launch_txid, offering_token_id, offered_token_id,
status, parameters, state, txchain_entrypoint, txchain_head, is_valid
status, parameters, state, txchain_entrypoint, txchain_head, is_valid, is_token_created_at_preinit
FROM ido WHERE id = ?",
)
.bind(ido_id)
@ -802,6 +805,7 @@ struct IdoContext {
parameters: IdoParameters,
state: IdoState,
is_valid_ido: bool,
is_token_created_at_preinit: bool,
offered_token_id: Option<Vec<u8>>,
offering_token_id: Option<Vec<u8>>,
}
@ -881,18 +885,18 @@ async fn create_ido_context_from_preinit(network: Option<Network>, tx: &Transact
}
if preinit_parameters.permanentLiquidityShareNumerator < *MIN_PLP_SHARE ||
preinit_parameters.permanentLiquidityShareNumerator > *MAX_PLP_SHARE ||
preinit_parameters.offering.offer.discountAnnualRateNumerator < *MIN_PLP_ANNUAL_DISCOUNT ||
preinit_parameters.offering.offer.discountAnnualRateNumerator > *MAX_PLP_ANNUAL_DISCOUNT ||
preinit_parameters.offering.offer.maxDiscountRateNumerator !=
preinit_parameters.permanentLiquidityShareNumerator ||
preinit_parameters.offeredTokenAmount <= BigInt::from(0) ||
preinit_parameters.offering.delphiCategory != DELPHI_TOKEN_ID ||
preinit_parameters.offering.platformFeeNFTH != platform_fee_nfth ||
preinit_parameters.offering.platformFeeNumerator < *PLATFORM_FEE ||
preinit_parameters.offering.executionFee < *ENTRY_EXECUTION_FEE {
is_valid_ido = false;
}
preinit_parameters.permanentLiquidityShareNumerator > *MAX_PLP_SHARE ||
preinit_parameters.offering.offer.discountAnnualRateNumerator < *MIN_PLP_ANNUAL_DISCOUNT ||
preinit_parameters.offering.offer.discountAnnualRateNumerator > *MAX_PLP_ANNUAL_DISCOUNT ||
preinit_parameters.offering.offer.maxDiscountRateNumerator !=
preinit_parameters.permanentLiquidityShareNumerator ||
preinit_parameters.offeredTokenAmount <= BigInt::from(0) ||
preinit_parameters.offering.delphiCategory != DELPHI_TOKEN_ID ||
preinit_parameters.offering.platformFeeNFTH != platform_fee_nfth ||
preinit_parameters.offering.platformFeeNumerator < *PLATFORM_FEE ||
preinit_parameters.offering.executionFee < *ENTRY_EXECUTION_FEE {
is_valid_ido = false;
}
}
_ => {
return Err(anyhow::anyhow!("invalid announcement (2)"));
@ -903,7 +907,7 @@ async fn create_ido_context_from_preinit(network: Option<Network>, tx: &Transact
}
let preInitOut = tx.output.get(1);
if preInitOut.is_none() {
if preInitOut.is_none() {
return Err(anyhow::anyhow!("preinit output is not defined!"));
}
@ -948,12 +952,12 @@ async fn create_ido_context_from_preinit(network: Option<Network>, tx: &Transact
)
).to_bytes()
) != offeringBytecodeStorageOut.unwrap().script_pubkey {
return Err(anyhow::anyhow!("on_create_info, offering bytecode storage does not match!"));
return Err(anyhow::anyhow!("offering bytecode storage does not match!"));
}
let launcherBytecodeStorageOut = tx.output.get(3);
if launcherBytecodeStorageOut.is_none() {
return Err(anyhow::anyhow!("on_create_info, launcher bytecode storage not defined!"));
return Err(anyhow::anyhow!("launcher bytecode storage not defined!"));
}
if build_p2sh32_script(
&build_storage_script_with_data(
@ -1055,9 +1059,9 @@ async fn create_ido_context_from_preinit(network: Option<Network>, tx: &Transact
return Err(anyhow::anyhow!("offered token storage does not contain a token!"));
}
if build_p2sh32_script(&build_storage_script(1u32).to_bytes()) !=
offeredTokenStorageOut.unwrap().script_pubkey {
return Err(anyhow::anyhow!("offered token locking bytecode does not match!"));
}
offeredTokenStorageOut.unwrap().script_pubkey {
return Err(anyhow::anyhow!("offered token locking bytecode does not match!"));
}
let token_amount = BigInt::from(offeredTokenStorageOut.unwrap().token.as_ref().unwrap().amount);
if token_amount < requiredTokens {
return Err(anyhow::anyhow!("invalid offered token amount!"));
@ -1088,6 +1092,7 @@ async fn create_ido_context_from_preinit(network: Option<Network>, tx: &Transact
is_valid_ido: is_valid_ido,
offered_token_id: offered_token_id,
offering_token_id: None,
is_token_created_at_preinit: !offered_token_is_in_supply,
})
}
@ -1095,12 +1100,14 @@ async fn on_create_ido(
network: Option<Network>,
pool: &SqlitePool,
tx: &Transaction,
block_height: i64,
) -> Result<()> {
match create_ido_context_from_preinit(network, tx).await {
Ok(context) => {
// create the ido
let mut dbtx = pool.begin().await?;
let result = sqlx::query(
"INSERT INTO ido (preinit_txid, init_txid, launch_txid, offering_token_id, offered_token_id, status, parameters, state, is_valid, txchain_entrypoint, txchain_head)
"INSERT INTO ido (preinit_txid, init_txid, launch_txid, offering_token_id, offered_token_id, status, parameters, state, is_valid, is_token_created_at_preinit, txchain_entrypoint, txchain_head)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(context.preinit_txid)
@ -1112,43 +1119,29 @@ async fn on_create_ido(
.bind(serde_json::to_vec(&context.parameters).unwrap())
.bind(serde_json::to_vec(&context.state).unwrap())
.bind(context.is_valid_ido)
.bind(context.is_token_created_at_preinit)
.bind(None::<i64>)
.bind(None::<i64>)
.execute(pool)
.execute(&mut *dbtx)
.await;
match result {
Ok(r) => {
// insert txchain entrypoint
let ido_id = r.last_insert_rowid();
let serialized_tx = bitcoincash::consensus::serialize(tx);
let result2 = sqlx::query(
"INSERT INTO ido_txchain (prev_id, ido_id, txid, tx)
VALUES (?, ?, ?, ?)",
)
.bind(None::<i64>)
.bind(ido_id)
.bind(tx.txid().to_blob())
.bind(serialized_tx)
.execute(pool)
.await;
match result2 {
Ok(r2) => {
// update txchain_entrypoint & txchain_head for the ido
let item_id = r2.last_insert_rowid();
sqlx::query(
"UPDATE ido SET txchain_entrypoint = ?, txchain_head = ?
let txchain_item_id = upsert_ido_txchain(&mut dbtx, tx, ido_id, None::<i64>, block_height, 1)
.await?;
sqlx::query(
"UPDATE ido SET txchain_entrypoint = ?, txchain_head = ?
WHERE id = ?",
)
.bind(item_id)
.bind(item_id)
.bind(ido_id)
.execute(pool)
.await?;
Ok(())
}
Err(e) => Err(e.into()),
}
}
)
.bind(txchain_item_id)
.bind(txchain_item_id)
.bind(ido_id)
.execute(&mut *dbtx)
.await?;
dbtx.commit().await?;
Ok(())
},
Err(e) => Err(e.into()),
}
},
@ -1179,7 +1172,7 @@ fn parse_preinit_state_from_tx(
let redeem_script = Script::from(redeem_bytecode.to_vec());
let instructions: Vec<_> = redeem_script.instructions().collect();
if instructions.len() < 4 {
return Err(anyhow::anyhow!("preInitIn redeem script has less than 4 opcodes!"));
return Err(anyhow::anyhow!("preInitIn redeem script has less than 4 opcodes!"));
}
match &instructions[0] {
Ok(Instruction::PushBytes(stateOTokenGeneratedData)) => {
@ -1667,7 +1660,7 @@ async fn on_add_ido_tx(
) -> Result<()> {
let mut dbtx = pool.begin().await?;
let current_item = get_txchain_item_by_txid(pool, &tx.txid())
.await?;
.await?;
if current_item.is_some() && Some(current_item.unwrap().id) == ido.txchain_head {
// already added, only update block height
update_ido_txchain_tracker_block_height(&mut dbtx, tx, block_height)
@ -1682,7 +1675,7 @@ async fn on_add_ido_tx(
items_tx_map.insert(item.txid.clone(), tx_deser);
}
let mut new_chain: Vec<&IdoTxChainDBRecord> = Vec::new();
let mut items_copy: Vec<&IdoTxChainDBRecord> = items.iter().rev().collect();
let mut items_copy: Vec<&IdoTxChainDBRecord> = items.iter().rev().collect();
let mut current_item = prev_txchain_item;
new_chain.insert(0, current_item);
while current_item.prev_id.is_some() {
@ -1705,17 +1698,17 @@ async fn on_add_ido_tx(
let result = ido_add_tx(&context, item_tx)?;
apply_updates_to_context(&mut context, &result.updates);
updates.extend_from_slice(&result.updates);
}
}
// add the tx to the chain
let result = ido_add_tx(&context, tx)?;
apply_updates_to_context(&mut context, &result.updates);
updates.extend_from_slice(&result.updates);
let txchain_item_id = upsert_ido_txchain(&mut dbtx, tx, ido.id, Some(prev_txchain_item.id), block_height, result.next_output_index)
.await?;
.await?;
update_ido(&mut dbtx, ido.id, &context, txchain_item_id)
.await?;
// delete all entries
sqlx::query(
sqlx::query(
"DELETE FROM ido_entry WHERE ido_id = ?",
)
.bind(ido.id)
@ -1724,8 +1717,8 @@ async fn on_add_ido_tx(
// insert the entries of the new state
upsert_updates_to_ido_entries(&mut dbtx, ido.id, &updates)
.await?;
} else {
// create context from ido
} else {
// create context from ido
let mut context: IdoContext = IdoContext {
preinit_txid: ido.preinit_txid.clone(),
init_txid: ido.init_txid.clone(),
@ -1734,6 +1727,7 @@ async fn on_add_ido_tx(
parameters: serde_json::from_slice(&ido.parameters).expect("Failed to parse parameters"),
state: serde_json::from_slice(&ido.state).expect("Failed to parse state"),
is_valid_ido: ido.is_valid,
is_token_created_at_preinit: ido.is_token_created_at_preinit,
offered_token_id: ido.offered_token_id.clone(),
offering_token_id: ido.offering_token_id.clone(),
};
@ -1741,12 +1735,12 @@ async fn on_add_ido_tx(
let result = ido_add_tx(&context, tx)?;
apply_updates_to_context(&mut context, &result.updates);
let txchain_item_id = upsert_ido_txchain(&mut dbtx, tx, ido.id, Some(prev_txchain_item.id), block_height, result.next_output_index)
.await?;
.await?;
update_ido(&mut dbtx, ido.id, &context, txchain_item_id)
.await?;
upsert_updates_to_ido_entries(&mut dbtx, ido.id, &result.updates)
.await?;
}
}
dbtx.commit().await?;
Ok(())
}
@ -1755,9 +1749,9 @@ fn is_ido_sig_in_tx_inputs(tx: &Transaction) -> bool {
for input_index in [ 0, 1 ] {
let input = tx.input.get(input_index);
if input.is_some() {
if has_script_ido_signature(&input.unwrap().script_sig) {
return true;
}
if has_script_ido_signature(&input.unwrap().script_sig) {
return true;
}
}
}
return false;
@ -1774,32 +1768,38 @@ pub async fn index_block(
for tx in sorted_txs {
// detect a new ido
if is_preinit_broadcast(tx) {
on_create_ido(network, pool, tx)
.await?;
match on_create_ido(network, pool, tx, block_height)
.await {
Err(err) => info!("failed to detect an ido, or an invalid ido detected, txid: {}, {}", hex::encode(tx.txid().to_blob()), err),
_ => (),
}
} else if is_ido_sig_in_tx_inputs(tx) {
// has ido sig
for input_index in [ 0, 1, 3 ] {
let input = tx.input.get(input_index);
if input.is_some() {
if let Some(txchain_item) =
txchain_lookup_next(
pool,
&input.unwrap().previous_output.txid,
input.unwrap().previous_output.vout
)
.await?
{
if let Some(txchain_item) =
txchain_lookup_next(
pool,
&input.unwrap().previous_output.txid,
input.unwrap().previous_output.vout
)
.await?
{
let ido = ido_lookup(pool, txchain_item.ido_id)
.await?
.expect("ido record not found!!");
on_add_ido_tx(network, pool, &ido, &txchain_item, tx, block_height)
.await?;
}
.expect("ido record not found!!");
match on_add_ido_tx(network, pool, &ido, &txchain_item, tx, block_height)
.await {
Err(err) => info!("add tx to an ido failed, txid: {}, {}", hex::encode(tx.txid().to_blob()), err),
_ => (),
}
}
}
}
}
}
txchain_trim_tracker(pool, block_height)
txchain_trim_tracker(pool, block_height)
.await?;
Ok(())
}