Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code enhancements #354

Merged
merged 4 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/smartcontracts/code.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { assert } from "chai";
import { Code } from "./code";
import { Hash } from "../hash";

describe("Code Class Tests", function() {
const sampleHex = "abcdef0123456789";
const sampleBuffer = Buffer.from(sampleHex, "hex");

it("should create Code from buffer", function() {
const code = Code.fromBuffer(sampleBuffer);

assert.instanceOf(code, Code);
assert.equal(code.toString(), sampleHex);
});

it("should create Code from hex string", function() {
const code = Code.fromHex(sampleHex);

assert.instanceOf(code, Code);
assert.equal(code.toString(), sampleHex);
});

it("should return the correct buffer from valueOf", function() {
const code = Code.fromHex(sampleHex);
const buffer = code.valueOf();

assert.isTrue(Buffer.isBuffer(buffer));
assert.equal(buffer.toString("hex"), sampleHex);
});

it("should compute hash correctly", function() {
const code = Code.fromHex(sampleHex);
const hash = code.computeHash();

assert.instanceOf(hash, Buffer);
assert.equal(hash.toString('hex'), 'ac86b78afd9bdda3641a47a4aff2a7ee26acd40cc534d63655e9dfbf3f890a02')
});
});
20 changes: 20 additions & 0 deletions src/smartcontracts/code.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import { Hash } from "../hash";

const createHasher = require('blake2b')
michavie marked this conversation as resolved.
Show resolved Hide resolved
const CODE_HASH_LENGTH = 32

/**
* Bytecode of a Smart Contract, as an abstraction.
*/
Expand All @@ -15,6 +20,13 @@ export class Code {
return new Code(code.toString("hex"));
}

/**
* Creates a Code object from a hex-encoded string.
*/
static fromHex(hex: string): Code {
popenta marked this conversation as resolved.
Show resolved Hide resolved
return new Code(hex)
}

/**
* Returns the bytecode as a hex-encoded string.
*/
Expand All @@ -25,4 +37,12 @@ export class Code {
valueOf(): Buffer {
return Buffer.from(this.hex, "hex");
}

computeHash(): Buffer {
const hash = createHasher(CODE_HASH_LENGTH)
.update(this.valueOf())
.digest();

return Buffer.from(hash)
}
}
Loading