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

TypedData & Raw Signing #200

Merged
merged 2 commits into from
Mar 28, 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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ArgumentsHost, HttpStatus } from '@nestjs/common'
import { ArgumentsHost, HttpStatus, Logger } from '@nestjs/common'
import { HttpArgumentsHost } from '@nestjs/common/interfaces'
import { ConfigService } from '@nestjs/config'
import { Response } from 'express'
Expand Down Expand Up @@ -46,6 +46,15 @@ describe(ApplicationExceptionFilter.name, () => {
})

describe('catch', () => {
// Silence the logger in these tests so we don't spam our console w/ errors that are "expected"
beforeAll(() => {
Logger.overrideLogger([])
})

afterAll(() => {
Logger.overrideLogger(new Logger())
})

describe('when environment is production', () => {
it('responds with exception status and short message', () => {
const filter = new ApplicationExceptionFilter(buildConfigServiceMock(Env.PRODUCTION))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { Action, Request } from '@narval/policy-engine-shared'
import { Action, Eip712TypedData, Request } from '@narval/policy-engine-shared'
import { Jwk, Secp256k1PublicKey, secp256k1PrivateKeyToJwk, verifySepc256k1 } from '@narval/signature'
import { Test } from '@nestjs/testing'
import {
Hex,
TransactionSerializable,
bytesToHex,
hexToBigInt,
parseTransaction,
serializeTransaction,
stringToBytes,
toHex,
verifyMessage
verifyMessage,
verifyTypedData
} from 'viem'
import { Wallet } from '../../../../../shared/type/domain.type'
import { WalletRepository } from '../../../../persistence/repository/wallet.repository'
Expand All @@ -21,6 +25,7 @@ describe('SigningService', () => {
address: '0x2c4895215973CbBd778C32c456C074b99daF8Bf1',
privateKey: '0x7cfef3303797cbc7515d9ce22ffe849c701b0f2812f999b0847229c47951fca5'
}
const privateKey: Jwk = secp256k1PrivateKeyToJwk(wallet.privateKey)

beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
Expand Down Expand Up @@ -139,5 +144,93 @@ describe('SigningService', () => {
expect(result).toEqual(expectedSignature)
expect(isVerified).toEqual(true)
})

it('signs EIP712 Typed Data', async () => {
const typedData: Eip712TypedData = {
domain: {
chainId: 137,
name: 'Crypto Unicorns Authentication',
version: '1'
},
message: {
contents: 'UNICOOOORN :)',
wallet: '0xdd4d43575a5eff17ec814da6ea810a0cc39ff23e',
nonce: '0e01c9bd-94a0-4ba1-925d-ab02688e65de'
},
primaryType: 'Validator',
types: {
EIP712Domain: [
{
name: 'name',
type: 'string'
},
{
name: 'version',
type: 'string'
},
{
name: 'chainId',
type: 'uint256'
}
],
Validator: [
{
name: 'contents',
type: 'string'
},
{
name: 'wallet',
type: 'address'
},
{
name: 'nonce',
type: 'string'
}
]
}
}
const tenantId = 'tenantId'
const typedDataRequest: Request = {
action: Action.SIGN_TYPED_DATA,
nonce: 'random-nonce-111',
resourceId: 'eip155:eoa:0x2c4895215973CbBd778C32c456C074b99daF8Bf1',
typedData
}

const expectedSignature =
'0x1f6b8ebbd066c5a849e37fc890c1f2f1b6b0a91e3dd3e8279c646948e8f14b030a13a532fd04c6b5d92e11e008558b0b60b6d061c8f34483af7deab0591317da1b'

// Call the sign method
const result = await signingService.sign(tenantId, typedDataRequest)

const isVerified = await verifyTypedData({
address: wallet.address,
signature: result,
...typedData
})

// Assert the result
expect(isVerified).toEqual(true)
expect(result).toEqual(expectedSignature)
})

it('signs raw payload', async () => {
const stringMessage = 'My ASCII message'
const byteMessage = stringToBytes(stringMessage)
const hexMessage = bytesToHex(byteMessage)

const tenantId = 'tenantId'
const rawRequest: Request = {
action: Action.SIGN_RAW,
nonce: 'random-nonce-111',
rawMessage: hexMessage,
resourceId: 'eip155:eoa:0x2c4895215973CbBd778C32c456C074b99daF8Bf1'
}

const result = await signingService.sign(tenantId, rawRequest)

const isVerified = await verifySepc256k1(result, byteMessage, privateKey as Secp256k1PublicKey)
expect(isVerified).toEqual(true)
})
})
})
72 changes: 52 additions & 20 deletions apps/vault/src/vault/core/service/signing.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { Action, Hex, Request, SignMessageAction, SignTransactionAction } from '@narval/policy-engine-shared'
import {
Action,
Hex,
Request,
SignMessageAction,
SignRawAction,
SignTransactionAction,
SignTypedDataAction
} from '@narval/policy-engine-shared'
import { signSecp256k1 } from '@narval/signature'
import { HttpStatus, Injectable } from '@nestjs/common'
import {
TransactionRequest,
checksumAddress,
createWalletClient,
extractChain,
hexToBigInt,
hexToBytes,
http,
signatureToHex,
transactionType
} from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
Expand All @@ -23,13 +34,16 @@ export class SigningService {
return this.signTransaction(tenantId, request)
} else if (request.action === Action.SIGN_MESSAGE) {
return this.signMessage(tenantId, request)
} else if (request.action === Action.SIGN_TYPED_DATA) {
return this.signTypedData(tenantId, request)
} else if (request.action === Action.SIGN_RAW) {
return this.signRaw(tenantId, request)
}

throw new Error('Action not supported')
}

async signTransaction(tenantId: string, action: SignTransactionAction): Promise<Hex> {
const { transactionRequest, resourceId } = action
async #getWallet(tenantId: string, resourceId: string) {
const wallet = await this.walletRepository.findById(tenantId, resourceId)
if (!wallet) {
throw new ApplicationException({
Expand All @@ -39,10 +53,16 @@ export class SigningService {
})
}

return wallet
}

async #buildClient(tenantId: string, resourceId: string, chainId?: number) {
const wallet = await this.#getWallet(tenantId, resourceId)

const account = privateKeyToAccount(wallet.privateKey)
const chain = extractChain<chains.Chain[], number>({
chains: Object.values(chains),
id: transactionRequest.chainId
id: chainId || 1
})

const client = createWalletClient({
Expand All @@ -51,8 +71,15 @@ export class SigningService {
transport: http('') // clear the RPC so we don't call any chain stuff here.
})

return client
}

async signTransaction(tenantId: string, action: SignTransactionAction): Promise<Hex> {
const { transactionRequest, resourceId } = action
const client = await this.#buildClient(tenantId, resourceId, transactionRequest.chainId)

const txRequest: TransactionRequest = {
from: checksumAddress(account.address),
from: checksumAddress(client.account.address),
to: transactionRequest.to,
nonce: transactionRequest.nonce,
data: transactionRequest.data,
Expand Down Expand Up @@ -83,24 +110,29 @@ export class SigningService {

async signMessage(tenantId: string, action: SignMessageAction): Promise<Hex> {
const { message, resourceId } = action
const wallet = await this.walletRepository.findById(tenantId, resourceId)
if (!wallet) {
throw new ApplicationException({
message: 'Wallet not found',
suggestedHttpStatusCode: HttpStatus.BAD_REQUEST,
context: { clientId: tenantId, resourceId }
})
}
const client = await this.#buildClient(tenantId, resourceId)

const account = privateKeyToAccount(wallet.privateKey)
const signature = await client.signMessage({ message })
return signature
}

const client = createWalletClient({
account,
chain: chains.mainnet,
transport: http('') // clear the RPC so we don't call any chain stuff here.
})
async signTypedData(tenantId: string, action: SignTypedDataAction): Promise<Hex> {
const { typedData, resourceId } = action
const client = await this.#buildClient(tenantId, resourceId)

const signature = await client.signMessage({ message })
const signature = await client.signTypedData(typedData)
return signature
}

// Sign a raw message; nothing ETH or chain-specific, simply performs an ecdsa signature on the byte representation of the hex-encoded raw message
async signRaw(tenantId: string, action: SignRawAction): Promise<Hex> {
const { rawMessage, resourceId } = action

const wallet = await this.#getWallet(tenantId, resourceId)
const message = hexToBytes(rawMessage)
const signature = await signSecp256k1(message, wallet.privateKey, true)

const hexSignature = signatureToHex(signature)
return hexSignature
}
}
15 changes: 8 additions & 7 deletions apps/vault/src/vault/http/rest/controller/sign.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@ import { Request } from '@narval/policy-engine-shared'
import { Body, Controller, Post, UseGuards } from '@nestjs/common'
import { createZodDto } from 'nestjs-zod'
import {
SignMessageActionSchema,
SignTransactionActionSchema,
SignTypedDataActionSchema
} from 'packages/policy-engine-shared/src/lib/schema/action.schema'
SignMessageAction,
SignRawAction,
SignTransactionAction,
SignTypedDataAction
} from 'packages/policy-engine-shared/src/lib/type/action.type'
import { z } from 'zod'
import { ClientId } from '../../../../shared/decorator/client-id.decorator'
import { AuthorizationGuard } from '../../../../shared/guard/authorization.guard'
import { SigningService } from '../../../core/service/signing.service'

const SignRequestSchema = z.object({
request: z.union([SignTransactionActionSchema, SignMessageActionSchema, SignTypedDataActionSchema])
const SignRequest = z.object({
request: z.union([SignTransactionAction, SignMessageAction, SignTypedDataAction, SignRawAction])
})

class SignRequestDto extends createZodDto(SignRequestSchema) {}
class SignRequestDto extends createZodDto(SignRequest) {}
@Controller('/sign')
@UseGuards(AuthorizationGuard)
export class SignController {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { toHex } from 'viem'
import { Action, SignTypedDataAction } from '../../type/action.type'

describe('SignTypedDataAction', () => {
const typedData = {
domain: {
name: 'Ether Mail',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC'
},
types: {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' }
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'contents', type: 'string' }
]
},
primaryType: 'Mail',
message: {
from: {
name: 'Cow',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826'
},
to: {
name: 'Bob',
wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'
},
contents: 'Hello, Bob!'
}
}

it('should validate a valid SignTypedDataAction object', () => {
const validAction = {
action: Action.SIGN_TYPED_DATA,
nonce: 'xxx',
resourceId: 'resourceId',
typedData
}

const result = SignTypedDataAction.safeParse(validAction)

expect(result).toEqual({
success: true,
data: expect.any(Object)
})
})

it('should validate a valid typedData as a string', () => {
const validAction = {
action: Action.SIGN_TYPED_DATA,
nonce: 'xxx',
resourceId: 'resourceId',
typedData: JSON.stringify(typedData)
}

const result = SignTypedDataAction.safeParse(validAction)

expect(result.success).toEqual(true)
})

it('should validate a valid typedData as a hex-encoded stringified json object', () => {
const validAction = {
action: Action.SIGN_TYPED_DATA,
nonce: 'xxx',
resourceId: 'resourceId',
typedData: toHex(JSON.stringify(typedData))
}

const result = SignTypedDataAction.safeParse(validAction)

expect(result.success).toEqual(true)
})

it('should not validate an invalid SignTypedDataAction object with invalid JSON string', () => {
const invalidAction = {
action: Action.SIGN_TYPED_DATA,
nonce: 'xxx',
resourceId: 'resourceId',
typedData: 'invalidJSON'
}

const result = SignTypedDataAction.safeParse(invalidAction)

expect(result.success).toEqual(false)
})
})
Loading
Loading