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

feat: create kms account for using with aws kms #120

Merged
merged 4 commits into from
Sep 29, 2024
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
5 changes: 5 additions & 0 deletions .changeset/giant-camels-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@fuels/kms-account': minor
---

Create KMSAccount for using KMS from AWS with fuels typescript SDK.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ dist-ssr
# turbo
.turbo
tsconfig.tsbuildinfo
*.tgz
5 changes: 4 additions & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
module.exports = {
projects: ['<rootDir>/packages/*'],
projects: [
'<rootDir>/packages/local-storage',
'<rootDir>/packages/react-xstore',
],
};
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"prettier:check": "prettier --check .",
"prettier:format": "prettier --write .",
"test": "turbo run test --parallel",
"test:ci": "jest --ci --testLocationInResults --json --coverage",
"test:ci": "jest --ci --testLocationInResults --json --coverage --config jest.config.ts",
"test:clear": "pnpm -r exec jest --clearCache",
"test:coverage": "turbo run test --parallel -- --coverage",
"ts:check": "turbo run ts:check",
Expand Down Expand Up @@ -86,7 +86,8 @@
"@adobe/css-tools@<4.3.2": ">=4.3.2",
"braces@<3.0.3": ">=3.0.3",
"ws@>=8.0.0 <8.17.1": ">=8.17.1",
"micromatch@<4.0.8": ">=4.0.8"
"micromatch@<4.0.8": ">=4.0.8",
"rollup": ">=3.29.5"
}
}
}
42 changes: 42 additions & 0 deletions packages/kms-account/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@fuels/kms-account",
"version": "0.23.0",
"license": "Apache-2.0",
"main": "src/index.ts",
"publishConfig": {
"access": "public",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"typings": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/index.js",
"default": "./dist/index.mjs"
}
},
"files": [
"dist"
]
},
"scripts": {
"build": "tsup --dts",
"ts:check": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"peerDependencies": {
"fuels": ">=0.94.8"
},
"devDependencies": {
"@fuels/tsup-config": "workspace:*",
"aws-sdk-client-mock": "^4.0.2",
"fuels": "^0.94.8",
"vitest": "^2.1.1"
},
"dependencies": {
"@aws-sdk/client-kms": "^3.658.1",
"@noble/curves": "^1.6.0",
"asn1js": "^3.0.5"
}
}
82 changes: 82 additions & 0 deletions packages/kms-account/src/KMSAccount/account.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
GetPublicKeyCommand,
KMSClient,
SignCommand,
} from '@aws-sdk/client-kms';
import { secp256k1 } from '@noble/curves/secp256k1';
import { mockClient } from 'aws-sdk-client-mock';
import { Address, bn, concat, hashMessage, Signer } from 'fuels';
import { launchTestNode } from 'fuels/test-utils';
import { test, describe, expect, beforeAll } from 'vitest';

import { KMSAccount } from './account';

const MOCK_HEADER_PUBLIC_KEY =
'0x3056301006072a8648ce3d020106052b8104000a034200';

describe('KMSAccount', () => {
// TODO: implement test for sign using mocked implementation
beforeAll(() => {
const kmsClientMock = mockClient(KMSClient);
const priv = secp256k1.utils.randomPrivateKey();
const pubKey = secp256k1.getPublicKey(priv, false);
const publicKeyASN1 = concat([MOCK_HEADER_PUBLIC_KEY, pubKey]);

kmsClientMock.on(GetPublicKeyCommand).resolves({
PublicKey: publicKeyASN1,
});

kmsClientMock.on(SignCommand).callsFake((params) => {
const { SigningAlgorithm, MessageType, Message } = params;
if (SigningAlgorithm === 'ECDSA_SHA_256' && MessageType === 'DIGEST') {
const signature = secp256k1.sign(Message, priv).toDERRawBytes(false);
return {
Signature: signature,
};
}
return {};
});
});

test('should be able to create a KMSAccount', async () => {
using launched = await launchTestNode();
const account = await KMSAccount.create('mock-id', {}, launched.provider);
expect(account.address).toBeDefined();
});

test('should be able to sign a message', async () => {
using launched = await launchTestNode();
const account = await KMSAccount.create('mock-id', {}, launched.provider);
const message = 'Hello, world!';
const signature = await account.signMessage(message);
const recoveredAddress = Signer.recoverAddress(
hashMessage(message),
signature,
);

expect(recoveredAddress).toEqual(account.address);
});

test('should be able to sign a transaction', async () => {
using launched = await launchTestNode();
const account = await KMSAccount.create('mock-id', {}, launched.provider);

// Send 1 coin to the account to be able to create a transfer
await (
await launched.wallets[0].transfer(account.address, bn.parseUnits('1'))
).waitForResult();

const transaction = await account.createTransfer(
Address.fromRandom(),
bn.parseUnits('0.1'),
);
const signature = await account.signTransaction(transaction);
const chainId = await launched.provider.getChainId();
const recoveredAddress = Signer.recoverAddress(
transaction.getTransactionId(chainId),
signature,
);

expect(recoveredAddress).toEqual(account.address);
});
});
98 changes: 98 additions & 0 deletions packages/kms-account/src/KMSAccount/account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type { KMSClientConfig } from '@aws-sdk/client-kms';
import type {
BytesLike,
CallResult,
EstimateTransactionParams,
Provider,
ProviderSendTxParams,
TransactionRequest,
TransactionRequestLike,
TransactionResponse,
} from 'fuels';
import { Account, hashMessage, hexlify, transactionRequestify } from 'fuels';

import { KMSSigner } from './signer';

export class KMSAccount extends Account {
protected signer: KMSSigner;

constructor(address: string, provider: Provider, signer: KMSSigner) {
super(address, provider);
this.signer = signer;
}

static async create(
kmsKeyId: string,
kmsClientConfig: KMSClientConfig,
provider: Provider,
) {
const kmsSigner = await KMSSigner.create(kmsKeyId, kmsClientConfig);
return new KMSAccount(kmsSigner.address, provider, kmsSigner);
}

protected async _sign(digest: BytesLike): Promise<string> {
return this.signer.sign(digest);
}

/**
* All the code bellow is copied form WalletUnlocked from fuels
*/
async signMessage(message: string): Promise<string> {
const signedMessage = await this._sign(hashMessage(message));
return hexlify(signedMessage);
}

async signTransaction(
transactionRequestLike: TransactionRequestLike,
): Promise<string> {
const transactionRequest = transactionRequestify(transactionRequestLike);
const chainId = this.provider.getChainId();
const hashedTransaction = transactionRequest.getTransactionId(chainId);
const signature = await this._sign(hashedTransaction);
return hexlify(signature);
}

async populateTransactionWitnessesSignature<T extends TransactionRequest>(
transactionRequestLike: TransactionRequestLike,
) {
const transactionRequest = transactionRequestify(
transactionRequestLike,
) as T;
const signedTransaction = await this.signTransaction(transactionRequest);

transactionRequest.updateWitnessByOwner(this.address, signedTransaction);

return transactionRequest;
}

async sendTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = false }: ProviderSendTxParams = {},
): Promise<TransactionResponse> {
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
await this.provider.estimateTxDependencies(transactionRequest);
}
return this.provider.sendTransaction(
await this.populateTransactionWitnessesSignature(transactionRequest),
{ estimateTxDependencies: false },
);
}

async simulateTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true }: EstimateTransactionParams = {},
): Promise<CallResult> {
const transactionRequest = transactionRequestify(transactionRequestLike);
if (estimateTxDependencies) {
await this.provider.estimateTxDependencies(transactionRequest);
}
return this.provider.dryRun(
await this.populateTransactionWitnessesSignature(transactionRequest),
{
utxoValidation: true,
estimateTxDependencies: false,
},
);
}
}
2 changes: 2 additions & 0 deletions packages/kms-account/src/KMSAccount/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './account';
export * from './signer';
129 changes: 129 additions & 0 deletions packages/kms-account/src/KMSAccount/signer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import type { KMSClientConfig } from '@aws-sdk/client-kms';
import {
KMSClient,
GetPublicKeyCommand,
SignCommand,
} from '@aws-sdk/client-kms';
import { secp256k1 } from '@noble/curves/secp256k1';
import * as asn1js from 'asn1js';
import type { BytesLike } from 'fuels';
import { arrayify, concat, hash, hexlify, Signer, toBytes } from 'fuels';

type Signature = {
s: bigint;
r: bigint;
recoveryParam?: number;
};

export class KMSSigner {
private kmsClient: KMSClient;
private kmsKeyId: string;

// Public
address: string;
publicKey: string;

constructor(kmsClient: KMSClient, kmsKeyId: string, publicKey: string) {
this.kmsClient = kmsClient;
this.kmsKeyId = kmsKeyId;
this.publicKey = publicKey;
this.address = hash(publicKey);
}

static async create(kmsKeyId: string, kmsClientConfig: KMSClientConfig) {
const kmsClient = new KMSClient(kmsClientConfig);
const command = new GetPublicKeyCommand({ KeyId: kmsKeyId });
const response = await kmsClient.send(command);
if (!response.PublicKey) {
throw new Error(
'Error when getting public key from KMS response undefined',
);
}
const publicKey = KMSSigner.publicKeyFromAsn1(response.PublicKey);

return new KMSSigner(kmsClient, kmsKeyId, publicKey);
}

static publicKeyFromAsn1(buf: Uint8Array): string {
const { result } = asn1js.fromBER(buf);
const values = (result as asn1js.Sequence).valueBlock.value;
const value = values[1] as asn1js.BitString;
const valueBuffer = Buffer.from(value.valueBlock.valueHex);
return hexlify(valueBuffer.slice(1));
}

static recoverPublicKeyFromSignature(
msgHash: Uint8Array,
signature: Signature,
): string {
const sig = new secp256k1.Signature(
signature.r,
signature.s,
).addRecoveryBit(signature.recoveryParam || 0);
const publicKey = sig
.recoverPublicKey(arrayify(msgHash))
.toRawBytes(false)
.slice(1);
return hexlify(publicKey);
}

static recoverPublicKey(signature: Uint8Array, msgHash: Uint8Array): string {
return Signer.recoverPublicKey(msgHash, signature);
}

findRecovery(digest: Uint8Array, signature: Signature): number {
const address = KMSSigner.recoverPublicKeyFromSignature(digest, signature);
const address1 = KMSSigner.recoverPublicKeyFromSignature(digest, {
...signature,
recoveryParam: 1,
});
if (address === this.publicKey) {
return 0;
}
if (address1 === this.publicKey) {
return 1;
}
throw new Error('Failed find recovery param');
}

encodeSignature(signature: Signature, digest: Uint8Array): string {
const maxPointS = BigInt(
'0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141',
);
const halfPointS = maxPointS / 2n;
// According to EIP2 https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
// if s < half the curve we need to invert it
// s = curve.n - s
if (signature.s > halfPointS) {
signature.s = maxPointS - signature.s;
}
const recovery = this.findRecovery(digest, signature);
const r = toBytes(`0x${signature.r.toString(16)}`, 32);
const s = toBytes(`0x${signature.s.toString(16)}`, 32);

// add recoveryParam to first s byte
s[0] |= (recovery << 7) | (s[0] & 0x7f);

return hexlify(concat([r, s]));
}

async sign(digest: BytesLike): Promise<string> {
const Message = arrayify(digest);
const commandSign = new SignCommand({
KeyId: this.kmsKeyId,
Message,
SigningAlgorithm: 'ECDSA_SHA_256',
MessageType: 'DIGEST',
});
const responseSign = await this.kmsClient.send(commandSign);

if (!responseSign.Signature) {
throw new Error(
'Error when getting signature from KMS response undefined',
);
}
const signature = secp256k1.Signature.fromDER(responseSign.Signature);

return this.encodeSignature(signature, Message);
}
}
1 change: 1 addition & 0 deletions packages/kms-account/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './KMSAccount';
Loading
Loading