From a34cc034827cc26a66a4b69e9030a489305e9519 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Thu, 11 Apr 2024 13:16:36 +0800 Subject: [PATCH] feat: remove raw bitcoin transaction cache (#1776) --- app/jobs/import_bitcoin_utxo_job.rb | 18 ++++++------------ app/models/bitcoin_transaction.rb | 10 ++++++++++ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/app/jobs/import_bitcoin_utxo_job.rb b/app/jobs/import_bitcoin_utxo_job.rb index 6c3c618c0..7c647b903 100644 --- a/app/jobs/import_bitcoin_utxo_job.rb +++ b/app/jobs/import_bitcoin_utxo_job.rb @@ -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) @@ -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 @@ -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 diff --git a/app/models/bitcoin_transaction.rb b/app/models/bitcoin_transaction.rb index 25e2c0fc6..718623961 100644 --- a/app/models/bitcoin_transaction.rb +++ b/app/models/bitcoin_transaction.rb @@ -12,6 +12,7 @@ def confirmations nil end + refresh_block_height! if block_hash.blank? tip_block_height ? tip_block_height - block_height : 0 end @@ -19,6 +20,15 @@ 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