Skip to content

Commit

Permalink
feat: remove raw bitcoin transaction cache (#1776)
Browse files Browse the repository at this point in the history
  • Loading branch information
rabbitz committed Apr 11, 2024
1 parent 41696de commit a34cc03
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
18 changes: 6 additions & 12 deletions app/jobs/import_bitcoin_utxo_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def perform(cell_id)
Rails.logger.info("Importing bitcoin utxo #{txid} out_index #{out_index}")
vout_attributes = []
# build bitcoin transaction
raw_tx = fetch_raw_transaction(txid)
raw_tx = rpc.getrawtransaction(txid, 2)
tx = build_transaction!(raw_tx)
# build op_returns
op_returns = build_op_returns!(raw_tx, tx, cell_output.ckb_transaction, vout_attributes)
Expand All @@ -36,14 +36,16 @@ def build_transaction!(raw_tx)
tx = BitcoinTransaction.find_by(txid: raw_tx["txid"])
return tx if tx

# avoid making multiple RPC requests
block_header = rpc.getblockheader(raw_tx["blockhash"])
# raw transactions may not include the block hash
if raw_tx["blockhash"].present?
block_header = rpc.getblockheader(raw_tx["blockhash"])
end
BitcoinTransaction.create!(
txid: raw_tx["txid"],
tx_hash: raw_tx["hash"],
time: raw_tx["time"],
block_hash: raw_tx["blockhash"],
block_height: block_header["height"],
block_height: block_header&.dig("height") || 0,
)
end

Expand Down Expand Up @@ -103,14 +105,6 @@ def build_address!(address_hash, cell_output)
bitcoin_address
end

def fetch_raw_transaction(txid)
Rails.cache.fetch("bitcoin_transactions/#{txid}", expires_in: 1.hour) do
rpc.getrawtransaction(txid, 2)
rescue StandardError => e
raise ArgumentError, "get bitcoin raw transaction #{txid} failed: #{e}"
end
end

def rpc
@rpc ||= Bitcoin::Rpc.instance
end
Expand Down
10 changes: 10 additions & 0 deletions app/models/bitcoin_transaction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,23 @@ def confirmations
nil
end

refresh_block_height! if block_hash.blank?
tip_block_height ? tip_block_height - block_height : 0
end

def ckb_transaction_hash
ckb_transaction = bitcoin_vouts&.take&.ckb_transaction
return ckb_transaction.tx_hash if ckb_transaction
end

def refresh_block_height!
rpc = Bitcoin::Rpc.instance
raw_transaction = rpc.getrawtransaction(txid, 2)
block_header = rpc.getblockheader(raw_transaction["blockhash"])
update(block_hash: raw_transaction["blockhash"], block_height: block_header["height"])
rescue StandardError => e
Rails.logger.error "refresh block height error: #{e.message}"
end
end

# == Schema Information
Expand Down

0 comments on commit a34cc03

Please sign in to comment.