Module: BSV::Network::Util
- Defined in:
- lib/bsv/network/util.rb
Overview
Shared utility methods for protocol implementations.
Class Method Summary collapse
-
.resolve_tx_hex(tx) ⇒ String
Coerce a transaction input to hex.
-
.safe_parse_json(raw) ⇒ Object
Parse JSON, returning a hash with a ‘detail’ key on parse failure.
Class Method Details
.resolve_tx_hex(tx) ⇒ String
Coerce a transaction input to hex.
Accepts (in order of preference):
-
Hex string — pass-through, zero conversion
-
Binary string — convert to hex
-
Transaction object — prefer EF hex (BRC-30), fall back to raw hex
Detection uses content, not encoding: a string is hex if it has even length and contains only hex characters. This handles hex strings tagged as ASCII-8BIT (e.g. read from IO in binary mode).
Empty input is rejected — an empty transaction cannot meaningfully be broadcast and any downstream ‘rawTx: ”` body is a sign of a caller bug, not valid traffic.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/bsv/network/util.rb', line 35 def self.resolve_tx_hex(tx) if tx.is_a?(String) raise ArgumentError, 'tx cannot be empty — refusing to construct an empty broadcast' if tx.empty? return tx if tx.match?(/\A[0-9a-fA-F]+\z/) && tx.length.even? return tx.unpack1('H*') end begin tx.to_ef_hex rescue ArgumentError => e BSV.logger&.debug { "[Network::Util] EF serialisation failed: #{e.} — falling back to raw hex" } tx.to_hex end end |
.safe_parse_json(raw) ⇒ Object
Parse JSON, returning a hash with a ‘detail’ key on parse failure. When the raw input is nil or empty the detail is nil (not an empty string).
11 12 13 14 15 |
# File 'lib/bsv/network/util.rb', line 11 def self.safe_parse_json(raw) JSON.parse(raw.to_s) rescue JSON::ParserError { 'detail' => (raw.to_s.empty? ? nil : raw.to_s) } end |