Skip to content

Recursive Length Prefix encoding written in Swift

License

Notifications You must be signed in to change notification settings

alephao/swift-rlp

Repository files navigation

SwiftRLP

Swift 5.9.2 Version

This is a simple, pure Swift implementation of Recursive Length Prefix Encoding, a serialisation method for encoding arbitrarily structured binary data (byte arrays).

RLP Encoding is used in Ethereum. You can read more about it here:

Library Usage

SwiftRLP is available through Swift Package Manager.

Adding SwiftRLP as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
  .package(url: "https://github.com/alephao/swift-rlp.git", from: "0.0.6")
],
targets: [
    .target(
      name: "MyTarget",
      dependencies: [
        .product(name: "SwiftRLP", package: "swift-rlp")
      ]
    ),
]

Encoding

import SwiftRLP

let encoder = RLPEncoder()

// String Encoding
try encoder.encode(.string("dog"))
try encoder.encode(string: "dog")

// Array Encoding
try encoder.encode(.array(["d", "o", "g"]))

Decoding

import SwiftRLP

let encodedData = try RLPEncoder().encode(string: "dog")

let decoder = RLPDecoder()
try decoder.decode(from: encodedData) // RLPValue.string("dog")

CLI

Currently, the CLI is only available via source code. To use it, clone this repo and run:

Encoding

$ swift run cli encode dog
> 0x83646F67

Decoding

$ swift run cli decode 0x83646F67
> string("dog")

License

SwiftRLP is released under an MIT license. See LICENSE for more information.