This repository has been archived by the owner on Sep 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
Feature/starknet #83
Closed
Closed
Feature/starknet #83
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9023144
draft: implement starknet compatibility
b87245c
draft: starknet-signing in-view
6abc84f
update
92cf6d7
chore: fixed issue with `verify`
Darlington02 a6c7181
ft: add starknetsigner
7e52eef
chore: fix static value mutation
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
}); | ||
}); | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} 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 }); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
||
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, | ||
}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
beforeinit
, you would see that verification doesn't work