Skip to main content

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: Epoch, Halving, 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§

Addr
Bitcoin address string
AddrChainStats
Address statistics on the blockchain (confirmed transactions only)
AddrHash
AddrIndexOutPoint
AddrIndexTxIndex
AddrMempoolStats
Address statistics in the mempool (unconfirmed transactions only)
AddrParam
AddrStats
Address information compatible with mempool.space API format
AddrTxidsParam
AddrValidation
Address validation result
Age
Represents the age of a UTXO or address balance. Encapsulates all age-related calculations in one type-safe struct.
AnyAddrIndex
Unified index for any address type (funded or empty)
BasisPoints16
Unsigned basis points stored as u16. 1 bp = 0.0001. Range: 0–6.5535. Use for bounded 0–1 ratios (dominance, adoption, liveliness, etc.). u16::MAX is reserved as a NaN sentinel.
BasisPoints32
Unsigned basis points stored as u32. 1 bp = 0.0001. Range: 0–429,496.7295. Use for unbounded unsigned ratios (MVRV, NVT, SOPR, etc.). u32::MAX is reserved as a NaN sentinel.
BasisPointsSigned16
Signed basis points stored as i16. 1 bp = 0.0001. Range: -3.2767 to +3.2767. Use for signed bounded ratios (NUPL, net PnL ratios, etc.). i16::MIN is reserved as a NaN sentinel.
BasisPointsSigned32
Signed basis points stored as i32. 1 bp = 0.0001. Range: -214,748.3647 to +214,748.3647. Use for unbounded signed values (returns, growth rates, volatility, z-scores, etc.). i32::MIN is reserved as a NaN sentinel.
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
Unsigned cents (u64) - for values that should never be negative. Used for invested capital, realized cap, etc.
CentsCompact
Compact unsigned cents (u32) - memory-efficient for map keys. Supports values from $0.00 to $42,949,672.95 (u32::MAX / 100).
CentsSats
Cents × Sats (u128) - price in cents multiplied by amount in sats. Uses u128 because large amounts at any price can overflow u64.
CentsSigned
Signed cents (i64) - for values that can be negative. Used for profit/loss calculations, deltas, etc.
CentsSquaredSats
Raw cents squared (u128) - stores cents² × sats without division. Used for precise accumulation of investor cap values: Σ(price² × sats). investor_price = investor_cap_raw / realized_cap_raw
Close
Closing price value for a time period
Cohort
Cohort identifier for cost basis distribution.
CostBasisCohortParam
Path parameters for cost basis dates endpoint.
CostBasisDistribution
Cost basis distribution: a map of price (cents) to sats.
CostBasisParams
Path parameters for cost basis distribution endpoint.
CostBasisQuery
Query parameters for cost basis distribution endpoint.
CostBasisSnapshot
Snapshot of cost basis related state. Uses CentsSats (u64) for single-UTXO values, CentsSquaredSats (u128) for investor cap.
DataRange
Range parameters for slicing data
DataRangeFormat
Data range with output format for API query parameters
Date
Date in YYYYMMDD format stored as u32
DateSeriesData
Series data that is guaranteed to use a date-based index.
Day1
Day3
DetailedSeriesCount
Detailed series 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.
DiskUsage
Disk usage of the indexed data
Dollars
US Dollar amount as floating point
EmptyAddrData
Data of an empty address
EmptyAddrIndex
EmptyOutputIndex
Epoch
Etag
HTTP ETag value.
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).
FundedAddrData
Data for a funded (non-empty) address with current balance
FundedAddrIndex
Halving
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
Hour1
Hour4
Hour12
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.
Limit
Maximum number of results to return. Defaults to 100 if not specified.
LimitParam
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
Minute10
Minute30
Month1
Month3
Month6
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
OracleBins
Phase histogram: counts per bin for frac(log10(sats))
OracleBinsV2
V2 Phase histogram: counts per bin for frac(log10(sats))
OutPoint
P2AAddrIndex
P2ABytes
P2MSOutputIndex
P2PK33AddrIndex
P2PK33Bytes
P2PK65AddrIndex
P2PK65Bytes
P2PKHAddrIndex
P2PKHBytes
P2SHAddrIndex
P2SHBytes
P2TRAddrIndex
P2TRBytes
P2WPKHAddrIndex
P2WPKHBytes
P2WSHAddrIndex
P2WSHBytes
PaginatedSeries
A paginated list of available series 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
Port
Server port. Defaults to 3110.
RangeMap
Maps ranges of indices to values for efficient reverse lookups.
RawLockTime
Transaction locktime
ReadBlock
RecommendedFees
Recommended fee rates in sat/vB
RewardStats
Block reward statistics over a range of blocks
Sats
Satoshis
SatsFract
Fractional satoshis (f64) - for representing USD prices in sats
SatsSigned
Signed satoshis (i64) - for values that can be negative. Used for changes, deltas, profit/loss calculations, etc.
SearchQuery
SeriesCount
Series count statistics - distinct series and total series-index combinations
SeriesData
Series data with range information.
SeriesInfo
Metadata about a series
SeriesLeaf
Leaf node containing series metadata
SeriesLeafWithSchema
SeriesLeaf with JSON Schema for client generation
SeriesList
Comma-separated list of series names
SeriesName
Series name
SeriesNameWithIndex
SeriesOutput
Series output with metadata for caching.
SeriesOutputLegacy
Deprecated: Legacy series output with metadata for caching.
SeriesParam
SeriesSelection
Selection of series to query
SeriesSelectionLegacy
Legacy series selection parameters (deprecated)
StoredBool
Fixed-size boolean value optimized for on-disk storage (stored as u8)
StoredF32
Stored 32-bit floating point value
StoredF64
Fixed-size 64-bit floating point value optimized for on-disk storage
StoredI8
StoredI16
StoredI64
Fixed-size 64-bit signed integer optimized for on-disk storage
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)
ValidateAddrParam
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
Week1
Weight
Transaction or block weight in weight units (WU)
Year
Bitcoin year (2009, 2010, …, 2025+)
Year1
Year10

Enums§

AddrBytes
AnyAddrDataIndexEnum
CostBasisBucket
Bucket type for cost basis aggregation. Options: raw (no aggregation), lin200/lin500/lin1000 (linear $200/$500/$1000), log10/log50/log100/log200 (logarithmic with 10/50/100/200 buckets per decade).
CostBasisValue
Value type for cost basis distribution. Options: supply (BTC), realized (USD, price × supply), unrealized (USD, spot × supply).
Format
Output format for API responses
FormatResponse
Response type for endpoints that support multiple formats (JSON/CSV).
Index
Aggregation dimension for querying series. Includes time-based (date, week, month, year), block-based (height, tx_index), and address/output type indexes.
LegacyValue
Deprecated: Raw JSON without metadata wrapper.
Output
Series data output format
OutputLegacy
Deprecated: Raw JSON without metadata wrapper
OutputType
Type (P2PKH, P2WPKH, P2SH, P2TR, etc.)
PoolSlug
RangeIndex
A range boundary: integer index, date, or timestamp.
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 series into categories

Constants§

BLOCKS_PER_DIFF_EPOCHS
BLOCKS_PER_HALVING
DAY3_INTERVAL
HOUR1_INTERVAL
HOUR4_INTERVAL
HOUR12_INTERVAL
INDEX_EPOCH
2009-01-01 00:00:00 UTC — epoch for fixed-interval time indexes.
MINUTE10_INTERVAL
MINUTE30_INTERVAL
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.
PHASE_BINS
Number of bins for the phase histogram
PHASE_BINS_V2
Number of bins for V2 phase histogram (0.5% resolution)

Traits§

CheckedSub
FromCoarserIndex
Maps coarser-grained indices to ranges of finer-grained indices.
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 root schema, following $ref and composition keywords.
get_percentile
Get a percentile value from a sorted slice.
pools

Type Aliases§

CostBasisFormatted
Formatted cost basis output. Key: price floor in USD (dollars). Value: BTC (for supply) or USD (for realized/unrealized).
StoredPhantom