btlv
A Rust library for encoding and decoding Lightning Network TLV (Type-Length-Value) streams, compliant with BOLT #1.
Features
- BOLT-compliant bigsize and TLV encoding with canonical-form validation
TlvStreamcontainer with sorted, deduplicated records and typed accessorstlv_struct!macro for declarative struct-to-TLV mappingtu64truncated unsigned integer encoding/decoding- Serde support (feature-gated) — serialize/deserialize
TlvStreamas hex strings - Spec test vectors from BOLT #1 appendices A and B
Installation
Add to your Cargo.toml:
[]
= "0.2"
Serde support is enabled by default. To disable it:
[]
= { = "0.2", = false }
To enable standalone BigSize encode/decode (e.g. for custom wire protocols):
[]
= { = "0.2", = ["bigsize"] }
use bigsize;
let encoded = encode;
let = decode.unwrap;
assert_eq!;
With serde enabled, tlv_struct! structs are directly serializable (they delegate to TlvStream's hex-string encoding):
let payload = OnionPayload ;
let json = to_string.unwrap;
let decoded: OnionPayload = from_str.unwrap;
Usage
Working with TlvStream directly
use TlvStream;
// Build a stream
let mut stream = default;
stream.set_tu64; // tu64-encoded amount
stream.set_tu64; // tu64-encoded CLTV
stream.insert;
// Serialize to wire format
let bytes = stream.to_bytes.unwrap;
// Parse back
let decoded = from_bytes.unwrap;
assert_eq!;
Declarative struct mapping with tlv_struct!
tlv_struct!
let payload = OnionPayload ;
// Serialize to TLV bytes and back
let bytes = payload.to_tlv_bytes.unwrap;
let decoded = from_tlv_bytes.unwrap;
assert_eq!;
The macro supports three encoding tags:
| Tag | Wire format | Rust types |
|---|---|---|
tu64 |
Variable-length minimal big-endian int | u64, u32 |
u64 |
Fixed 8-byte big-endian | u64 |
bytes |
Raw bytes | Vec<u8>, [u8; N] |
Fields wrapped in Option<T> are automatically optional — omitted when None, decoded as None when absent.
Core types
| Type | Description |
|---|---|
TlvStream |
Sorted, deduplicated record container with typed get/set accessors |
TlvRecord |
A single type-value pair |
TlvError |
Error enum covering duplicate types, ordering, truncation, overflow |
Bigsize encoding
Implements the BOLT #1 variable-length integer format:
| Value range | Wire encoding |
|---|---|
0 to 252 |
1 byte |
253 to 65535 |
0xfd + 2 bytes |
65536 to 4294967295 |
0xfe + 4 bytes |
4294967296 to 2^64 - 1 |
0xff + 8 bytes |
Contributing
Contributions are welcome! Please feel free to submit a Pull Request or open an issue.
The test suite includes BOLT #1 specification test vectors for bigsize, tu64, and TLV stream encoding.
License
This project is licensed under the MIT License - see the LICENSE file for details.