Skip to main content

Crate brk_types

Crate brk_types 

Source
Expand description

§brk_types

Bitcoin domain and storage-index types shared across BRK and Bitview.

§What it provides

Purpose-built types for heights, amounts, hashes, addresses, transactions, calendar indexes, protocol epochs, and API values that are intrinsically tied to Bitcoin. Query-protocol types such as SeriesSelection, SeriesData, Pagination, and TreeNode live in bitview_types.

§Type categories

CategoryExamples
Block metadataHeight, BlockHash, BlockTimestamp, BlkPosition
TransactionsTxid, TxIndex, TxIn, TxOut, VSize, Weight
AddressesAddr, OutputType, P2PKHAddrIndex, AnyAddrIndex, AddrStats
ValuesSats, Bitcoin, Dollars, Cents, OHLCCents
Time indexesDay1, Day3, Week1, Month1, Month3, Month6, Year1, Year10
ProtocolEpoch, Halving, TxVersion, RawLockTime

The types implement the serialization, JSON Schema, arithmetic, formatting, and vecdb traits needed by their domains rather than exposing a parallel set of API wrapper types.

§Example

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

let height = Height::new(840_000);
let reward = Sats::FIFTY_BTC / 16;
let day = Day1::try_from(Date::new(2024, 4, 20))?;

§Built on

  • bitcoin for consensus primitives and address parsing
  • brk_error for shared errors
  • vecdb for persistent-vector traits

Structs§

Addr
Bitcoin address string
AddrChainStats
Address statistics on the blockchain (confirmed transactions only)
AddrHash
AddrHashPrefixMatches
AddrIndexOutPoint
AddrIndexTxIndex
AddrMempoolStats
Address statistics in the mempool (unconfirmed transactions only)
AddrState
Four-byte primary state stored for every address.
AddrStats
Address information compatible with mempool.space API format.
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)
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
BlockExtras
Extended block data matching mempool.space /api/v1/blocks extras
BlockFeeRatesEntry
A single block fee rates data point with percentiles.
BlockFeesEntry
A single block fees data point.
BlockHash
Double-SHA256 block-header hash, serialized in Bitcoin’s conventional hexadecimal byte order.
BlockHashPrefix
First-8-bytes prefix of a block hash, packed as a u64. Both From<&BlockHash> (via from_le_bytes) and From<ByteView> (via from_be_bytes, inverse of the to_be_bytes writer) are host-independent so on-disk keys are portable across architectures.
BlockHeader
Block header matching mempool.space’s format. Contains the same fields as bitcoin::block::Header but serialized for the JSON API.
BlockInfo
Block information matching mempool.space /api/block/{hash}
BlockInfoV1
Block information with extras, matching mempool.space /api/v1/blocks
BlockPool
Mining pool identification for a block
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
BlockTemplate
Projected next-block contents from Bitcoin Core’s getblocktemplate (block 0 of the snapshot). Returned by GET /api/v1/mempool/block-template.
BlockTemplateDiff
Delta between the current getblocktemplate projection and a prior one identified by since. Returned by GET /api/v1/mempool/block-template/diff/{hash}.
BlockTimestamp
Block information returned for timestamp queries
BlockTxIndex
Position of a transaction within a single block (0 = coinbase). Distinct from TxIndex, which is the chain-wide global tx index.
BlockWeightEntry
A single block weight data point.
Bytes
Cents
Unsigned cents (u64) - for values that should never be negative. Used for invested capital, realized cap, etc. u64::MAX is reserved as a NaN sentinel.
CentsCompact
Compact unsigned cents (u32) - memory-efficient for map keys. Supports finite values from $0.00 to $42,949,672.94. u32::MAX is reserved as a NaN sentinel.
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 capitalized cap values: Σ(price² × sats). capitalized_price = capitalized_cap_raw / realized_cap_raw
ChunkInput
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/urpd to list available cohorts.
CoinbaseTag
Up to the first 100 bytes of a coinbase transaction’s first-input scriptSig. Bytes are preserved for storage and exposed as a string by mapping each byte to the same-valued Unicode code point. Pool attribution may search this raw value, but the value itself is not a normalized pool label.
CostBasisPercentilePrices
CostBasisSnapshot
Snapshot of cost basis related state.
CpfpCluster
CPFP cluster: the connected component the seed belongs to, plus its SFL linearization.
CpfpClusterChunk
One SFL chunk inside a CpfpCluster. txs is in topological order (matches CpfpCluster.txs ordering); the chunk’s feerate is the per-chunk SFL feerate and is the same for every tx in this chunk.
CpfpClusterTx
One entry in a CpfpCluster.txs array.
CpfpClusterTxIndex
Position of a transaction inside a CpfpCluster.txs array. Cluster-local, has no meaning outside the enclosing cluster.
CpfpEntry
A transaction in a CPFP relationship.
CpfpInfo
CPFP (Child Pays For Parent) information for a transaction.
Date
Date in YYYYMMDD format stored as u32
Day1
Day3
DifficultyAdjustment
Difficulty adjustment information.
DifficultyAdjustmentEntry
A single difficulty adjustment entry. Serializes as array: [timestamp, height, difficulty, change_percent]
DifficultyEntry
A single difficulty data point in the hashrate summary.
DiskUsage
Disk usage of the indexed data
Dollars
US Dollar amount
EmptyAddrData
Data of an empty address
EmptyAddrIndex
EmptyOutputIndex
Epoch
ExchangeRates
Exchange rates (USD base, on-chain only — no fiat pairs available)
ExtendedEmptyAddrIndex
Index into the sidecar for empty-address data that does not fit inline.
FeeRate
Fee rate stored in milli-sat/vB and exposed as sat/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.
Height
Block height
Hex
Hex-encoded string. Transparent wrapper over String: serializes as a plain JSON string and derefs to str, so anywhere &str or AsRef<[u8]> is expected the Hex “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 of N values. Deref exposes the underlying array for indexing and iteration.
HistoricalPrice
Historical price response
HistoricalPriceEntry
A single price data point
Hour1
Hour4
Hour12
Lengths
Pipeline-wide length/count snapshot.
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 getmempoolentry.
MempoolInfo
Mempool statistics with incrementally maintained fee histogram.
MempoolRecentTx
Simplified mempool transaction for the /api/mempool/recent endpoint.
MerkleProof
Merkle inclusion proof for a transaction
Minute10
Minute30
Month1
Month3
Month6
NextBlockHash
Content hash of the projected next block (block 0 of the mempool snapshot). Same value as the mempool ETag. Opaque token: pass back to GET /api/v1/mempool/block-template/diff/{hash} to fetch deltas.
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
OutpointPrefix
Compact (TxidPrefix, Vout) outpoint identifier. Prefix collisions are possible and must be verified by the caller.
P2AAddrIndex
P2ABytes
P2MSOutputIndex
P2PK33AddrIndex
P2PK33Bytes
P2PK65AddrIndex
P2PK65Bytes
P2PKHAddrIndex
P2PKHBytes
P2SHAddrIndex
P2SHBytes
P2TRAddrIndex
P2TRBytes
P2WPKHAddrIndex
P2WPKHBytes
P2WSHAddrIndex
P2WSHBytes
PartsPerMillion32
Unsigned parts per million stored as u32. One unit is 0.000001. Range: 0–4,294.967294. Use for precise bounded ratios and percentages. u32::MAX is reserved as a NaN sentinel.
PartsPerMillion64
Unsigned parts per million stored as u64. One unit is 0.000001. Range: 0–18,446,744,073,709.551614. Use for precise wide-range ratios. u64::MAX is reserved as a NaN sentinel.
PartsPerMillionSigned32
Signed parts per million stored as i32. One unit is 0.000001. Range: -2,147.483647 to +2,147.483647. Use for precise bounded signed ratios and percentages. i32::MIN is reserved as a NaN sentinel.
PartsPerMillionSigned64
Signed parts per million stored as i64. One unit is 0.000001. Range: -9,223,372,036,854.775807 to +9,223,372,036,854.775807. Use for precise wide-range signed ratios and percentages. i64::MIN is reserved as a NaN sentinel.
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
PoolHashrateEntry
A single pool hashrate data point.
PoolInfo
Basic pool information for listing all pools
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.
Prices
Current price response matching mempool.space /api/v1/prices format
RangeMap
Maps ranges of indices to values for efficient reverse lookups.
RawLockTime
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/rbf and /api/v1/replacements responses.
ReadBlock
RecommendedFees
Recommended fee rates in sat/vB
ReplacementNode
One node in an RBF replacement tree. The node’s tx replaced each entry in replaces, recursively.
RewardStats
Block reward statistics over a range of blocks
Sats
Amount in satoshis (1 BTC = 100,000,000 sats)
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.
SigOps
BIP-141 sigop cost. The block-level budget is 80,000, so a u32 fits a single tx’s count with room to spare.
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
Timestamp
UNIX timestamp in seconds
Transaction
Transaction information compatible with mempool.space API format
TxIn
Transaction input
TxInIndex
TxIndex
Chain-wide transaction index (0 = the genesis coinbase). For an in-block position, use BlockTxIndex instead.
TxOut
Transaction output
TxOutIndex
TxOutspend
Status of an output indicating whether it has been spent
TxStatus
Transaction confirmation status
TxVersion
Compact indexed transaction-version category. Values 1, 2, and 3 preserve those exact signed 32-bit Bitcoin transaction versions; 255 represents every other version.
TxVersionRaw
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)
TxidPrefix
First-8-bytes prefix of a txid, packed as a u64. Both From<&Txid> (via from_le_bytes) and From<ByteView> (via from_be_bytes, inverse of the to_be_bytes writer) are host-independent so on-disk keys are portable across architectures.
TypeIndex
Index within its type (e.g., 0 for first P2WPKH address)
U8x2
U8x20
U8x32
U8x33
U8x65
Unit
UnknownOutputIndex
Urpd
UTXO Realized Price Distribution for a cohort on a specific date.
UrpdBucket
A single bucket in a URPD snapshot.
UrpdRaw
Raw on-disk URPD: a map of price (cents) to supply (sats). Processed into crate::Urpd for 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.
Weight64
Weight in weight units with enough range for cumulative and rolling totals.
Witness
Transaction witness: a stack of byte arrays, one per witness item.
Year
Bitcoin year (2009, 2010, …, 2025+)
Year1
Year10

Enums§

AddrBytes
AnyAddrDataIndexEnum
BlockTemplateDiffEntry
One slot of the new template in a BlockTemplateDiff.
CacheClass
How the trailing edge of an Index mutates 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).
CapitalSentimentPhase
Investor phase from the Capital Sentiment model.
DecodedAddrState
Decoded form of an address’s four-byte primary state.
Index
Aggregation dimension for querying series. Includes time-based (date, week, month, year), block-based (height, tx_index), and address/output type indexes.
OpReturnKind
OpReturnPolicyId
OutputType
Type (P2PKH, P2WPKH, P2SH, P2TR, etc.)
OutputTypeNormalized
Output type names used by Esplora and mempool.space.
PercentileId
PoolSlug
URL-friendly mining pool identifier
RangeIndex
A range boundary: integer index, date, or timestamp.
RarityPercentileId
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.
UrpdAggregation
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).
UrpdWeight
Weighting applied to a URPD: raw (unweighted), cointime, or coinflow.

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.
MINUTE10_INTERVAL
MINUTE30_INTERVAL
ONE_DAY_IN_SEC
ONE_DAY_IN_SEC_F64
ONE_HOUR_IN_SEC
OP_RETURN_KINDS
OP_RETURN_KIND_COUNT
OP_RETURN_POLICY_COUNT
OP_RETURN_POLICY_IDS
PERCENTILES
Standard percentile values used throughout BRK.
PERCENTILES_LEN
Length of the PERCENTILES array.
PERCENTILE_IDS
POOL_ATTRIBUTION_VERSION
Increment when pool IDs, payout addresses, or coinbase tags change.
RARITY_PERCENTILES
Percentiles used by the rarity meter, in physical column order.
RARITY_PERCENTILES_LEN
RARITY_PERCENTILE_IDS

Traits§

CheckedSub
Subtraction that returns None on underflow.
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.
VecIndex
Trait for types that can be used as vector indices.

Functions§

de_unquote_i64
de_unquote_usize
find_seed_chunk
Find the chunk containing seed_local and 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 items into chunks. items must be in topological order (parents before children); parents indices must point earlier in the slice. Returns chunks sorted by descending feerate, with each chunk’s txs listed in the input topological order.
pools