Skip to content

Commit

Permalink
refactor: query bitcoin raw transactions with multiple txids (#1698)
Browse files Browse the repository at this point in the history
  • Loading branch information
rabbitz authored Mar 21, 2024
1 parent 1cebf8a commit 51c6a70
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
35 changes: 24 additions & 11 deletions app/controllers/api/v2/bitcoin_transactions_controller.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
module Api
module V2
class BitcoinTransactionsController < BaseController
def raw
expires_in 1.minute, public: true, must_revalidate: true, stale_while_revalidate: 10.seconds
def query
cache_keys = params[:txids]
res = Rails.cache.read_multi(*cache_keys)

raw_transaction = rpc.getrawtransaction(params[:id], 2)
if raw_transaction.dig("error").present?
head :not_found
else
render json: raw_transaction
not_cached = cache_keys - res.keys
to_cache = {}

get_raw_transactions(not_cached).each do |tx|
next if tx.dig("error").present?

txid = tx.dig("result", "txid")
res[txid] = tx
to_cache[txid] = tx
end

Rails.cache.write_multi(to_cache, expires_in: 10.minutes) unless to_cache.empty?

render json: res
rescue StandardError => e
Rails.logger.error "get raw transaction(#{params[:id]}) faild: #{e.message}"
head :not_found
Rails.logger.error "get raw transaction(#{params[:txids]}) failed: #{e.message}"
render json: {}, status: :not_found
end

private

def rpc
@rpc ||= Bitcoin::Rpc.instance
def get_raw_transactions(txids)
payload = txids.map.with_index do |txid, index|
{ jsonrpc: "1.0", id: index + 1, method: "getrawtransaction", params: [txid, 2] }
end
response = HTTP.timeout(10).post(ENV["BITCOIN_NODE_URL"], json: payload)
JSON.parse(response.to_s)
end
end
end
Expand Down
4 changes: 1 addition & 3 deletions config/routes/v2.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace :api do
namespace :v2 do
post "/das_accounts" => "das_accounts#query", as: :das_accounts
post "/bitcoin_transactions" => "bitcoin_transactions#query", as: :bitcoin_transactions
resources :ckb_transactions, only: %i[index show] do
member do
get :details
Expand Down Expand Up @@ -90,8 +91,5 @@
end
end
end
resources :bitcoin_transactions do
get :raw, on: :member
end
end
end

0 comments on commit 51c6a70

Please sign in to comment.