Skip to content

Commit

Permalink
WIP: checks nft id in hardware serial proofs
Browse files Browse the repository at this point in the history
  • Loading branch information
jim-toth committed Jul 23, 2024
1 parent 4fec844 commit 73c3752
Show file tree
Hide file tree
Showing 8 changed files with 591 additions and 390 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ Entity-Type: <string with the type of entities stored in the datafile>
}
```

## CLI

### Seeding Relay Sale Data

- Seed Relay Sale Data
```bash
npm run cli -- seed relay-sale-data -d <path-to-relay-sale-data.csv>
```

- Remove Relay Sale Data
```bash
npm run cli -- seed relay-sale-data -d <path-to-relay-sale-data.csv> down
```

## Development

Expand Down
68 changes: 55 additions & 13 deletions cli/commands/seed-relay-sale-data.subcommand.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { Logger } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import fs from 'fs'
import { Model } from 'mongoose'
import { CommandRunner, Option, SubCommand } from 'nest-commander'

import { SeedLock } from './seed-lock'
import { SeedLock, SeedLockDocument } from './seed-lock'
import { RelaySaleData } from '../../src/verification/schemas/relay-sale-data'


@SubCommand({ name: 'relay-sale-data' })
export class RelaySaleDataSubCommand extends CommandRunner {
private readonly seedName = 'relay-sale-data'
private readonly logger = new Logger(RelaySaleDataSubCommand.name)

constructor(
@InjectModel(SeedLock.name)
private readonly seedLockModel: Model<SeedLock>,
Expand All @@ -26,38 +31,57 @@ export class RelaySaleDataSubCommand extends CommandRunner {
const exists = fs.existsSync(path)

if (!exists) {
console.error(`File not found: ${path}`)
this.logger.error(`File not found: ${path}`)
process.exit(1)
}

return path
}

async run(params: string[], options: { data: string }): Promise<void> {
const seedName = 'relay-sale-data'
const existingLock = await this.seedLockModel.findOne({ seedName })
async run(
params: string[],
options: { data: string }
): Promise<void> {
const existingLock = await this.seedLockModel.findOne({
seedName: this.seedName
})

if (params.includes('down')) {
return this.down(existingLock)
} else {
return this.up(existingLock, options.data)
}
}

private async up(
existingLock: SeedLockDocument | null,
dataFilePath: string
) {
if (existingLock) {
console.log(
`Found existing seed lock for ${seedName}`,
this.logger.log(
`Found existing seed lock for ${this.seedName}`,
existingLock.toObject()
)

return
}

const saleDataCsv = fs.readFileSync(options.data).toString('utf-8')
const saleDataCsv = fs.readFileSync(dataFilePath).toString('utf-8')
const saleDataLines = saleDataCsv.split('\r\n')

const seedLock = await this.seedLockModel.create<SeedLock>({ seedName })
const seedLock = await this.seedLockModel.create<SeedLock>({
seedName: this.seedName
})

const session = await this.relaySaleDataModel.startSession()
session.startTransaction()

console.log(`Clearing existing ${seedName} data`)
this.logger.log(`Clearing existing ${this.seedName} data`)
await this.relaySaleDataModel.deleteMany()

console.log(`Seeding ${saleDataLines.length - 1} documents.`)
this.logger.log(
`Seeding ${saleDataLines.length - 1} ${this.seedName} documents.`
)
for (let i = 1; i < saleDataLines.length; i++) {
const [ serial, unparsedNftId ] = saleDataLines[i].split(',')
const parsedNftId = Number.parseInt(unparsedNftId)
Expand All @@ -72,8 +96,26 @@ export class RelaySaleDataSubCommand extends CommandRunner {
seedLock.finishedAt = Date.now()
await seedLock.save()

console.log(
`Done seeding ${saleDataLines.length - 1} ${seedName} documents.`
this.logger.log(
`Done seeding ${saleDataLines.length - 1} ${this.seedName} documents.`
)
}

private async down(existingLock: SeedLockDocument | null) {
if (!existingLock) {
this.logger.log(`No seed lock found for ${this.seedName}, nothing to remove`)

return
}

this.logger.log(
`Removing existing seed lock for ${this.seedName}`,
existingLock
)
await existingLock.deleteOne()

this.logger.log(`Removing existing ${this.seedName} seed data`)
const result = await this.relaySaleDataModel.deleteMany()
this.logger.log(`Removed ${result.deletedCount}`)
}
}
46 changes: 24 additions & 22 deletions src/validation/schemas/validated-relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,29 @@ import { HydratedDocument } from 'mongoose'

export type ValidatedRelayDocument = HydratedDocument<ValidatedRelay>

export type RelayHardwareInfo = {
id?: string
company?: string
format?: string
wallet?: string
fingerprint?: string
nftid?: string
build?: string
flags?: string
serNums?: {
type?: string
number?: string
}[]
pubKeys?: {
type?: string
number?: string
}[]
certs?: {
type?: string
signature?: string
}[]
}

@Schema()
export class ValidatedRelay {
@Prop({ type: String, required: true })
Expand Down Expand Up @@ -36,28 +59,7 @@ export class ValidatedRelay {
nickname?: string

@Prop({ type: Object, required: false })
hardware_info?: {
id?: string
company?: string
format?: string
wallet?: string
fingerprint?: string
nftid?: string
build?: string
flags?: string
serNums?: {
type?: string
number?: string
}[]
pubKeys?: {
type?: string
number?: string
}[]
certs?: {
type?: string
signature?: string
}[]
}
hardware_info?: RelayHardwareInfo
}

export const ValidatedRelaySchema = SchemaFactory.createForClass(ValidatedRelay)
89 changes: 89 additions & 0 deletions src/verification/hardware-verification.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Test, TestingModule } from '@nestjs/testing'
import { ConfigModule } from '@nestjs/config'
import { MongooseModule } from '@nestjs/mongoose'

import { HardwareVerificationService } from './hardware-verification.service'
import {
VerifiedHardware,
VerifiedHardwareSchema
} from './schemas/verified-hardware'
import { RelaySaleData, RelaySaleDataSchema } from './schemas/relay-sale-data'

describe('HardwareVerificationService', () => {
let module: TestingModule
let service: HardwareVerificationService

beforeEach(async () => {
const dbName = 'validator-hardware-verification-service-tests'

module = await Test.createTestingModule({
imports: [
ConfigModule.forRoot(),
MongooseModule.forRoot(`mongodb://localhost/${dbName}`),
MongooseModule.forFeature([
{ name: VerifiedHardware.name, schema: VerifiedHardwareSchema },
{ name: RelaySaleData.name, schema: RelaySaleDataSchema },
]),
],
providers: [HardwareVerificationService],
}).compile()

service = module.get<HardwareVerificationService>(HardwareVerificationService)
})

afterEach(async () => {
await module.close()
})

it('should be defined', () => {
expect(service).toBeDefined()
})

it('should check owner of valid nft id', async () => {
const address = '0xe96caef5e3b4d6b3F810679637FFe95D21dEFa5B'
const nftId = BigInt(621)

const isOwnerOfRelayupNft = await service.isOwnerOfRelayupNft(
address,
nftId
)

expect(isOwnerOfRelayupNft).toBe(true)
})

it('should check owner of invalid nft id', async () => {
const address = '0xe96caef5e3b4d6b3F810679637FFe95D21dEFa5B'
const nftId = BigInt(999)

const isOwnerOfRelayupNft = await service.isOwnerOfRelayupNft(
address,
nftId
)

expect(isOwnerOfRelayupNft).toBe(false)
})

it('should validate hardware serial proofs', async () => {
const nodeId = 'relay'
const nftId = 0
const deviceSerial = 'c2eeefaa42a50073'
const atecSerial = '01237da6e721fcee01'
const fingerprint = '6CF7AA4F7C8DABCF523DC1484020906C0E0F7A9C'
const address = '01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF02'
const publicKey = '8ac7f77ca08a2402424608694e76cf9a126351cf62b27204c96b0d5d71887634240bf6a034d08c54dd7ea66c46cec9b97bf9861931bd3e69c2eac899551a66cb'
const signature = 'e84dad1da3bbc25e60d3e54676ad1610172a2239bb571db9031dd8ca1973c4bab68b23f9a94ecab9396433499333963889f4ebcce79e3f219dab93956b4719ef'

const result = await service.verifyRelaySerialProof(
nodeId,
nftId,
deviceSerial,
atecSerial,
fingerprint,
address,
publicKey,
signature
)

expect(result).toBe(true)
})
})
Loading

0 comments on commit 73c3752

Please sign in to comment.