Skip to content

Commit

Permalink
feat: add support for ipv4 peers (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonatan-Chaverri authored Oct 2, 2024
1 parent 8c4de1a commit e4b10f7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 18 additions & 0 deletions src/network/message/utils.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const std = @import("std");

pub fn convertIPv4ToIPv6(address: std.net.Address) std.net.Address {
// Convert IPv4 to IPv6-mapped IPv4 address
const ipv4_address = address.in;

var ipv6_mapped: [16]u8 = [_]u8{0} ** 16;

// Set bytes 10 and 11 to 0xff
ipv6_mapped[10] = 0xff;
ipv6_mapped[11] = 0xff;

// Copy the IPv4 address into the last 4 bytes of the IPv6-mapped address
const ipv4_bytes = std.mem.asBytes(&ipv4_address.sa.addr);
@memcpy(ipv6_mapped[12..16], ipv4_bytes[0..4]);

return std.net.Address.initIp6(ipv6_mapped, ipv4_address.getPort(), 0, 0);
}
7 changes: 5 additions & 2 deletions src/network/peer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const net = std.net;
const protocol = @import("./protocol/lib.zig");
const wire = @import("./wire/lib.zig");
const Config = @import("../config/config.zig").Config;
const MessageUtils = @import("./message/utils.zig");

pub const Boundness = enum {
inbound,
Expand Down Expand Up @@ -89,11 +90,13 @@ pub const Peer = struct {
}

/// Send version message to peer
fn sendVersionMessage(self: *Peer) !void {
fn sendVersionMessage(self: *const Peer) !void {
const address = if (self.address.any.family == std.posix.AF.INET) MessageUtils.convertIPv4ToIPv6(self.address) else self.address;

const message = protocol.messages.VersionMessage.new(
self.config.protocol_version,
.{ .ip = std.mem.zeroes([16]u8), .port = 0, .services = self.config.services },
.{ .ip = self.address.in6.sa.addr, .port = self.address.in6.getPort(), .services = 0 },
.{ .ip = address.in6.sa.addr, .port = address.in6.getPort(), .services = 0 },
std.crypto.random.int(u64),
self.config.bestBlock(),
);
Expand Down

0 comments on commit e4b10f7

Please sign in to comment.