Swift Bitcoin – Full node library

Jan 27, 2025 • Implementation Details

New BinaryCodable Framework

The new BinaryCodable framework adds simplicity, performance and stability to the way Bitcoin types are parsed and serialized from binary streams.

The idea of a BinaryCodable protocol is inspired by Swift's own Codable protocol. While it is possible to encode/decode binary formats using Apple's framework, the requirement to define keys for all fields hints at a different use case.

To make a type binary decodable just define an initializer:

init(from decoder: inout BinaryDecoder) throws(BinaryDecodingError)

Use BinaryDecoder to decode each field, like in the case of a non-witness Bitcoin transaction:

version = try decoder.decode()
ins = try decoder.decode()
outs = try decoder.decode()
locktime = try decoder.decode()

To encode simply implement the encode(to:) method and use the provided BinaryEncoder instance to encode each value.

public func encode(to encoder: inout BinaryEncoder) {
    encoder.encode(version)
    encoder.encode(ins)
    encoder.encode(outs)
    encoder.encode(locktime)
}

Notice how because TxIn and TxOut are themselves binary codable, a collection of inputs and outputs can be trivially handled by the encoder and decoder. The framework is tailored for Bitcoin development so the variable integer prefix is handled automatically.

This will greatly improve all serialization logic across the Swift Bitcoin codebase both in readability as well as speed.

The Binary Codable API is public so you can also use it independently by simply importing BitcoinCrypto.