Class: BSV::Transaction::ChainTrackers::WhatsOnChain

Inherits:
BSV::Transaction::ChainTracker show all
Defined in:
lib/bsv/transaction/chain_trackers/whats_on_chain.rb

Overview

Chain tracker that verifies merkle roots using the WhatsOnChain API.

Queries the WoC block header endpoint to retrieve the merkle root for a given block height and compares it with the provided root.

Examples:

tracker = BSV::Transaction::ChainTrackers::WhatsOnChain.new
tracker.valid_root_for_height?('abcd...', 800_000)

Constant Summary collapse

BASE_URL =
'https://api.whatsonchain.com'
NETWORKS =
{
  main: 'main',
  mainnet: 'main',
  test: 'test',
  testnet: 'test',
  stn: 'stn'
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(network: :main, api_key: nil, http_client: nil) ⇒ WhatsOnChain

Returns a new instance of WhatsOnChain.

Parameters:

  • network (Symbol) (defaults to: :main)

    :main, :mainnet, :test, :testnet, or :stn

  • api_key (String, nil) (defaults to: nil)

    optional WoC API key

  • http_client (#request, nil) (defaults to: nil)

    injectable HTTP client for testing



32
33
34
35
36
37
# File 'lib/bsv/transaction/chain_trackers/whats_on_chain.rb', line 32

def initialize(network: :main, api_key: nil, http_client: nil)
  super()
  @network = NETWORKS.fetch(network) { raise ArgumentError, "unknown network: #{network}" }
  @api_key = api_key
  @http_client = http_client
end

Instance Method Details

#current_heightInteger

Return the current blockchain height.

Returns:

  • (Integer)


55
56
57
58
59
# File 'lib/bsv/transaction/chain_trackers/whats_on_chain.rb', line 55

def current_height
  response = get("/v1/bsv/#{@network}/chain/info", not_found_returns_nil: false)
  data = JSON.parse(response.body)
  data['blocks']
end

#valid_root_for_height?(root, height) ⇒ Boolean

Verify that a merkle root is valid for the given block height.

Parameters:

  • root (String)

    merkle root as a hex string

  • height (Integer)

    block height

Returns:

  • (Boolean)


44
45
46
47
48
49
50
# File 'lib/bsv/transaction/chain_trackers/whats_on_chain.rb', line 44

def valid_root_for_height?(root, height)
  response = get("/v1/bsv/#{@network}/block/#{height}/header")
  return false if response.nil?

  data = JSON.parse(response.body)
  data['merkleroot'].downcase == root.downcase
end