weixin_58911309 2024-05-27 18:46 采纳率: 0%
浏览 2
已结题

比特币ord程序wallet_constructor.rs文件支持一次性铸造1000个代币,并将它们分配到40个UTXO上(每个UTXO上分配25个代币),并设置找零地址(相关搜索:比特币)

添加对铸造1000个代币的逻辑。
将1000个代币分配到40个UTXO上,每个UTXO上分配25个代币。
设置找零地址。
加威信:TanWang2022 指导200元感谢
以下是原文件代码

use super::*;

#[derive(Clone)]
pub(crate) struct WalletConstructor {
  ord_client: reqwest::blocking::Client,
  name: String,
  no_sync: bool,
  rpc_url: Url,
  settings: Settings,
}

impl WalletConstructor {
  pub(crate) fn construct(
    name: String,
    no_sync: bool,
    settings: Settings,
    rpc_url: Url,
  ) -> Result<Wallet> {
    let mut headers = HeaderMap::new();
    headers.insert(
      header::ACCEPT,
      header::HeaderValue::from_static("application/json"),
    );

    if let Some((username, password)) = settings.credentials() {
      let credentials =
        base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
      headers.insert(
        header::AUTHORIZATION,
        header::HeaderValue::from_str(&format!("Basic {credentials}")).unwrap(),
      );
    }

    Self {
      ord_client: reqwest::blocking::ClientBuilder::new()
        .timeout(None)
        .default_headers(headers.clone())
        .build()?,
      name,
      no_sync,
      rpc_url,
      settings,
    }
    .build()
  }

  pub(crate) fn build(self) -> Result<Wallet> {
    let database = Wallet::open_database(&self.name, &self.settings)?;

    let bitcoin_client = {
      let client =
        Wallet::check_version(self.settings.bitcoin_rpc_client(Some(self.name.clone()))?)?;

      if !client.list_wallets()?.contains(&self.name) {
        client.load_wallet(&self.name)?;
      }

      if client.get_wallet_info()?.private_keys_enabled {
        Wallet::check_descriptors(&self.name, client.list_descriptors(None)?.descriptors)?;
      }

      client
    };

    let chain_block_count = bitcoin_client.get_block_count().unwrap() + 1;

    if !self.no_sync {
      for i in 0.. {
        let response = self.get("/blockcount")?;

        if response
          .text()?
          .parse::<u64>()
          .expect("wallet failed to talk to server. Make sure `ord server` is running.")
          >= chain_block_count
        {
          break;
        } else if i == 20 {
          bail!("wallet failed to synchronize with `ord server` after {i} attempts");
        }
        std::thread::sleep(Duration::from_millis(50));
      }
    }

    let mut utxos = Self::get_utxos(&bitcoin_client)?;
    let locked_utxos = Self::get_locked_utxos(&bitcoin_client)?;
    utxos.extend(locked_utxos.clone());

    let output_info = self.get_output_info(utxos.clone().into_keys().collect())?;

    let inscriptions = output_info
      .iter()
      .flat_map(|(_output, info)| info.inscriptions.clone())
      .collect::<Vec<InscriptionId>>();

    let (inscriptions, inscription_info) = self.get_inscriptions(&inscriptions)?;

    let status = self.get_server_status()?;

    Ok(Wallet {
      bitcoin_client,
      database,
      has_rune_index: status.rune_index,
      has_sat_index: status.sat_index,
      inscription_info,
      inscriptions,
      locked_utxos,
      ord_client: self.ord_client,
      output_info,
      rpc_url: self.rpc_url,
      settings: self.settings,
      utxos,
    })
  }

  fn get_output_info(&self, outputs: Vec<OutPoint>) -> Result<BTreeMap<OutPoint, api::Output>> {
    let response = self.post("/outputs", &outputs)?;

    if !response.status().is_success() {
      bail!("wallet failed get outputs: {}", response.text()?);
    }

    let output_info: BTreeMap<OutPoint, api::Output> = outputs
      .into_iter()
      .zip(serde_json::from_str::<Vec<api::Output>>(&response.text()?)?)
      .collect();

    for (output, info) in &output_info {
      if !info.indexed {
        bail!("output in wallet but not in ord server: {output}");
      }
    }

    Ok(output_info)
  }

  fn get_inscriptions(
    &self,
    inscriptions: &Vec<InscriptionId>,
  ) -> Result<(
    BTreeMap<SatPoint, Vec<InscriptionId>>,
    BTreeMap<InscriptionId, api::Inscription>,
  )> {
    let response = self.post("/inscriptions", inscriptions)?;

    if !response.status().is_success() {
      bail!("wallet failed get inscriptions: {}", response.text()?);
    }

    let mut inscriptions = BTreeMap::new();
    let mut inscription_infos = BTreeMap::new();
    for info in serde_json::from_str::<Vec<api::Inscription>>(&response.text()?)? {
      inscriptions
        .entry(info.satpoint)
        .or_insert_with(Vec::new)
        .push(info.id);

      inscription_infos.insert(info.id, info);
    }

    Ok((inscriptions, inscription_infos))
  }

  fn get_utxos(bitcoin_client: &Client) -> Result<BTreeMap<OutPoint, TxOut>> {
    Ok(
      bitcoin_client
        .list_unspent(None, None, None, None, None)?
        .into_iter()
        .map(|utxo| {
          let outpoint = OutPoint::new(utxo.txid, utxo.vout);
          let txout = TxOut {
            script_pubkey: utxo.script_pub_key,
            value: utxo.amount.to_sat(),
          };

          (outpoint, txout)
        })
        .collect(),
    )
  }

  fn get_locked_utxos(bitcoin_client: &Client) -> Result<BTreeMap<OutPoint, TxOut>> {
    #[derive(Deserialize)]
    pub(crate) struct JsonOutPoint {
      txid: Txid,
      vout: u32,
    }

    let outpoints = bitcoin_client.call::<Vec<JsonOutPoint>>("listlockunspent", &[])?;

    let mut utxos = BTreeMap::new();

    for outpoint in outpoints {
      let Some(tx_out) = bitcoin_client.get_tx_out(&outpoint.txid, outpoint.vout, Some(false))?
      else {
        continue;
      };

      utxos.insert(
        OutPoint::new(outpoint.txid, outpoint.vout),
        TxOut {
          value: tx_out.value.to_sat(),
          script_pubkey: ScriptBuf::from_bytes(tx_out.script_pub_key.hex),
        },
      );
    }

    Ok(utxos)
  }

  fn get_server_status(&self) -> Result<api::Status> {
    let response = self.get("/status")?;

    if !response.status().is_success() {
      bail!("could not get status: {}", response.text()?)
    }

    Ok(serde_json::from_str(&response.text()?)?)
  }

  pub fn get(&self, path: &str) -> Result<reqwest::blocking::Response> {
    self
      .ord_client
      .get(self.rpc_url.join(path)?)
      .send()
      .map_err(|err| anyhow!(err))
  }

  pub fn post(&self, path: &str, body: &impl Serialize) -> Result<reqwest::blocking::Response> {
    self
      .ord_client
      .post(self.rpc_url.join(path)?)
      .json(body)
      .header(reqwest::header::ACCEPT, "application/json")
      .send()
      .map_err(|err| anyhow!(err))
  }
}


  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2024-05-27 18:52
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    在比特币ord程序中添加逻辑以一次性铸造1000个代币并分配到40个UTXO上,以及设置找零地址,需要对现有的WalletConstructor结构体及其方法进行扩展。以下是一些可能的步骤和代码示例,用于实现这一功能:

    1. 准备铭文内容和UTXOs

    首先,需要准备铭文内容(代币信息)和可用的UTXOs。这可能涉及到调用比特币网络的接口来获取当前钱包的UTXO列表。

    2. 分配代币到UTXOs

    接下来,需要编写逻辑来将1000个代币分配到40个UTXO上,每个UTXO分配25个代币。这可能需要创建多个输出,每个输出包含25个代币的铭文信息。

    3. 设置找零地址

    在分配代币后,需要设置一个找零地址来接收剩余的比特币。这通常涉及到计算总交易费用,并确保找零地址能够接收剩余的比特币。

    4. 构建并发送交易

    最后,需要构建包含上述逻辑的交易,并将其发送到比特币网络。

    以下是一些伪代码示例,用于指导如何实现上述步骤:

    impl WalletConstructor {
      // ... 现有代码 ...
    
      pub(crate) fn mint_tokens_and_distribute(&self, token_count: u64, utxo_count: usize, change_address: String) -> Result<()> {
        // 获取当前钱包的UTXO列表
        let utxos = self.get_utxos(&self.bitcoin_client)?;
    
        // 确保有足够的UTXO来分配代币
        if utxos.len() < utxo_count {
          bail!("Not enough UTXOs to distribute tokens.");
        }
    
        // 准备铭文内容和交易输出
        let mut outputs = Vec::new();
        for _ in 0..token_count {
          let铭文内容 = ...; // 准备铭文内容
          outputs.push(铭文内容);
        }
    
        // 分配代币到UTXOs
        for (index, utxo) in utxos.iter().enumerate() {
          if index >= utxo_count {
            break;
          }
          // 为每个UTXO创建一个包含25个代币的输出
          let output = ...; // 创建输出逻辑
          outputs.push(output);
        }
    
        // 设置找零地址
        let change_output = TxOut {
          script_pubkey: ..., // change_address的script_pubkey
          value: ..., // 计算找零金额
        };
        outputs.push(change_output);
    
        // 构建交易
        let tx = self.build_transaction(utxos, outputs)?;
    
        // 发送交易到比特币网络
        self.send_transaction(tx)
      }
    
      // 构建交易的逻辑
      fn build_transaction(&self, utxos: BTreeMap<OutPoint, TxOut>, outputs: Vec<TxOut>) -> Result<Transaction> {
        // ... 构建交易逻辑 ...
      }
    
      // 发送交易的逻辑
      fn send_transaction(&self, tx: Transaction) -> Result<()> {
        // ... 发送交易逻辑 ...
      }
    }
    

    请注意,上述代码仅为示例,实际实现可能需要根据具体的程序逻辑和比特币网络的API进行调整。

    参考资料

    关于UTXO模型、铭文交易构建过程以及找零地址的设置,可以参考以下资料:

    1. 深入区块链技术(八):UTXO与普通账户模型[^1^]
    2. Ordinal铭文协议的原理与技术细节讨论[^5^]
    3. Ordinals Inscription铸造过程解析[^4^]
    4. UTXO:加密货币模型如何运作[^9^]

    这些资料提供了关于UTXO模型、铭文交易的构建过程以及如何在比特币交易中设置找零地址的详细信息。在实现上述功能时,可以参考这些资料来获取更深入的理解。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月27日
  • 创建了问题 5月27日

悬赏问题

  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 在虚拟机环境下完成以下,要求截图!
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见