feat: bootstrap moon-i2p core protocol foundation
check / check (ubuntu-latest) (push) Failing after 30s
check / check (macos-latest) (push) Failing after 33s
check / check (windows-latest) (push) Failing after 32s

This commit is contained in:
Antigravity committed 2026-11-27 15:37:42 +00:00
commit e527b84bc3
47 files changed
+5350

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
///|
/// I2P Base32 alphabet (RFC 4648 lowercase `a-z2-7`, unpadded, used for `.b32.i2p` addresses).
let i2p_b32_alphabet : Bytes = b"abcdefghijklmnopqrstuvwxyz234567"
///|
fn b32_decode_char(c : Int32) -> Int32 raise EncodingError {
if c >= 97 && c <= 122 {
c - 97
} else if c >= 65 && c <= 90 {
// Accept uppercase too (case-insensitive)
c - 65
} else if c >= 50 && c <= 55 {
// '2'..'7' -> 26..31
c - 50 + 26
} else {
raise InvalidCharacter("invalid Base32 character code: \{c}")
}
}
///|
/// Encodes bytes as lowercase unpadded Base32 (standard for I2P `.b32.i2p` addresses).
pub fn base32_encode(data : Bytes) -> String {
let len = data.length()
if len == 0 {
return ""
}
let buf = StringBuilder(capacity=(len * 8 + 4) / 5)
let mut buffer = 0
let mut bits_left = 0
for i = 0; i < len; i = i + 1 {
buffer = (buffer << 8) | data[i].to_int()
bits_left += 8
while bits_left >= 5 {
bits_left -= 5
let idx = (buffer >> bits_left) & 0x1F
buf.write_char(i2p_b32_alphabet[idx].to_int().unsafe_to_char())
}
}
if bits_left > 0 {
let idx = (buffer << (5 - bits_left)) & 0x1F
buf.write_char(i2p_b32_alphabet[idx].to_int().unsafe_to_char())
}
buf.to_string()
}
///|
/// Decodes an I2P Base32 string (case-insensitive, optional `=` padding) into `Bytes`.
pub fn base32_decode(input : String) -> Bytes raise EncodingError {
let out : Array[Byte] = []
let mut buffer = 0
let mut bits_left = 0
for ch in input {
let c = ch.to_int()
if c == 61 || c == 32 || c == 9 || c == 10 || c == 13 {
continue
}
let val = b32_decode_char(c)
buffer = (buffer << 5) | val
bits_left += 5
if bits_left >= 8 {
bits_left -= 8
out.push(((buffer >> bits_left) & 0xFF).to_byte())
}
}
Bytes::from_array(out)
}
+110
View File
@@ -0,0 +1,110 @@
///|
/// I2P custom Base64 alphabet: `A-Z`, `a-z`, `0-9`, `-`, `~` with `=` padding.
let i2p_b64_alphabet : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~"
///|
fn b64_decode_char(c : Int32) -> Int32 raise EncodingError {
if c >= 65 && c <= 90 {
c - 65
} else if c >= 97 && c <= 122 {
c - 97 + 26
} else if c >= 48 && c <= 57 {
c - 48 + 52
} else if c == 45 {
// '-'
62
} else if c == 126 {
// '~'
63
} else {
raise InvalidCharacter("invalid I2P Base64 character code: \{c}")
}
}
///|
/// Encodes bytes using the I2P Base64 alphabet (`-` and `~`, padded with `=`).
pub fn base64_encode(data : Bytes) -> String {
let len = data.length()
if len == 0 {
return ""
}
let buf = StringBuilder(capacity=(len + 2) / 3 * 4)
let mut i = 0
while i < len {
let b0 = data[i].to_int()
let has_b1 = i + 1 < len
let has_b2 = i + 2 < len
let b1 = if has_b1 { data[i + 1].to_int() } else { 0 }
let b2 = if has_b2 { data[i + 2].to_int() } else { 0 }
let c0 = b0 >> 2
let c1 = ((b0 & 0x03) << 4) | (b1 >> 4)
let c2 = ((b1 & 0x0F) << 2) | (b2 >> 6)
let c3 = b2 & 0x3F
buf.write_char(i2p_b64_alphabet[c0].to_int().unsafe_to_char())
buf.write_char(i2p_b64_alphabet[c1].to_int().unsafe_to_char())
if has_b1 {
buf.write_char(i2p_b64_alphabet[c2].to_int().unsafe_to_char())
} else {
buf.write_char('=')
}
if has_b2 {
buf.write_char(i2p_b64_alphabet[c3].to_int().unsafe_to_char())
} else {
buf.write_char('=')
}
i += 3
}
buf.to_string()
}
///|
/// Decodes an I2P Base64 string (`-` and `~`, optional `=` padding) into `Bytes`.
pub fn base64_decode(input : String) -> Bytes raise EncodingError {
let chars : Array[Int32] = []
for ch in input {
let c = ch.to_int()
if c == 32 || c == 9 || c == 10 || c == 13 {
continue
}
chars.push(c)
}
let len = chars.length()
if len == 0 {
return b""
}
if len % 4 != 0 {
raise InvalidLength("I2P Base64 length must be a multiple of 4, got \{len}")
}
let out : Array[Byte] = Array(capacity=len / 4 * 3)
let mut i = 0
while i < len {
let c0 = chars[i]
let c1 = chars[i + 1]
let c2 = chars[i + 2]
let c3 = chars[i + 3]
let v0 = b64_decode_char(c0)
let v1 = b64_decode_char(c1)
let pad2 = c2 == 61 // '='
let pad3 = c3 == 61 // '='
if pad2 && !pad3 {
raise InvalidCharacter("invalid Base64 padding")
}
if (pad2 || pad3) && i + 4 < len {
raise InvalidCharacter("Base64 padding before end of input")
}
let v2 = if pad2 { 0 } else { b64_decode_char(c2) }
let v3 = if pad3 { 0 } else { b64_decode_char(c3) }
out.push(((v0 << 2) | (v1 >> 4)).to_byte())
if !pad2 {
out.push((((v1 & 0x0F) << 4) | (v2 >> 2)).to_byte())
}
if !pad3 {
out.push((((v2 & 0x03) << 6) | v3).to_byte())
}
i += 4
}
Bytes::from_array(out)
}
+325
View File
@@ -0,0 +1,325 @@
///|
/// Errors raised during I2P binary, Base64, Base32, or Hex encoding/decoding.
#derive(Eq, Debug)
pub suberror EncodingError {
UnexpectedEof(String)
InvalidCharacter(String)
InvalidLength(String)
ValueOutOfRange(String)
}
///|
/// Big-endian binary reader over an immutable `Bytes` buffer.
pub struct Reader {
data : Bytes
mut pos : Int32
}
///|
pub fn Reader::new(data : Bytes) -> Reader {
{ data, pos: 0, }
}
///|
pub fn Reader::position(self : Reader) -> Int32 {
self.pos
}
///|
pub fn Reader::remaining(self : Reader) -> Int32 {
self.data.length() - self.pos
}
///|
pub fn Reader::is_eof(self : Reader) -> Bool {
self.pos >= self.data.length()
}
///|
pub fn Reader::skip(self : Reader, n : Int32) -> Unit raise EncodingError {
if n < 0 || self.remaining() < n {
raise UnexpectedEof("skip: need \{n} bytes, have \{self.remaining()}")
}
self.pos += n
}
///|
pub fn Reader::read_u8(self : Reader) -> Byte raise EncodingError {
if self.remaining() < 1 {
raise UnexpectedEof("read_u8: unexpected EOF at \{self.pos}")
}
let b = self.data[self.pos]
self.pos += 1
b
}
///|
pub fn Reader::read_u16_be(self : Reader) -> UInt32 raise EncodingError {
if self.remaining() < 2 {
raise UnexpectedEof("read_u16_be: unexpected EOF at \{self.pos}")
}
let b0 = self.data[self.pos].to_uint()
let b1 = self.data[self.pos + 1].to_uint()
self.pos += 2
(b0 << 8) | b1
}
///|
pub fn Reader::read_u32_be(self : Reader) -> UInt32 raise EncodingError {
if self.remaining() < 4 {
raise UnexpectedEof("read_u32_be: unexpected EOF at \{self.pos}")
}
let b0 = self.data[self.pos].to_uint()
let b1 = self.data[self.pos + 1].to_uint()
let b2 = self.data[self.pos + 2].to_uint()
let b3 = self.data[self.pos + 3].to_uint()
self.pos += 4
(b0 << 24) | (b1 << 16) | (b2 << 8) | b3
}
///|
pub fn Reader::read_u64_be(self : Reader) -> UInt64 raise EncodingError {
if self.remaining() < 8 {
raise UnexpectedEof("read_u64_be: unexpected EOF at \{self.pos}")
}
let mut acc : UInt64 = 0UL
for i = 0; i < 8; i = i + 1 {
acc = (acc << 8) | self.data[self.pos + i].to_uint64()
}
self.pos += 8
acc
}
///|
pub fn Reader::read_bytes(
self : Reader,
len : Int32,
) -> Bytes raise EncodingError {
if len < 0 || self.remaining() < len {
raise UnexpectedEof(
"read_bytes: need \{len} bytes, have \{self.remaining()}",
)
}
let out = FixedArray::make(len, b'\x00')
for i = 0; i < len; i = i + 1 {
out[i] = self.data[self.pos + i]
}
self.pos += len
Bytes::from_array(out)
}
///|
pub fn Reader::read_remaining(self : Reader) -> Bytes {
let len = self.remaining()
let out = FixedArray::make(len, b'\x00')
for i = 0; i < len; i = i + 1 {
out[i] = self.data[self.pos + i]
}
self.pos = self.data.length()
Bytes::from_array(out)
}
///|
/// Reads an I2P String: 1-byte unsigned length prefix (0..255) followed by UTF-8 bytes.
pub fn Reader::read_i2p_string(self : Reader) -> String raise EncodingError {
let len = self.read_u8().to_int()
let raw = self.read_bytes(len)
utf8_bytes_to_string(raw)
}
///|
/// Big-endian binary writer backed by a growable byte buffer.
pub struct Writer {
buf : Array[Byte]
}
///|
pub fn Writer::new(capacity~ : Int32 = 64) -> Writer {
{ buf: Array(capacity~), }
}
///|
pub fn Writer::length(self : Writer) -> Int32 {
self.buf.length()
}
///|
pub fn Writer::write_u8(self : Writer, v : Byte) -> Unit {
self.buf.push(v)
}
///|
pub fn Writer::write_u16_be(self : Writer, v : UInt32) -> Unit {
self.buf.push(((v >> 8) & 0xFFU).to_byte())
self.buf.push((v & 0xFFU).to_byte())
}
///|
pub fn Writer::write_u32_be(self : Writer, v : UInt32) -> Unit {
self.buf.push(((v >> 24) & 0xFFU).to_byte())
self.buf.push(((v >> 16) & 0xFFU).to_byte())
self.buf.push(((v >> 8) & 0xFFU).to_byte())
self.buf.push((v & 0xFFU).to_byte())
}
///|
pub fn Writer::write_u64_be(self : Writer, v : UInt64) -> Unit {
self.buf.push(((v >> 56) & 0xFFUL).to_byte())
self.buf.push(((v >> 48) & 0xFFUL).to_byte())
self.buf.push(((v >> 40) & 0xFFUL).to_byte())
self.buf.push(((v >> 32) & 0xFFUL).to_byte())
self.buf.push(((v >> 24) & 0xFFUL).to_byte())
self.buf.push(((v >> 16) & 0xFFUL).to_byte())
self.buf.push(((v >> 8) & 0xFFUL).to_byte())
self.buf.push((v & 0xFFUL).to_byte())
}
///|
pub fn Writer::write_bytes(self : Writer, data : Bytes) -> Unit {
for i = 0; i < data.length(); i = i + 1 {
self.buf.push(data[i])
}
}
///|
/// Writes an I2P String (1-byte length + UTF-8 bytes, max 255 bytes).
pub fn Writer::write_i2p_string(
self : Writer,
s : String,
) -> Unit raise EncodingError {
let raw = string_to_utf8_bytes(s)
if raw.length() > 255 {
raise ValueOutOfRange("I2P string exceeds 255 UTF-8 bytes: \{raw.length()}")
}
self.write_u8(raw.length().to_byte())
self.write_bytes(raw)
}
///|
pub fn Writer::to_bytes(self : Writer) -> Bytes {
Bytes::from_array(self.buf)
}
///|
/// Encodes a MoonBit `String` to UTF-8 `Bytes`.
pub fn string_to_utf8_bytes(s : String) -> Bytes {
let out : Array[Byte] = []
for ch in s {
let cp = ch.to_int()
if cp < 0x80 {
out.push(cp.to_byte())
} else if cp < 0x800 {
out.push((0xC0 | (cp >> 6)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else if cp < 0x10000 {
out.push((0xE0 | (cp >> 12)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else {
out.push((0xF0 | (cp >> 18)).to_byte())
out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
}
}
Bytes::from_array(out)
}
///|
/// Decodes UTF-8 `Bytes` to a MoonBit `String`.
pub fn utf8_bytes_to_string(data : Bytes) -> String raise EncodingError {
let buf = StringBuilder()
let len = data.length()
let mut i = 0
while i < len {
let b0 = data[i].to_int()
if b0 < 0x80 {
buf.write_char(b0.unsafe_to_char())
i += 1
} else if (b0 & 0xE0) == 0xC0 {
if i + 1 >= len {
raise InvalidCharacter("truncated 2-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let cp = ((b0 & 0x1F) << 6) | (b1 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 2
} else if (b0 & 0xF0) == 0xE0 {
if i + 2 >= len {
raise InvalidCharacter("truncated 3-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let b2 = data[i + 2].to_int()
let cp = ((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 3
} else if (b0 & 0xF8) == 0xF0 {
if i + 3 >= len {
raise InvalidCharacter("truncated 4-byte UTF-8 sequence")
}
let b1 = data[i + 1].to_int()
let b2 = data[i + 2].to_int()
let b3 = data[i + 3].to_int()
let cp = ((b0 & 0x07) << 18) |
((b1 & 0x3F) << 12) |
((b2 & 0x3F) << 6) |
(b3 & 0x3F)
buf.write_char(cp.unsafe_to_char())
i += 4
} else {
raise InvalidCharacter("invalid UTF-8 lead byte: \{b0}")
}
}
buf.to_string()
}
///|
let hex_digits : Bytes = b"0123456789abcdef"
///|
/// Encodes `Bytes` as lowercase hexadecimal.
pub fn hex_encode(data : Bytes) -> String {
let buf = StringBuilder(capacity=data.length() * 2)
for i = 0; i < data.length(); i = i + 1 {
let b = data[i].to_int()
buf.write_char(hex_digits[b >> 4].to_int().unsafe_to_char())
buf.write_char(hex_digits[b & 0x0F].to_int().unsafe_to_char())
}
buf.to_string()
}
///|
fn hex_nibble(c : Int32) -> Int32 raise EncodingError {
if c >= 48 && c <= 57 {
c - 48
} else if c >= 97 && c <= 102 {
c - 87
} else if c >= 65 && c <= 70 {
c - 55
} else {
raise InvalidCharacter("invalid hex character code: \{c}")
}
}
///|
/// Decodes a hexadecimal string (case-insensitive, ignoring ASCII whitespace) into `Bytes`.
pub fn hex_decode(s : String) -> Bytes raise EncodingError {
let chars : Array[Int32] = []
for ch in s {
let c = ch.to_int()
if c == 32 || c == 9 || c == 10 || c == 13 {
continue
}
chars.push(c)
}
if chars.length() % 2 != 0 {
raise InvalidLength("hex string has odd length: \{chars.length()}")
}
let out = FixedArray::make(chars.length() / 2, b'\x00')
for i = 0; i < out.length(); i = i + 1 {
let hi = hex_nibble(chars[i * 2])
let lo = hex_nibble(chars[i * 2 + 1])
out[i] = ((hi << 4) | lo).to_byte()
}
Bytes::from_array(out)
}
+81
View File
@@ -0,0 +1,81 @@
///|
test "i2p base64 uses - and ~ instead of + and /" {
// 0xfb 0xff 0xfe -> 111110 111111 111111 111110 -> 62 63 63 62 -> "-~~-"
let raw = b"\xfb\xff\xfe"
let encoded = @encoding.base64_encode(raw)
assert_eq(encoded, "-~~-")
let decoded = @encoding.base64_decode(encoded)
assert_eq(decoded, raw)
}
///|
test "i2p base64 padding round-trip" {
let cases : Array[(Bytes, String)] = [
(b"", ""),
(b"f", "Zg=="),
(b"fo", "Zm8="),
(b"foo", "Zm9v"),
(b"foob", "Zm9vYg=="),
(b"fooba", "Zm9vYmE="),
(b"foobar", "Zm9vYmFy"),
]
for item in cases {
let (raw, expected) = item
assert_eq(@encoding.base64_encode(raw), expected)
assert_eq(@encoding.base64_decode(expected), raw)
}
}
///|
test "i2p base32 rfc4648 lowercase unpadded vectors" {
let cases : Array[(Bytes, String)] = [
(b"", ""),
(b"f", "my"),
(b"fo", "mzxq"),
(b"foo", "mzxw6"),
(b"foob", "mzxw6yq"),
(b"fooba", "mzxw6ytb"),
(b"foobar", "mzxw6ytboi"),
]
for item in cases {
let (raw, expected) = item
assert_eq(@encoding.base32_encode(raw), expected)
assert_eq(@encoding.base32_decode(expected), raw)
}
}
///|
test "i2p base32 32-byte hash produces 52 chars" {
let zeros = Bytes::make(32, b'\x00')
let b32 = @encoding.base32_encode(zeros)
assert_eq(b32.length(), 52)
assert_eq(@encoding.base32_decode(b32), zeros)
}
///|
test "binary reader and writer big-endian round-trip" {
let w = @encoding.Writer::new()
w.write_u8(b'\x42')
w.write_u16_be(0x1234U)
w.write_u32_be(0xDEADBEEFU)
w.write_u64_be(0x0102030405060708UL)
w.write_i2p_string("NTCP2")
w.write_bytes(b"\xAA\xBB")
let bytes = w.to_bytes()
let r = @encoding.Reader::new(bytes)
assert_eq(r.read_u8(), b'\x42')
assert_eq(r.read_u16_be(), 0x1234U)
assert_eq(r.read_u32_be(), 0xDEADBEEFU)
assert_eq(r.read_u64_be(), 0x0102030405060708UL)
assert_eq(r.read_i2p_string(), "NTCP2")
assert_eq(r.read_bytes(2), b"\xAA\xBB")
assert_true(r.is_eof())
}
///|
test "hex encode and decode" {
let raw = b"\x00\x0f\xa5\xff"
assert_eq(@encoding.hex_encode(raw), "000fa5ff")
assert_eq(@encoding.hex_decode("000F a5ff"), raw)
}
+1
View File
@@ -0,0 +1 @@
+67
View File
@@ -0,0 +1,67 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moon_i2p/encoding"
import {
"moonbitlang/core/debug",
}
// Values
pub fn base32_decode(String) -> Bytes raise EncodingError
pub fn base32_encode(Bytes) -> String
pub fn base64_decode(String) -> Bytes raise EncodingError
pub fn base64_encode(Bytes) -> String
pub fn hex_decode(String) -> Bytes raise EncodingError
pub fn hex_encode(Bytes) -> String
pub fn string_to_utf8_bytes(String) -> Bytes
pub fn utf8_bytes_to_string(Bytes) -> String raise EncodingError
// Errors
#derive(Eq, @debug.Debug)
pub suberror EncodingError {
UnexpectedEof(String)
InvalidCharacter(String)
InvalidLength(String)
ValueOutOfRange(String)
}
// Types and methods
pub struct Reader {
data : Bytes
mut pos : Int32
}
pub fn Reader::is_eof(Self) -> Bool
pub fn Reader::new(Bytes) -> Self
pub fn Reader::position(Self) -> Int32
pub fn Reader::read_bytes(Self, Int32) -> Bytes raise EncodingError
pub fn Reader::read_i2p_string(Self) -> String raise EncodingError
pub fn Reader::read_remaining(Self) -> Bytes
pub fn Reader::read_u16_be(Self) -> UInt32 raise EncodingError
pub fn Reader::read_u32_be(Self) -> UInt32 raise EncodingError
pub fn Reader::read_u64_be(Self) -> UInt64 raise EncodingError
pub fn Reader::read_u8(Self) -> Byte raise EncodingError
pub fn Reader::remaining(Self) -> Int32
pub fn Reader::skip(Self, Int32) -> Unit raise EncodingError
pub struct Writer {
buf : Array[Byte]
}
pub fn Writer::length(Self) -> Int32
pub fn Writer::new(capacity? : Int32) -> Self
pub fn Writer::to_bytes(Self) -> Bytes
pub fn Writer::write_bytes(Self, Bytes) -> Unit
pub fn Writer::write_i2p_string(Self, String) -> Unit raise EncodingError
pub fn Writer::write_u16_be(Self, UInt32) -> Unit
pub fn Writer::write_u32_be(Self, UInt32) -> Unit
pub fn Writer::write_u64_be(Self, UInt64) -> Unit
pub fn Writer::write_u8(Self, Byte) -> Unit
// Type aliases
// Traits