Skip to content

Commit

Permalink
test: implement dnsname encoder
Browse files Browse the repository at this point in the history
  • Loading branch information
petejkim committed Mar 2, 2022
1 parent 773cb33 commit 3524122
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
29 changes: 29 additions & 0 deletions src/dnsname.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Adapted from https://github.com/petejkim/ens-dnsname/blob/master/dnsname.go#L59
export function encode(name: string): Buffer {
const trimmed = name.replace(/^\.+|\.+$/g, "");

// split name into labels
const labels = trimmed.split(".").map((l) => Buffer.from(l, "utf8"));

const encoded = Buffer.alloc(Buffer.from(trimmed, "utf8").byteLength + 2);
let offset = 0;

for (const label of labels) {
const l = label.byteLength;

// length must be less than 64
if (l > 63) {
throw new Error("label too long");
}

// write length
encoded.writeUInt8(l, offset);
offset++;

// write label
label.copy(encoded, offset);
offset += l;
}

return encoded;
}
26 changes: 26 additions & 0 deletions test/dnsname.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { expect } from "chai";
import { encode } from "../src/dnsname";

describe("dnsname", () => {
describe("encode", () => {
it("encodes a given name in the ens-compatible dns wire format", () => {
["test.eth", ".test.eth", "test.eth.", "..test.eth..."].forEach((name) =>
expect(encode(name).toString("hex")).to.equal("04746573740365746800")
);
[
["pete.test.eth", "047065746504746573740365746800"],
["this.is.test.eth", "047468697302697304746573740365746800"],
["example.xyz", "076578616d706c650378797a00"],
["", "0000"],
].forEach((tc) => expect(encode(tc[0]).toString("hex")).to.equal(tc[1]));
});

it("throws an error if a label has greater than 63 characters", () => {
expect(() =>
encode(
"0000000001000000000200000000030000000004000000000500000000061234.eth"
)
).to.throw("label too long");
});
});
});
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
},
"exclude": ["node_modules"],
"files": ["./hardhat.config.ts"],
"include": ["tasks/**/*", "test/**/*", "types/**/*"]
"include": ["tasks/**/*", "test/**/*", "types/**/*", "src/**/*"]
}

0 comments on commit 3524122

Please sign in to comment.