Crate brk_types

Crate brk_types 

Source
Expand description

§brk_types

Domain types for Bitcoin data analysis with serialization and indexing support.

§What It Enables

Work with Bitcoin primitives (heights, satoshis, addresses, transactions) through purpose-built types that handle encoding, arithmetic, time conversions, and database storage automatically.

§Key Features

  • Bitcoin primitives: Height, Sats, Txid, BlockHash, Outpoint with full arithmetic and conversion support
  • Address types: All output types (P2PK33, P2PK65, P2PKH, P2MS, P2SH, P2WPKH, P2WSH, P2TR, P2A, OP_RETURN) with address index variants
  • Time indexes: DateIndex, WeekIndex, MonthIndex, QuarterIndex, SemesterIndex, YearIndex, DecadeIndex with cross-index conversion
  • Protocol types: DifficultyEpoch, HalvingEpoch, TxVersion, RawLocktime
  • Financial types: Dollars, Cents, OHLC (Open/High/Low/Close)
  • Serialization: Serde + JSON Schema generation via schemars
  • Compression: PCO (Pco) derive for columnar compression in vecdb

§Type Categories

CategoryExamples
Block metadataHeight, BlockHash, BlockTimestamp, BlkPosition
TransactionTxid, TxIndex, TxIn, TxOut, Vsize, Weight
AddressP2PKHAddressIndex, P2TRBytes, AnyAddressIndex, AddressStats
ValueSats, Dollars, Cents, Bitcoin
TimeDate, DateIndex, WeekIndex, MonthIndex, …
MetricMetric, MetricData, MetricSelection
APIPagination, Health, RecommendedFees, MempoolInfo

§Core API

All types implement standard traits: Debug, Clone, Serialize, Deserialize, plus domain-specific operations like CheckedSub, Formattable, and PrintableIndex.

use brk_types::{Height, Sats, DateIndex, Date};

let height = Height::new(840_000);
let reward = Sats::FIFTY_BTC / 16;  // Post-4th-halving reward
let date_idx = DateIndex::try_from(Date::new(2024, 4, 20))?;

§Built On

  • brk_error for error handling

Structs§

Address
Bitcoin address string
AddressChainStats
Address statistics on the blockchain (confirmed transactions only)
AddressHash
AddressIndexOutPoint
AddressIndexTxIndex
AddressMempoolStats
Address statistics in the mempool (unconfirmed transactions only)
AddressParam
AddressStats
Address information compatible with mempool.space API format
AddressTxidsParam
AddressValidation
Address validation result
Age
Represents the age of a UTXO or address balance. Encapsulates all age-related calculations in one type-safe struct.
AnyAddressIndex
Unified index for any address type (loaded or empty)
Bitcoin
Bitcoin amount as floating point (1 BTC = 100,000,000 satoshis)
BlkMetadata
BlkPosition
Position within a .blk file, encoding file index and byte offset
Block
BlockCountParam
BlockFeeRatesEntry
A single block fee rates data point with percentiles.
BlockFeesEntry
A single block fees data point.
BlockHash
Block hash
BlockHashParam
BlockHashPrefix
BlockHashStartIndex
BlockHashTxIndex
BlockInfo
Block information returned by the API
BlockRewardsEntry
A single block rewards data point.
BlockSizeEntry
A single block size data point.
BlockSizesWeights
Combined block sizes and weights response.
BlockStatus
Block status indicating whether block is in the best chain
BlockTimestamp
Block information returned for timestamp queries
BlockWeightEntry
A single block weight data point.
Cents
CentsCompact
Compact representation of USD cents as i32.
Close
Closing price value for a time period
ComputeIndexes
Extended indexes with time-based granularities. Used by brk_computer for time-series aggregation.
DataRange
Range parameters for slicing data
DataRangeFormat
Data range with output format for API query parameters
Date
Date in YYYYMMDD format stored as u32
DateIndex
DecadeIndex
DetailedMetricCount
Detailed metric count with per-database breakdown
DifficultyAdjustment
Difficulty adjustment information.
DifficultyAdjustmentEntry
A single difficulty adjustment entry. Serializes as array: [timestamp, height, difficulty, change_percent]
DifficultyEntry
A single difficulty data point.
DifficultyEpoch
DiskUsage
Disk usage of the indexed data
Dollars
US Dollar amount as floating point
EmptyAddressData
Data of an empty address
EmptyAddressIndex
EmptyOutputIndex
Exit
Graceful shutdown coordinator for ensuring data consistency during program exit.
FeeRate
Fee rate in sats/vB
FeeRatePercentiles
Fee rate percentiles (min, 10%, 25%, 50%, 75%, 90%, max).
HalvingEpoch
HashrateEntry
A single hashrate data point.
HashrateSummary
Summary of network hashrate and difficulty data.
Health
Server health status
Height
Block height
HeightParam
Hex
Hex-encoded string
High
Highest price value for a time period
IndexInfo
Information about an available index and its query aliases
Indexes
Blockchain-level indexes tracking current positions for various entity types. Used by brk_indexer during block processing.
JSONPool
Limit
Maximum number of results to return. Defaults to 100 if not specified.
LimitParam
LoadedAddressData
Data for a loaded (non-empty) address with current balance
LoadedAddressIndex
Low
Lowest price value for a time period
MempoolBlock
Block info in a mempool.space like format for fee estimation.
MempoolEntryInfo
Mempool entry info from Bitcoin Core’s getrawmempool verbose
MempoolInfo
Mempool statistics
Metric
Metric name
MetricCount
Metric count statistics - distinct metrics and total metric-index combinations
MetricData
Metric data with range information.
MetricLeaf
Leaf node containing metric metadata
MetricLeafWithSchema
MetricLeaf with JSON Schema for client generation
MetricParam
MetricSelection
Selection of metrics to query
MetricSelectionLegacy
Legacy metric selection parameters (deprecated)
MetricWithIndex
Metrics
Comma-separated list of metric names
MonthIndex
OHLCCents
OHLC (Open, High, Low, Close) data in cents
OHLCDollars
OHLC (Open, High, Low, Close) data in dollars
OHLCSats
OHLC (Open, High, Low, Close) data in satoshis
OpReturnIndex
Open
Opening price value for a time period
OutPoint
P2AAddressIndex
P2ABytes
P2MSOutputIndex
P2PK33AddressIndex
P2PK33Bytes
P2PK65AddressIndex
P2PK65Bytes
P2PKHAddressIndex
P2PKHBytes
P2SHAddressIndex
P2SHBytes
P2TRAddressIndex
P2TRBytes
P2WPKHAddressIndex
P2WPKHBytes
P2WSHAddressIndex
P2WSHBytes
PaginatedMetrics
A paginated list of available metric names (1000 per page)
Pagination
Pagination parameters for paginated API endpoints
PaginationIndex
Pagination parameters with an index filter
Pool
Mining pool information
PoolBlockCounts
Block counts for different time periods
PoolBlockShares
Pool’s share of total blocks for different time periods
PoolDetail
Detailed pool information with statistics across time periods
PoolDetailInfo
Pool information for detail view
PoolInfo
Basic pool information for listing all pools
PoolSlugParam
PoolStats
Mining pool with block statistics for a time period
Pools
PoolsSummary
Mining pools response for a time period
QuarterIndex
RawLockTime
Transaction locktime
ReadBlock
RecommendedFees
Recommended fee rates in sat/vB
RewardStats
Block reward statistics over a range of blocks
Sats
Satoshis
SemesterIndex
StoredBool
Fixed-size boolean value optimized for on-disk storage (stored as u16)
StoredF32
Stored 32-bit floating point value
StoredF64
Fixed-size 64-bit floating point value optimized for on-disk storage
StoredI16
StoredString
StoredU8
StoredU16
StoredU32
Fixed-size 32-bit unsigned integer optimized for on-disk storage
StoredU64
Fixed-size 64-bit unsigned integer optimized for on-disk storage
SupplyState
Current supply state tracking UTXO count and total value
SyncStatus
Sync status of the indexer
TimePeriodParam
Timestamp
UNIX timestamp in seconds
TimestampParam
Transaction
Transaction information compatible with mempool.space API format
TxIn
Transaction input
TxInIndex
TxIndex
TxOut
Transaction output
TxOutIndex
TxOutspend
Status of an output indicating whether it has been spent
TxStatus
Transaction confirmation status
TxVersion
Transaction version number
TxWithHex
A transaction with its raw hex representation
Txid
Transaction ID (hash)
TxidParam
TxidPrefix
TxidVout
Transaction output reference (txid + output index)
TypeIndex
Index within its type (e.g., 0 for first P2WPKH address)
U8x2
U8x20
U8x32
U8x33
U8x65
Unit
UnknownOutputIndex
Utxo
Unspent transaction output
VSize
Virtual size in vbytes (weight / 4, rounded up)
ValidateAddressParam
Version
Version tracking for data schema and computed values.
Vin
Input index in the spending transaction
Vout
Index of the output being spent in the previous transaction
WeekIndex
Weight
Transaction or block weight in weight units (WU)
Year
Bitcoin year (2009, 2010, …, 2025+)
YearIndex

Enums§

AddressBytes
AnyAddressDataIndexEnum
Format
Output format for API responses
FormatResponse
Response type for endpoints that support multiple formats (JSON/CSV).
Index
Aggregation dimension for querying metrics. Includes time-based (date, week, month, year), block-based (height, txindex), and address/output type indexes.
OutputType
Type (P2PKH, P2WPKH, P2SH, P2TR, etc.)
PoolSlug
Term
Classification for short-term vs long-term holders. The threshold is 150 days (approximately 5 months) = 3600 hours.
TimePeriod
Time period for mining statistics.
TreeNode
Hierarchical tree node for organizing metrics into categories

Constants§

BLOCKS_PER_DIFF_EPOCHS
BLOCKS_PER_HALVING
ONE_DAY_IN_SEC
ONE_DAY_IN_SEC_F64
ONE_HOUR_IN_SEC
PERCENTILES
Standard percentile values used throughout BRK.
PERCENTILES_LEN
Length of the PERCENTILES array.

Traits§

CheckedSub
OptionExt
Extension trait for Option to provide shorter unwrap methods
PrintableIndex
Provides string representations of index types for display and region naming.

Functions§

de_unquote_i64
de_unquote_limit
de_unquote_usize
extract_json_type
Extract JSON type from a schema, following $ref if needed.
get_percentile
Get a percentile value from a sorted slice.
pools

Type Aliases§

StoredPhantom