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,Outpointwith 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,DecadeIndexwith 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
| Category | Examples |
|---|---|
| Block metadata | Height, BlockHash, BlockTimestamp, BlkPosition |
| Transaction | Txid, TxIndex, TxIn, TxOut, Vsize, Weight |
| Address | P2PKHAddressIndex, P2TRBytes, AnyAddressIndex, AddressStats |
| Value | Sats, Dollars, Cents, Bitcoin |
| Time | Date, DateIndex, WeekIndex, MonthIndex, … |
| Metric | Metric, MetricData, MetricSelection |
| API | Pagination, 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_errorfor error handling
Structs§
- Addr
- Bitcoin address string
- Addr
Chain Stats - Address statistics on the blockchain (confirmed transactions only)
- Addr
Hash - Addr
Index OutPoint - Addr
Index TxIndex - Addr
Mempool Stats - Address statistics in the mempool (unconfirmed transactions only)
- Addr
Stats - Address information compatible with mempool.space API format
- Addr
Validation - Address validation result
- Age
- Represents the age of a UTXO or address balance. Encapsulates all age-related calculations in one type-safe struct.
- AnyAddr
Index - Unified index for any address type (funded or empty)
- Basis
Points16 - 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::MAXis reserved as a NaN sentinel. - Basis
Points32 - 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::MAXis reserved as a NaN sentinel. - Basis
Points Signed16 - 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::MINis reserved as a NaN sentinel. - Basis
Points Signed32 - 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::MINis 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
- Block
Extras - Extended block data matching mempool.space /api/v1/blocks extras
- Block
FeeRates Entry - A single block fee rates data point with percentiles.
- Block
Fees Entry - A single block fees data point.
- Block
Hash - Block hash
- Block
Hash Prefix - First-8-bytes prefix of a block hash, packed as a
u64. BothFrom<&BlockHash>(viafrom_le_bytes) andFrom<ByteView>(viafrom_be_bytes, inverse of theto_be_byteswriter) are host-independent so on-disk keys are portable across architectures. - Block
Header - Block header matching mempool.space’s format. Contains the same fields as bitcoin::block::Header but serialized for the JSON API.
- Block
Info - Block information matching mempool.space /api/block/{hash}
- Block
Info V1 - Block information with extras, matching mempool.space /api/v1/blocks
- Block
Pool - Mining pool identification for a block
- Block
Rewards Entry - A single block rewards data point.
- Block
Size Entry - A single block size data point.
- Block
Sizes Weights - Combined block sizes and weights response.
- Block
Status - Block status indicating whether block is in the best chain
- Block
Template - Projected next-block contents from Bitcoin Core’s
getblocktemplate(block 0 of the snapshot). Returned byGET /api/v1/mempool/block-template. - Block
Template Diff - Delta between the current
getblocktemplateprojection and a prior one identified bysince. Returned byGET /api/v1/mempool/block-template/diff/{hash}. - Block
Timestamp - Block information returned for timestamp queries
- Block
TxIndex - Position of a transaction within a single block (0 = coinbase).
Distinct from
TxIndex, which is the chain-wide global tx index. - Block
Weight Entry - A single block weight data point.
- Cents
- Unsigned cents (u64) - for values that should never be negative. Used for invested capital, realized cap, etc.
- Cents
Compact - Compact unsigned cents (u32) - memory-efficient for map keys. Supports values from $0.00 to $42,949,672.95 (u32::MAX / 100).
- Cents
Sats - Cents × Sats (u128) - price in cents multiplied by amount in sats. Uses u128 because large amounts at any price can overflow u64.
- Cents
Signed - Signed cents (i64) - for values that can be negative. Used for profit/loss calculations, deltas, etc.
- Cents
Squared Sats - Raw cents squared (u128) - stores cents² × sats without division. Used for precise accumulation of capitalized cap values: Σ(price² × sats). capitalized_price = capitalized_cap_raw / realized_cap_raw
- Chunk
Input - One cluster member’s input to Single Fee Linearization: its
(fee, vsize)and parent edges as local indices into the same array. - Close
- Closing price value for a time period
- Cohort
- URPD cohort identifier. Use
GET /api/urpdto list available cohorts. - Coinbase
Tag - Coinbase scriptSig tag for pool identification.
- Cost
Basis Snapshot - Snapshot of cost basis related state. Uses CentsSats (u64) for single-UTXO values, CentsSquaredSats (u128) for capitalized cap.
- Cpfp
Cluster - CPFP cluster: the connected component the seed belongs to, plus its SFL linearization.
- Cpfp
Cluster Chunk - One SFL chunk inside a
CpfpCluster.txsis in topological order (matchesCpfpCluster.txsordering); the chunk’sfeerateis the per-chunk SFL feerate and is the same for every tx in this chunk. - Cpfp
Cluster Tx - One entry in a
CpfpCluster.txsarray. - Cpfp
Cluster TxIndex - Position of a transaction inside a
CpfpCluster.txsarray. Cluster-local, has no meaning outside the enclosing cluster. - Cpfp
Entry - A transaction in a CPFP relationship.
- Cpfp
Info - CPFP (Child Pays For Parent) information for a transaction.
- Data
Range Format - Range parameters with output format for API query parameters.
- Date
- Date in YYYYMMDD format stored as u32
- Date
Series Data - Series data that is guaranteed to use a date-based index.
- Day1
- Day3
- Detailed
Series Count - Detailed series count with per-database breakdown
- Difficulty
Adjustment - Difficulty adjustment information.
- Difficulty
Adjustment Entry - A single difficulty adjustment entry. Serializes as array: [timestamp, height, difficulty, change_percent]
- Difficulty
Entry - A single difficulty data point in the hashrate summary.
- Disk
Usage - Disk usage of the indexed data
- Dollars
- US Dollar amount
- Empty
Addr Data - Data of an empty address
- Empty
Addr Index - Empty
Output Index - Epoch
- Exchange
Rates - Exchange rates (USD base, on-chain only — no fiat pairs available)
- Exit
- Graceful shutdown coordinator for ensuring data consistency during program exit.
- FeeRate
- Fee rate in sat/vB
- FeeRate
Percentiles - Fee rate percentiles (min, 10%, 25%, 50%, 75%, 90%, max).
- Funded
Addr Data - Data for a funded (non-empty) address with current balance
- Funded
Addr Index - Halving
- Hashrate
Entry - A single hashrate data point.
- Hashrate
Summary - Summary of network hashrate and difficulty data.
- Health
- Server health status
- Height
- Block height
- Hex
- Hex-encoded string. Transparent wrapper over
String: serializes as a plain JSON string and derefs tostr, so anywhere&strorAsRef<[u8]>is expected theHex“just works”. - High
- Highest price value for a time period
- Histogram
- Fixed-length, log-scale bin histogram generic over the per-bin counter type.
Instantiated as raw counts (
u32), the smoothed EMA buffer (f64), or the quantized wire projection (u16). Serializes as a flat JSON array ofNvalues.Derefexposes the underlying array for indexing and iteration. - Historical
Price - Historical price response
- Historical
Price Entry - A single price data point
- Hour1
- Hour4
- Hour12
- Index
Info - Information about an available index and its query aliases
- Limit
- Maximum number of results to return. Defaults to 100 if not specified.
- Low
- Lowest price value for a time period
- Mempool
Block - Block info in a mempool.space like format for fee estimation.
- Mempool
Entry Info - Mempool entry info from Bitcoin Core’s
getmempoolentry. - Mempool
Info - Mempool statistics with incrementally maintained fee histogram.
- Mempool
Recent Tx - Simplified mempool transaction for the
/api/mempool/recentendpoint. - Merkle
Proof - Merkle inclusion proof for a transaction
- Minute10
- Minute30
- Month1
- Month3
- Month6
- Next
Block Hash - Content hash of the projected next block (block 0 of the mempool
snapshot). Same value as the mempool ETag. Opaque token: pass back
as
sinceon/api/v1/mempool/block-template/diff/{hash}to fetch deltas. - OHLC
Cents - OHLC (Open, High, Low, Close) data in cents
- OHLC
Dollars - OHLC (Open, High, Low, Close) data in dollars
- OHLC
Sats - OHLC (Open, High, Low, Close) data in satoshis
- OpReturn
Index - Open
- Opening price value for a time period
- OutPoint
- Outpoint
Prefix - Compact
(TxidPrefix, Vout)outpoint identifier. Prefix collisions are possible and must be verified by the caller. - P2AAddr
Index - P2ABytes
- P2MS
Output Index - P2PK33
Addr Index - P2PK33
Bytes - P2PK65
Addr Index - P2PK65
Bytes - P2PKH
Addr Index - P2PKH
Bytes - P2SH
Addr Index - P2SH
Bytes - P2TR
Addr Index - P2TR
Bytes - P2WPKH
Addr Index - P2WPKH
Bytes - P2WSH
Addr Index - P2WSH
Bytes - Paginated
Series - A paginated list of available series names (1000 per page)
- Pagination
- Pagination parameters for paginated API endpoints
- Pool
- Mining pool information
- Pool
Block Counts - Block counts for different time periods
- Pool
Block Shares - Pool’s share of total blocks for different time periods
- Pool
Detail - Detailed pool information with statistics across time periods
- Pool
Detail Info - Pool information for detail view
- Pool
Hashrate Entry - A single pool hashrate data point.
- Pool
Info - Basic pool information for listing all pools
- Pool
Stats - Mining pool with block statistics for a time period
- Pools
- Pools
Summary - Mining pools response for a time period
- Port
- Server port. Defaults to 3110.
- Prices
- Current price response matching mempool.space /api/v1/prices format
- Range
Map - Maps ranges of indices to values for efficient reverse lookups.
- RawLock
Time - Transaction locktime. Values below 500,000,000 are interpreted as block heights; values at or above are Unix timestamps.
- RbfResponse
- Response body for
GET /api/v1/tx/:txid/rbf. Both fields are null when the tx has no known RBF history within the mempool monitor’s graveyard retention window. - RbfTx
- Transaction summary carried inside an RBF replacement node. Shape
matches mempool.space’s
/api/v1/tx/:txid/rbfand/api/v1/replacementsresponses. - Read
Block - Recommended
Fees - Recommended fee rates in sat/vB
- Replacement
Node - One node in an RBF replacement tree. The node’s
txreplaced each entry inreplaces, recursively. - Reward
Stats - Block reward statistics over a range of blocks
- Sats
- Amount in satoshis (1 BTC = 100,000,000 sats)
- Sats
Fract - Fractional satoshis (f64) - for representing USD prices in sats
- Sats
Signed - Signed satoshis (i64) - for values that can be negative. Used for changes, deltas, profit/loss calculations, etc.
- Search
Query - Series
Count - Series count statistics - distinct series and total series-index combinations
- Series
Data - Series data with range information.
- Series
Info - Metadata about a series
- Series
Leaf - Leaf node containing series metadata
- Series
Leaf With Schema - SeriesLeaf with JSON Schema for client generation
- Series
List - Comma-separated list of series names
- Series
Name - Series name
- Series
Name With Index - Series
Output - Series output with metadata for caching.
- Series
Output Legacy - Deprecated: Legacy series output with metadata for caching.
- Series
Selection - Selection of series to query
- Series
Selection Legacy - Legacy series selection parameters (deprecated)
- SigOps
- BIP-141 sigop cost. The block-level budget is 80,000, so a
u32fits a single tx’s count with room to spare. - Stored
Bool - Fixed-size boolean value optimized for on-disk storage (stored as u8)
- Stored
F32 - Stored 32-bit floating point value
- Stored
F64 - Fixed-size 64-bit floating point value optimized for on-disk storage
- Stored
I8 - Stored
I16 - Stored
I64 - Fixed-size 64-bit signed integer optimized for on-disk storage
- Stored
String - Stored
U8 - Stored
U16 - Stored
U32 - Fixed-size 32-bit unsigned integer optimized for on-disk storage
- Stored
U64 - Fixed-size 64-bit unsigned integer optimized for on-disk storage
- Supply
State - Current supply state tracking UTXO count and total value
- Sync
Status - Sync status of the indexer
- Timestamp
- UNIX timestamp in seconds
- Transaction
- Transaction information compatible with mempool.space API format
- TxIn
- Transaction input
- TxIn
Index - TxIndex
- Chain-wide transaction index (0 = the genesis coinbase). For an
in-block position, use
BlockTxIndexinstead. - TxOut
- Transaction output
- TxOut
Index - TxOutspend
- Status of an output indicating whether it has been spent
- TxStatus
- Transaction confirmation status
- TxVersion
- Transaction version number
- TxVersion
Raw - Raw transaction version (i32) from Bitcoin protocol. Unlike TxVersion (u8, indexed), this preserves non-standard values used in coinbase txs for miner signaling/branding.
- Txid
- Transaction ID (hash)
- Txid
Prefix - First-8-bytes prefix of a txid, packed as a
u64. BothFrom<&Txid>(viafrom_le_bytes) andFrom<ByteView>(viafrom_be_bytes, inverse of theto_be_byteswriter) are host-independent so on-disk keys are portable across architectures. - Type
Index - Index within its type (e.g., 0 for first P2WPKH address)
- U8x2
- U8x20
- U8x32
- U8x33
- U8x65
- Unit
- Unknown
Output Index - Urpd
- UTXO Realized Price Distribution for a cohort on a specific date.
- Urpd
Bucket - A single bucket in a URPD snapshot.
- UrpdRaw
- Raw on-disk URPD: a map of price (cents) to supply (sats).
Processed into
crate::Urpdfor API responses. - Utxo
- Unspent transaction output
- VSize
- Virtual size in vbytes (weight / 4, rounded up). Max block vsize is ~1,000,000 vB.
- 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
- Weight in weight units (WU). Max block weight is 4,000,000 WU.
- Witness
- Transaction witness: a stack of byte arrays, one per witness item.
- Year
- Bitcoin year (2009, 2010, …, 2025+)
- Year1
- Year10
Enums§
- Addr
Bytes - AnyAddr
Data Index Enum - Block
Template Diff Entry - One slot of the new template in a
BlockTemplateDiff. - Cache
Class - How the trailing edge of an
Indexmutates over time. Drives the series cache: bucketed indexes have a small fixed volatile tail, entity indexes derive their stable count from a height→first-index mapping, and mutable addr indexes have no immutable region (entries change retroactively). - Format
- Output format for API responses
- Format
Response - 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.
- Legacy
Value - Deprecated: Raw JSON without metadata wrapper.
- Output
- Series data output format
- Output
Legacy - Deprecated: Raw JSON without metadata wrapper
- Output
Type - Type (P2PKH, P2WPKH, P2SH, P2TR, etc.)
- Pool
Slug - URL-friendly mining pool identifier
- Range
Index - 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.
- Time
Period - Time period for mining statistics.
- Tree
Node - Hierarchical tree node for organizing series into categories
- Urpd
Aggregation - Aggregation strategy for URPD buckets. Options: raw (no aggregation), lin200/lin500/lin1000 (linear $200/$500/$1000), log10/log50/log100/log200/log500/log1000/log2000 (logarithmic with 10/50/100/200/500/1000/2000 buckets per decade).
Constants§
- BLOCKS_
PER_ DIFF_ EPOCHS - BLOCKS_
PER_ HALVING - CPFP_
CHAIN_ LIMIT - Bitcoin Core’s default mempool ancestor/descendant chain cap, also used by mempool.space-style truncation in CPFP walks.
- DAY3_
INTERVAL - HOUR1_
INTERVAL - HOUR4_
INTERVAL - HOUR12_
INTERVAL - INDEX_
EPOCH - 2009-01-01 00:00:00 UTC — epoch for fixed-interval time indexes.
- MINUT
E10_ INTERVAL - MINUT
E30_ 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.
Traits§
- Checked
Sub - Subtraction that returns
Noneon underflow. - From
Coarser Index - Maps coarser-grained indices to ranges of finer-grained indices.
- Option
Ext - Extension trait for Option to provide shorter unwrap methods
- Printable
Index - 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.
- find_
seed_ chunk - Find the chunk containing
seed_localand return(chunk_index, feerate). Falls back to(0, fallback)when the seed isn’t in any chunk - shouldn’t happen for a well-formed linearization but keeps callers’ wire shape valid. - get_
percentile - Get a percentile value from a sorted slice using nearest-rank method.
- get_
weighted_ percentile - Get a percentile value from a sorted (value, vsize) slice using vsize-weighted interpolation — matches mempool.space’s feeRange calculation.
- linearize
- Linearize
itemsinto chunks.itemsmust be in topological order (parents before children);parentsindices must point earlier in the slice. Returns chunks sorted by descending feerate, with each chunk’stxslisted in the input topological order. - pools