|
| 1 | +class BitcoinVoutSpentCheckerWorker |
| 2 | + include Sidekiq::Job |
| 3 | + sidekiq_options retry: 0, queue: :bitcoin |
| 4 | + |
| 5 | + ZERO_TXID = "0000000000000000000000000000000000000000000000000000000000000000".freeze |
| 6 | + |
| 7 | + def perform |
| 8 | + unspent_outpoints.each do |txid, index| |
| 9 | + fallback_networks = ENV["CKB_NET_MODE"] == CKB::MODE::MAINNET ? [:mainnet] : %i[testnet signet] |
| 10 | + fallback_networks.each do |network| |
| 11 | + result = check_outspent(txid, index, network: network) |
| 12 | + break if %i[spent unspent].include?(result) |
| 13 | + end |
| 14 | + end |
| 15 | + end |
| 16 | + |
| 17 | + def unspent_outpoints |
| 18 | + desired_limit = ENV["CKB_NET_MODE"] == CKB::MODE::MAINNET ? 166 : 2000 |
| 19 | + vouts = BitcoinVout.includes(:bitcoin_transaction).without_op_return.where(consumed_by_id: nil).order(id: :asc).limit(desired_limit * 2) |
| 20 | + if (last_id = $redis.get("btc:vout:last_request_id")).present? |
| 21 | + vouts = vouts.where("id > ?", last_id.to_i) |
| 22 | + end |
| 23 | + |
| 24 | + outpoints = [] |
| 25 | + vout_ids = [] |
| 26 | + |
| 27 | + vouts.each do |vout| |
| 28 | + key = [vout.bitcoin_transaction.txid, vout.index] |
| 29 | + next if outpoints.include?(key) |
| 30 | + |
| 31 | + outpoints << key |
| 32 | + vout_ids << vout.id |
| 33 | + break if outpoints.size >= desired_limit |
| 34 | + end |
| 35 | + |
| 36 | + $redis.set("btc:vout:last_request_id", vout_ids.max) |
| 37 | + outpoints |
| 38 | + end |
| 39 | + |
| 40 | + def check_outspent(txid, index, network:) |
| 41 | + cache_key = "unisat:#{network}:tx:#{txid}" |
| 42 | + vouts = Rails.cache.read(cache_key) |
| 43 | + if vouts.nil? |
| 44 | + vouts = fetch_unisat_vouts(txid, network) |
| 45 | + Rails.cache.write(cache_key, vouts, expires_in: 30.minutes) if vouts.present? |
| 46 | + end |
| 47 | + |
| 48 | + return :not_found if vouts.nil? |
| 49 | + |
| 50 | + out = vouts.detect { |o| o["vout"] == index } |
| 51 | + spent_txid = out&.dig("txidSpent") |
| 52 | + |
| 53 | + if spent_txid.present? && spent_txid != ZERO_TXID |
| 54 | + resolve_binding_status(spent_txid, txid, index) |
| 55 | + Rails.logger.info("Unisat: #{txid}:#{index} on #{network} => spent => #{spent_txid}") |
| 56 | + return :spent |
| 57 | + end |
| 58 | + |
| 59 | + Rails.logger.info("Unisat: #{txid}:#{index} on #{network} => unspent") |
| 60 | + :unspent |
| 61 | + rescue StandardError => e |
| 62 | + Rails.logger.error("check_outspent failed #{txid}:#{index} on #{network} - #{e.class}: #{e.message}") |
| 63 | + :unknown |
| 64 | + end |
| 65 | + |
| 66 | + def fetch_unisat_vouts(txid, network) |
| 67 | + # testnet: 10 RPS, 864000/day |
| 68 | + # mainnet: 5 RPS, 2000/day |
| 69 | + host = ENV.fetch("UNISAT_#{network.to_s.upcase}_HOST", nil) |
| 70 | + token = ENV.fetch("UNISAT_#{network.to_s.upcase}_TOKEN", nil) |
| 71 | + headers = { "accept" => "application/json", "Authorization" => "Bearer #{token}" } |
| 72 | + |
| 73 | + all = [] |
| 74 | + cursor = 0 |
| 75 | + size = 1000 |
| 76 | + |
| 77 | + loop do |
| 78 | + url = "#{host}/v1/indexer/tx/#{txid}/outs?cursor=#{cursor}&size=#{size}" |
| 79 | + response = HTTP.timeout(60).headers(headers).get(url) |
| 80 | + sleep(network == :mainnet ? 0.4 : 0.2) |
| 81 | + |
| 82 | + body = JSON.parse(response.body.to_s) |
| 83 | + if body["code"] != 0 || !body["data"].is_a?(Array) |
| 84 | + # Rails.logger.warn("Unisat error #{txid} on #{network}: #{body['msg']}") |
| 85 | + return nil |
| 86 | + end |
| 87 | + |
| 88 | + all += body["data"] |
| 89 | + break if body["data"].size < size |
| 90 | + |
| 91 | + cursor += size |
| 92 | + end |
| 93 | + |
| 94 | + all |
| 95 | + rescue StandardError => e |
| 96 | + Rails.logger.error("fetch_unisat_vouts failed: #{txid} on #{network} - #{e.class}: #{e.message}") |
| 97 | + nil |
| 98 | + end |
| 99 | + |
| 100 | + def resolve_binding_status(consumed_txid, txid, index) |
| 101 | + consumed_by = find_consumed_by_transaction(consumed_txid) |
| 102 | + return unless consumed_by |
| 103 | + |
| 104 | + bitcoin_vouts = BitcoinVout.includes(:bitcoin_transaction). |
| 105 | + where( |
| 106 | + bitcoin_transactions: { txid: }, |
| 107 | + bitcoin_vouts: { index:, op_return: false }, |
| 108 | + ) |
| 109 | + related_cell_outputs = bitcoin_vouts.filter_map(&:cell_output) |
| 110 | + |
| 111 | + if related_cell_outputs.all?(&:live?) |
| 112 | + bitcoin_vouts.update_all(status: "binding") |
| 113 | + else |
| 114 | + bitcoin_vouts.each do |vout| |
| 115 | + next unless vout.cell_output |
| 116 | + next if vout.normal? || vout.unbound? |
| 117 | + |
| 118 | + status = vout.cell_output.dead? ? "normal" : "unbound" |
| 119 | + vout.update(consumed_by:, status:) |
| 120 | + end |
| 121 | + end |
| 122 | + end |
| 123 | + |
| 124 | + def find_consumed_by_transaction(txid) |
| 125 | + # check whether consumed_by has been synchronized |
| 126 | + consumed_by = BitcoinTransaction.find_by(txid:) |
| 127 | + unless consumed_by |
| 128 | + raw_tx = fetch_raw_transaction(txid) |
| 129 | + return nil unless raw_tx |
| 130 | + |
| 131 | + consumed_by = BitcoinTransaction.create!( |
| 132 | + txid: raw_tx["txid"], |
| 133 | + tx_hash: raw_tx["hash"], |
| 134 | + time: raw_tx["time"], |
| 135 | + block_hash: raw_tx["blockhash"], |
| 136 | + block_height: 0, |
| 137 | + ) |
| 138 | + end |
| 139 | + consumed_by |
| 140 | + end |
| 141 | + |
| 142 | + def fetch_raw_transaction(txid) |
| 143 | + data = Rails.cache.read(txid) |
| 144 | + data ||= Bitcoin::Rpc.instance.getrawtransaction(txid, 2) |
| 145 | + Rails.cache.write(txid, data, expires_in: 10.minutes) unless Rails.cache.exist?(txid) |
| 146 | + data["result"] |
| 147 | + rescue StandardError => e |
| 148 | + Rails.logger.error "get bitcoin raw transaction #{txid} failed: #{e}" |
| 149 | + nil |
| 150 | + end |
| 151 | +end |
0 commit comments