Skip to content
This repository has been archived by the owner on Sep 4, 2024. It is now read-only.

Feature/starknet #83

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@
"base64url": "^3.0.1",
"bs58": "^4.0.1",
"keccak": "^3.0.2",
"secp256k1": "^5.0.0"
"secp256k1": "^5.0.0",
"starknet": "^6.11.0"
},
"optionalDependencies": {
"@randlabs/myalgo-connect": "^1.1.2",
Expand Down
1 change: 0 additions & 1 deletion src/DataItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ export class DataItem implements BundleItem {
const tags: { name: string; value: string }[] = deserializeTags(
Buffer.from(buffer.subarray(tagsStart + 16, tagsStart + 16 + numberOfTagBytes)),
);

if (tags.length !== numberOfTags) {
return false;
}
Expand Down
108 changes: 108 additions & 0 deletions src/__tests__/starknet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
jest.setTimeout(20000);
import StarknetSigner from "../signing/chains/StarknetSigner";
import { RpcProvider } from "starknet";
import Crypto from "crypto";
import { createData } from "../../index";

const tagsTestVariations = [
{ description: "no tags", tags: undefined },
{ description: "empty tags", tags: [] },
{ description: "single tag", tags: [{ name: "Content-Type", value: "image/png" }] },
{
description: "multiple tags",
tags: [
{ name: "Content-Type", value: "image/png" },
{ name: "hello", value: "world" },
{ name: "lorem", value: "ipsum" },
],
},
];

const dataTestVariations = [
{ description: "empty string", data: "" },
{ description: "small string", data: "hello world" },
{ description: "large string", data: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{};':\",./<>?`~" },
{ description: "empty buffer", data: Buffer.from([]) },
{ description: "small buffer", data: Buffer.from("hello world") },
{ description: "large buffer", data: Buffer.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{};':\",./<>?`~") },
];

describe("Typed Starknet Signer", () => {
let signer: StarknetSigner;
const provider = new RpcProvider({ nodeUrl: "https://starknet-sepolia.public.blastapi.io" });

const PrivateKey = "0x005d5c250b5c181684ae6d8ebfa0faeac3ad0c6f31a6c2f102a2fffddba00a05";
const myAddressInStarknet = "0x02F659cf8CCE41168B8c0A8BedCE468E33BE1B7bd26E920266C025Dc0F8FBD1b";

beforeAll(async () => {
signer = new StarknetSigner(provider, myAddressInStarknet, PrivateKey);
await signer.init();
});

it("should sign a known value", async () => {
const data = Buffer.from("Hello-world!");
const expectedSignature = Buffer.from([
2, 154, 223, 194, 248, 201, 115, 24, 151, 209, 169, 144, 101, 125, 81, 118, 127, 193, 75, 181, 252, 203, 34, 209, 32, 188, 0, 51, 207, 153, 230,
253, 2, 158, 118, 14, 24, 86, 192, 14, 32, 126, 155, 125, 147, 175, 89, 174, 56, 100, 178, 79, 171, 232, 78, 215, 3, 216, 2, 18, 30, 90, 14, 32,
1,
]);

const signature = await signer.sign(data);
const signatureBuffer = Buffer.from(signature);
expect(signatureBuffer).toEqual(expectedSignature);
});

it("should verify a known values", async () => {
const data = Buffer.from("Hello-world!");
const signature = await signer.sign(data);
const isValid = await StarknetSigner.verify(signer.publicKey, data, signature);
expect(isValid).toEqual(true);
});
it("should sign & verify an unknown value", async () => {
const randData = Crypto.randomBytes(256);
const signature = await signer.sign(randData);
const isValid = await StarknetSigner.verify(signer.publicKey, randData, signature);
expect(isValid).toEqual(true);
});
describe("Create & Validate DataItem", () => {
it("should create a valid dataItem", async () => {
const data = "Hello, Bundlr!";
const tags = [{ name: "Hello", value: "Bundlr" }];
const item = createData(data, signer, { tags });
await item.sign(signer);
expect(await item.isValid()).toBe(true);
});

describe("With an unknown wallet", () => {
it("should sign & verify an unknown value", async () => {
const randSigner = new StarknetSigner(provider, myAddressInStarknet, PrivateKey);
const randData = Crypto.randomBytes(256);
const signature = await randSigner.sign(randData);
const isValid = await StarknetSigner.verify(signer.publicKey, randData, signature);
expect(isValid).toEqual(true);
});
});

describe("and given we want to create a dataItem", () => {
describe.each(tagsTestVariations)("with $description tags", ({ tags }) => {
describe.each(dataTestVariations)("and with $description data", ({ data }) => {
it("should create a valid dataItem", async () => {
const item = createData(data, signer, { tags });
await item.sign(signer);
expect(await item.isValid()).toBe(true);
});
it("should set the correct tags", async () => {
const item = createData(data, signer, { tags });
await item.sign(signer);
expect(item.tags).toEqual(tags ?? []);
});
it("should set the correct data", async () => {
const item = createData(data, signer, { tags });
await item.sign(signer);
expect(item.rawData).toEqual(Buffer.from(data));
});
});
});
});
});
});
6 changes: 6 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export enum SignatureConfig {
INJECTEDAPTOS = 5,
MULTIAPTOS = 6,
TYPEDETHEREUM = 7,
STARKNET = 8,
}

export interface SignatureMeta {
Expand Down Expand Up @@ -50,4 +51,9 @@ export const SIG_CONFIG: Record<SignatureConfig, SignatureMeta> = {
pubLength: 42,
sigName: "typedEthereum",
},
[SignatureConfig.STARKNET]:{
sigLength:65,
pubLength: 32,
sigName:'starknet'
}
};
128 changes: 128 additions & 0 deletions src/signing/chains/StarknetSigner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import {
Account,
RpcProvider,
Signature,
WeierstrassSignatureType,
ec,
encode,
typedData,
Signer as StarknetSignerAlias,
TypedData,
TypedDataRevision,
} from "starknet";
import type { Signer } from "../index";
import { SignatureConfig, SIG_CONFIG } from "../../constants";

export default class StarknetSigner implements Signer {
protected signer: Account;
public publicKey: Buffer;
public static address: string;
private static privateKey: string;
public static provider: RpcProvider;
public static chainId: string;
readonly ownerLength: number = SIG_CONFIG[SignatureConfig.STARKNET].pubLength;
readonly signatureLength: number = SIG_CONFIG[SignatureConfig.STARKNET].sigLength;
readonly signatureType: number = SignatureConfig.STARKNET;

// Constructor to set static properties
constructor(provider: RpcProvider, address: string, pKey: string) {
StarknetSigner.provider = provider;
StarknetSigner.address = address;
StarknetSigner.privateKey = pKey;
this.signer = new Account(provider, address, pKey);
}

public async init() {
try {
const signer = new StarknetSignerAlias(StarknetSigner.privateKey);
const pub_key = await signer.getPubKey();
let hexKey = pub_key.startsWith("0x") ? pub_key.slice(2) : pub_key;
this.publicKey = Buffer.from(0 + hexKey, "hex");
StarknetSigner.chainId = await StarknetSigner.provider.getChainId();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overriding a static signer property is a very bad behaviour - right now your test cases pass because this change sticks around between test runs - if you removed this, or tried running verify before init, you would see that verification doesn't work

} catch (error) {
console.error("Error setting public key or chain ID:", error);
}
}

async sign(message: Uint8Array, _opts?: any): Promise<Uint8Array> {
if (!this.signer.signMessage) throw new Error("Selected signer does not support message signing");

let message_to_felt = convertToFelt252(message);
let TypedDataMessage = typed_domain({ chainId: StarknetSigner.chainId, message: message_to_felt });
let signature: Signature = (await this.signer.signMessage(TypedDataMessage.typemessage)) as WeierstrassSignatureType;

const r = BigInt(signature.r).toString(16).padStart(64, "0");
const s = BigInt(signature.s).toString(16).padStart(64, "0");
// @ts-ignore
const recovery = signature.recovery.toString(16).padStart(2, "0");

const rArray = Uint8Array.from(Buffer.from(r, "hex"));
const sArray = Uint8Array.from(Buffer.from(s, "hex"));
const recoveryArray = Uint8Array.from(Buffer.from(recovery, "hex"));

const result = new Uint8Array(rArray.length + sArray.length + recoveryArray.length);
result.set(rArray);
result.set(sArray, rArray.length);
result.set(recoveryArray, rArray.length + sArray.length);

return result;
}

static async verify(_pk: Buffer, message: Uint8Array, _signature: Uint8Array, _opts?: any): Promise<boolean> {
let message_to_felt = convertToFelt252(message);
let TypedDataMessage = typed_domain({ chainId: StarknetSigner.chainId, message: message_to_felt });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chainId would be undefined here as nothing sets it (data item verification doesn't run the init function) - this would cause verification to fail.
I'd suggest adding the chainID to the public key/signature data so you can use it in the verify function.


const fullPubKey = encode.addHexPrefix(encode.buf2hex(ec.starkCurve.getPublicKey(StarknetSigner.privateKey, true)));

const msgHash = typedData.getMessageHash(TypedDataMessage.typemessage, StarknetSigner.address);

return ec.starkCurve.verify(_signature.slice(0, -1), msgHash, fullPubKey);
}
}

// Utility function to convert Uint8Array to felt252
function convertToFelt252(data: Uint8Array): bigint[] {
const felt252Array: bigint[] = [];
const felt252Size = 31;

for (let i = 0; i < data.length; i += felt252Size) {
let value = BigInt(0);
for (let j = 0; j < felt252Size && i + j < data.length; j++) {
value = (value << BigInt(8)) | BigInt(data[i + j]);
}
felt252Array.push(value);
}

return felt252Array;
}

interface TypedParam {
chainId: string | number;
message: bigint[];
}

export const typed_domain = ({ chainId, message }: TypedParam): { typemessage: TypedData } => {
const typemessage: TypedData = {
domain: {
name: "Arbundle",
chainId: chainId,
version: "1.0.2",
revision: TypedDataRevision.ACTIVE,
},
message: {
message,
},
primaryType: "Message",
types: {
Message: [{ name: "message", type: "felt*" }],
StarknetDomain: [
{ name: "name", type: "string" },
{ name: "chainId", type: "felt" },
{ name: "version", type: "string" },
],
},
};
return {
typemessage,
};
};
1 change: 1 addition & 0 deletions src/signing/chains/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export { default as MultiSignatureAptosSigner } from "./multiSignatureAptos";
export { default as TypedEthereumSigner } from "./TypedEthereumSigner";
export * from "./InjectedTypedEthereumSigner";
export { default as ArconnectSigner } from "./arconnectSigner";
export { default as InjectedStarknetSigner } from "./StarknetSigner";
4 changes: 4 additions & 0 deletions src/signing/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
InjectedAptosSigner,
MultiSignatureAptosSigner,
TypedEthereumSigner,
InjectedStarknetSigner
} from "./chains/index";

export type IndexToType = Record<
Expand Down Expand Up @@ -42,4 +43,7 @@ export const indexToType: IndexToType = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
7: TypedEthereumSigner,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
8: InjectedStarknetSigner
};
Loading
Loading