Skip to content
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
15 changes: 8 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"typescript": "^5.4.5"
},
"dependencies": {
"@coti-io/coti-sdk-typescript": "^1.0.4",
"@coti-io/coti-sdk-typescript": "^1.0.9",
"ethers": "^6.13.1"
},
"scripts": {
Expand Down
13 changes: 12 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,15 @@ export {JsonRpcApiProvider} from './providers/JsonRpcApiProvider'
export {JsonRpcSigner} from './providers/JsonRpcSigner'
export {BrowserProvider} from './providers/BrowserProvider'
export * from './types'
export {itBool, itUint, itString, ctBool, ctUint, ctString, itUint256, ctUint256} from '@coti-io/coti-sdk-typescript'
export {
itBool,
itUint,
itString,
itUint256,
itInt256,
ctBool,
ctUint,
ctString,
ctUint256,
ctInt256
} from '@coti-io/coti-sdk-typescript'
57 changes: 57 additions & 0 deletions src/providers/JsonRpcSigner.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import {
ctInt256,
ctString,
ctUint,
ctUint256,
decodeUint,
decryptInt256,
decryptString,
decryptUint,
decryptUint256,
encodeKey,
encodeUint,
encrypt,
itInt256,
itString,
itUint,
itUint256
Expand Down Expand Up @@ -188,6 +191,32 @@ export class JsonRpcSigner extends BaseJsonRpcSigner {
}
}

/**
* Builds input text (itInt256) for signed 256-bit values.
* Two's-complement encodes then delegates to {@link #prepareIT256}.
*/
async #prepareSignedIT256(
plaintext: bigint,
userKey: string,
contractAddress: string,
functionSelector: string
): Promise<itInt256> {
const value = BigInt(plaintext)
const min = -(1n << 255n)
const max = (1n << 255n) - 1n
if (value < min || value > max) {
throw new RangeError("Plaintext size must fit in int256.")
}

const unsigned = value < 0n ? (1n << 256n) + value : value
return await this.#prepareIT256(
unsigned,
userKey,
contractAddress,
functionSelector
)
}

/**
* Builds input text (itString) for string values
* IMPORTANT: Strings are chunked in 8-byte (64-bit) increments to ensure compatibility
Expand Down Expand Up @@ -377,6 +406,34 @@ export class JsonRpcSigner extends BaseJsonRpcSigner {
return decryptUint256(ciphertext, this._userOnboardInfo!.aesKey!);
}

/**
* Encrypts a signed int256 (uses #prepareSignedIT256).
*/
async encryptValueSigned256(
plaintextValue: bigint | number,
contractAddress: string,
functionSelector: string
): Promise<itInt256> {
await this._ensureAesKey();

const value = typeof plaintextValue === 'number' ? BigInt(plaintextValue) : plaintextValue;

return await this.#prepareSignedIT256(
value,
this._userOnboardInfo!.aesKey!,
contractAddress,
functionSelector
);
}

/**
* Decrypts ctInt256 ciphertexts (uses decryptInt256).
*/
async decryptValueSigned256(ciphertext: ctInt256): Promise<bigint> {
await this._ensureAesKey();
return decryptInt256(ciphertext, this._userOnboardInfo!.aesKey!);
}

/**
* Decrypts ctUint and ctString ciphertexts
*/
Expand Down
2 changes: 1 addition & 1 deletion src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const ONBOARD_CONTRACT_ADDRESS = "0xe1dA9B857E1196D0BeDBE46960586cBc3F909C17"
export const ONBOARD_CONTRACT_ADDRESS = "0x536A67f0cc46513E7d27a370ed1aF9FDcC7A5095"

export const ONBOARD_CONTRACT_ABI = [
{
Expand Down
10 changes: 7 additions & 3 deletions src/utils/onboard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Contract, ContractRunner, keccak256, Provider } from "ethers"
import { getDefaultProvider } from "./network"
import { decryptRSA, generateRSAKeyPair, recoverUserKey, sign } from "@coti-io/coti-sdk-typescript"
import { generateRSAKeyPair, recoverUserKey, sign } from "@coti-io/coti-sdk-typescript"
import { CotiNetwork, RsaKeyPair } from "../types"
import { ONBOARD_CONTRACT_ABI } from "./constants"
import { Wallet } from "../wallet/Wallet"
Expand Down Expand Up @@ -64,8 +64,12 @@ export async function recoverAesFromTx(txHash: string,

const accountOnboardContract: any = getAccountOnboardContract(defaultOnboardContractAddress)
const decodedLog = accountOnboardContract.interface.parseLog(receipt.logs[0])
const encryptedKey = decodedLog.args.userKey
return decryptRSA(rsaKey.privateKey, encryptedKey.substring(2))
if (!decodedLog) {
throw new Error("failed to get onboard tx info")
}
const userKey1 = decodedLog.args.userKey1.substring(2)
const userKey2 = decodedLog.args.userKey2.substring(2)
return recoverUserKey(rsaKey.privateKey, userKey1, userKey2)
} catch (e) {
console.error("failed to get onboard tx info")
throw Error(`unable to recover aes key from transaction.`)
Expand Down
37 changes: 36 additions & 1 deletion src/wallet/Wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@ import {Provider, SigningKey, Wallet as BaseWallet} from "ethers";
import {CotiNetwork, OnboardInfo, RsaKeyPair} from "../types";
import {
buildStringInputText,
ctInt256,
ctString,
ctUint,
ctUint256,
decryptInt256,
decryptString,
decryptUint,
decryptUint256,
itInt256,
itString,
itUint,
itUint256,
prepareIT,
prepareIT256
prepareIT256,
prepareSignedIT256
} from "@coti-io/coti-sdk-typescript";
import {getAccountBalance, getDefaultProvider, onboard, recoverAesFromTx} from "../utils";
import {ONBOARD_CONTRACT_ADDRESS} from "../utils/constants";
Expand Down Expand Up @@ -156,6 +160,37 @@ export class Wallet extends BaseWallet {
return decryptUint256(ciphertext, this._userOnboardInfo!.aesKey!);
}

/**
* Encrypts a signed int256 (uses prepareSignedIT256).
*/
async encryptValueSigned256(
plaintextValue: bigint | number,
contractAddress: string,
functionSelector: string
): Promise<itInt256> {
await this._ensureAesKey();

const value = typeof plaintextValue === 'number' ? BigInt(plaintextValue) : plaintextValue;

return prepareSignedIT256(
value,
{
wallet: this as any,
userKey: this._userOnboardInfo!.aesKey!
},
contractAddress,
functionSelector
);
}

/**
* Decrypts ctInt256 ciphertexts (uses decryptInt256).
*/
async decryptValueSigned256(ciphertext: ctInt256): Promise<bigint> {
await this._ensureAesKey();
return decryptInt256(ciphertext, this._userOnboardInfo!.aesKey!);
}

/**
* Decrypts ctUint and ctString ciphertexts
*/
Expand Down
6 changes: 5 additions & 1 deletion test/example.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
PRIVATE_KEY=
USER_KEY=
AES_KEY=
RSA_PUB=
RSA_PRIVATE=
RSA_PRIVATE=
TX_HASH=
ACCOUNT_ADDRESS=
PUBLIC_KEY=
28 changes: 28 additions & 0 deletions test/jsonRpcSigner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,34 @@ async function test() {
throw error;
}
}

// Test signed int256 round-trip (uses encryptValueSigned256)
console.log("\n7. Testing signed int256 encryption/decryption...");
const signedValues = [0n, -1n, (1n << 255n) - 1n, -(1n << 255n)];
for (const value of signedValues) {
const encrypted = await signer.encryptValueSigned256(value, contractAddress, functionSelector);
const decrypted = await signer.decryptValueSigned256(encrypted.ciphertext);
console.log(` Original: ${value.toString()}`);
console.log(` Decrypted: ${decrypted.toString()}`);
if (decrypted !== value) {
throw new Error(`signed int256 mismatch: expected ${value}, got ${decrypted}`);
}
}
console.log("✅ Signed int256 encryption/decryption: PASSED");

// Test out-of-range signed int256 should fail
console.log("\n8. Testing signed int256 range rejection...");
try {
await signer.encryptValueSigned256(1n << 255n, contractAddress, functionSelector);
console.log("❌ Should have thrown error for value above int256 max");
throw new Error("encryptValueSigned256 should reject values outside int256");
} catch (error: any) {
if (error instanceof RangeError || error.message.includes("int256")) {
console.log("✅ Correctly rejected out-of-range signed int256");
} else {
throw error;
}
}

console.log("\n" + "=".repeat(60));
console.log("✅ ALL TESTS PASSED!");
Expand Down
56 changes: 56 additions & 0 deletions test/wallet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

it('Should successfully onboard the wallet', async function () {
await wallet.generateOrRecoverAes()
expect(wallet.getUserOnboardInfo()?.aesKey).to.not.equal(null);

Check warning on line 22 in test/wallet.test.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer "expect(wallet.getUserOnboardInfo()?.aesKey).to.not.be.null" over this generic assertion; dedicated matchers read better and report clearer failures.

See more on https://sonarcloud.io/project/issues?id=coti-io_coti-ethers&issues=AZ-Ek-Tr-k2f51dfJW3H&open=AZ-Ek-Tr-k2f51dfJW3H&pullRequest=10
expect(wallet.getUserOnboardInfo()?.aesKey).to.equal(process.env.USER_KEY);
})

Expand Down Expand Up @@ -113,6 +113,62 @@
wallet.clearUserOnboardInfo()
expect(wallet.getUserOnboardInfo()).to.be.undefined
})

it('Should successfully encrypt and decrypt signed int256', async function () {
const wallet = new Wallet(Wallet.createRandom().privateKey);
wallet.disableAutoOnboard();
wallet.setAesKey(process.env.AES_KEY || "e0262555000f88878acc5b38146fbd05");
const contractAddress = "0x0000000000000000000000000000000000000001";
const functionSelector = "0x11223344";
const values = [0n, -1n, 42n, -42n, (1n << 255n) - 1n, -(1n << 255n)];

for (const value of values) {
const { ciphertext, signature } = await wallet.encryptValueSigned256(
value,
contractAddress,
functionSelector
);
expect(signature).to.be.instanceOf(Uint8Array);
expect(await wallet.decryptValueSigned256(ciphertext)).to.equal(value);
}
})

it('Should decrypt signed int256 using uint256 two\'s-complement wire format', async function () {
const wallet = new Wallet(Wallet.createRandom().privateKey);
wallet.disableAutoOnboard();
wallet.setAesKey(process.env.AES_KEY || "e0262555000f88878acc5b38146fbd05");
const contractAddress = "0x0000000000000000000000000000000000000001";
const functionSelector = "0x11223344";

const { ciphertext } = await wallet.encryptValueSigned256(-1n, contractAddress, functionSelector);
expect(await wallet.decryptValue256(ciphertext)).to.equal((1n << 256n) - 1n);
})

it('Should reject signed int256 outside int256 range', async function () {
const wallet = new Wallet(Wallet.createRandom().privateKey);
wallet.disableAutoOnboard();
wallet.setAesKey(process.env.AES_KEY || "e0262555000f88878acc5b38146fbd05");
const contractAddress = "0x0000000000000000000000000000000000000001";
const functionSelector = "0x11223344";

let errorThrown = false;
try {
await wallet.encryptValueSigned256((1n << 255n), contractAddress, functionSelector);
} catch (error) {
errorThrown = true;
expect(error).to.be.instanceOf(RangeError);
}
expect(errorThrown).to.be.true;

errorThrown = false;
try {
await wallet.encryptValueSigned256(-(1n << 255n) - 1n, contractAddress, functionSelector);
} catch (error) {
errorThrown = true;
expect(error).to.be.instanceOf(RangeError);
}
expect(errorThrown).to.be.true;
})
})

function parseRsaKey(key: string | undefined): Uint8Array {
Expand Down