Merge pull request #3199 from gradido/iota6_protobuf_models

feat(dlt): protobuf entities for blockchain protocol
This commit is contained in:
einhornimmond 2023-09-27 08:42:05 +02:00 committed by GitHub
commit a2f9604213
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 1430 additions and 661 deletions

View File

@ -78,27 +78,34 @@ export class DltConnectorClient {
* transmit transaction via dlt-connector to iota
* and update dltTransactionId of transaction in db with iota message id
*/
public async transmitTransaction(transaction?: DbTransaction | null): Promise<string> {
if (transaction) {
const typeString = getTransactionTypeString(transaction.typeId)
const secondsSinceEpoch = Math.round(transaction.balanceDate.getTime() / 1000)
const amountString = transaction.amount.toString()
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { data } = await this.client.rawRequest(sendTransaction, {
input: {
type: typeString,
amount: amountString,
createdAt: secondsSinceEpoch,
public async transmitTransaction(
transaction: DbTransaction,
senderCommunityUuid?: string,
recipientCommunityUuid?: string,
): Promise<string> {
const typeString = getTransactionTypeString(transaction.typeId)
const amountString = transaction.amount.toString()
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { data } = await this.client.rawRequest(sendTransaction, {
input: {
senderUser: {
uuid: transaction.userGradidoID,
communityUuid: senderCommunityUuid,
},
})
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return data.sendTransaction.dltTransactionIdHex
} catch (e) {
throw new LogError('Error send sending transaction to dlt-connector: ', e)
}
} else {
throw new LogError('parameter transaction not set...')
recipientUser: {
uuid: transaction.linkedUserGradidoID,
communityUuid: recipientCommunityUuid,
},
amount: amountString,
type: typeString,
createdAt: transaction.balanceDate.toString(),
},
})
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return data.sendTransaction.dltTransactionIdHex
} catch (e) {
throw new LogError('Error send sending transaction to dlt-connector: ', e)
}
}
}

View File

@ -6,6 +6,7 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Connection } from '@dbTools/typeorm'
import { Community } from '@entity/Community'
import { DltTransaction } from '@entity/DltTransaction'
import { Transaction } from '@entity/Transaction'
import { ApolloServerTestClient } from 'apollo-server-testing'
@ -14,6 +15,7 @@ import { Decimal } from 'decimal.js-light'
// import { Response } from 'graphql-request/dist/types'
import { GraphQLClient } from 'graphql-request'
import { Response } from 'graphql-request/dist/types'
import { v4 as uuidv4 } from 'uuid'
import { testEnvironment, cleanDB } from '@test/helpers'
import { logger, i18n as localization } from '@test/testSetup'
@ -80,6 +82,16 @@ let testEnv: {
}
*/
async function createHomeCommunity(): Promise<Community> {
const homeCommunity = Community.create()
homeCommunity.foreign = false
homeCommunity.communityUuid = uuidv4()
homeCommunity.url = 'localhost'
homeCommunity.publicKey = Buffer.from('0x6e6a6c6d6feffe', 'hex')
await Community.save(homeCommunity)
return homeCommunity
}
async function createTxCREATION1(verified: boolean): Promise<Transaction> {
let tx = Transaction.create()
tx.amount = new Decimal(1000)
@ -358,6 +370,7 @@ describe('create and send Transactions to DltConnector', () => {
txCREATION1 = await createTxCREATION1(false)
txCREATION2 = await createTxCREATION2(false)
txCREATION3 = await createTxCREATION3(false)
await createHomeCommunity()
CONFIG.DLT_CONNECTOR = false
await sendTransactionsToDltConnector()
@ -413,6 +426,7 @@ describe('create and send Transactions to DltConnector', () => {
txCREATION1 = await createTxCREATION1(false)
txCREATION2 = await createTxCREATION2(false)
txCREATION3 = await createTxCREATION3(false)
await createHomeCommunity()
CONFIG.DLT_CONNECTOR = true
@ -481,6 +495,7 @@ describe('create and send Transactions to DltConnector', () => {
txCREATION1 = await createTxCREATION1(true)
txCREATION2 = await createTxCREATION2(true)
txCREATION3 = await createTxCREATION3(true)
await createHomeCommunity()
txSEND1to2 = await createTxSend1ToReceive2(false)
txRECEIVE2From1 = await createTxReceive2FromSend1(false)

View File

@ -1,4 +1,5 @@
import { IsNull } from '@dbTools/typeorm'
import { Community } from '@entity/Community'
import { DltTransaction } from '@entity/DltTransaction'
import { Transaction } from '@entity/Transaction'
@ -16,6 +17,13 @@ export async function sendTransactionsToDltConnector(): Promise<void> {
try {
await createDltTransactions()
const dltConnector = DltConnectorClient.getInstance()
// TODO: get actual communities from users
const homeCommunity = await Community.findOneOrFail({ where: { foreign: false } })
const senderCommunityUuid = homeCommunity.communityUuid
if (!senderCommunityUuid) {
throw new Error('Cannot find community uuid of home community')
}
const recipientCommunityUuid = ''
if (dltConnector) {
logger.debug('with sending to DltConnector...')
const dltTransactions = await DltTransaction.find({
@ -23,9 +31,17 @@ export async function sendTransactionsToDltConnector(): Promise<void> {
relations: ['transaction'],
order: { createdAt: 'ASC', id: 'ASC' },
})
for (const dltTx of dltTransactions) {
if (!dltTx.transaction) {
continue
}
try {
const messageId = await dltConnector.transmitTransaction(dltTx.transaction)
const messageId = await dltConnector.transmitTransaction(
dltTx.transaction,
senderCommunityUuid,
recipientCommunityUuid,
)
const dltMessageId = Buffer.from(messageId, 'hex')
if (dltMessageId.length !== 32) {
logger.error(

View File

@ -9,4 +9,4 @@ IOTA_API_URL=https://chrysalis-nodes.iota.org
IOTA_COMMUNITY_ALIAS=GRADIDO: TestHelloWelt2
# DLT-Connector
DLT_CONNECTOR_PORT=6000
DLT_CONNECTOR_PORT=6010

View File

@ -16,7 +16,7 @@ ENV BUILD_COMMIT="0000000"
## SET NODE_ENV
ENV NODE_ENV="production"
## App relevant Envs
ENV PORT="6000"
ENV PORT="6010"
# Labels
LABEL org.label-schema.build-date="${BUILD_DATE}"

View File

@ -6,7 +6,7 @@ module.exports = {
collectCoverageFrom: ['src/**/*.ts', '!**/node_modules/**', '!src/seeds/**', '!build/**'],
coverageThreshold: {
global: {
lines: 63,
lines: 77,
},
},
setupFiles: ['<rootDir>/test/testSetup.ts'],
@ -14,6 +14,8 @@ module.exports = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
moduleNameMapper: {
'@/(.*)': '<rootDir>/src/$1',
'@arg/(.*)': '<rootDir>/src/graphql/arg/$1',
'@controller/(.*)': '<rootDir>/src/controller/$1',
'@enum/(.*)': '<rootDir>/src/graphql/enum/$1',
'@resolver/(.*)': '<rootDir>/src/graphql/resolver/$1',
'@input/(.*)': '<rootDir>/src/graphql/input/$1',
@ -30,6 +32,7 @@ module.exports = {
process.env.NODE_ENV === 'development'
? '<rootDir>/../database/src/$1'
: '<rootDir>/../database/build/src/$1',
'@validator/(.*)': '<rootDir>/src/graphql/validator/$1',
},
}
/*

View File

@ -23,7 +23,7 @@ const iota = {
}
const dltConnector = {
DLT_CONNECTOR_PORT: process.env.DLT_CONNECTOR_PORT || 6000,
DLT_CONNECTOR_PORT: process.env.DLT_CONNECTOR_PORT || 6010,
}
// Check config version

View File

@ -0,0 +1,10 @@
import { GradidoTransaction } from '@/proto/3_3/GradidoTransaction'
import { TransactionBody } from '@/proto/3_3/TransactionBody'
export const create = (body: TransactionBody): GradidoTransaction => {
const transaction = new GradidoTransaction({
bodyBytes: Buffer.from(TransactionBody.encode(body).finish()),
})
// TODO: add correct signature(s)
return transaction
}

View File

@ -0,0 +1,6 @@
import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel'
export abstract class TransactionBase {
// validate if transaction is valid, maybe expensive because depending on level several transactions will be fetched from db
public abstract validate(level: TransactionValidationLevel): boolean
}

View File

@ -0,0 +1,162 @@
import 'reflect-metadata'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
import { create, determineCrossGroupType, determineOtherGroup } from './TransactionBody'
import { UserIdentifier } from '@/graphql/input/UserIdentifier'
import { TransactionError } from '@/graphql/model/TransactionError'
import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType'
import { CrossGroupType } from '@/graphql/enum/CrossGroupType'
import { TransactionType } from '@/graphql/enum/TransactionType'
import Decimal from 'decimal.js-light'
describe('test controller/TransactionBody', () => {
describe('test create ', () => {
const senderUser = new UserIdentifier()
const recipientUser = new UserIdentifier()
it('test with contribution transaction', () => {
const transactionDraft = new TransactionDraft()
transactionDraft.senderUser = senderUser
transactionDraft.recipientUser = recipientUser
transactionDraft.type = TransactionType.CREATION
transactionDraft.amount = new Decimal(1000)
transactionDraft.createdAt = '2022-01-02T19:10:34.121'
transactionDraft.targetDate = '2021-12-01T10:05:00.191'
const body = create(transactionDraft)
expect(body.creation).toBeDefined()
expect(body).toMatchObject({
createdAt: {
seconds: 1641150634,
nanoSeconds: 121000000,
},
versionNumber: '3.3',
type: CrossGroupType.LOCAL,
otherGroup: '',
creation: {
recipient: {
amount: '1000',
},
targetDate: {
seconds: 1638353100,
},
},
})
})
it('test with local send transaction send part', () => {
const transactionDraft = new TransactionDraft()
transactionDraft.senderUser = senderUser
transactionDraft.recipientUser = recipientUser
transactionDraft.type = TransactionType.SEND
transactionDraft.amount = new Decimal(1000)
transactionDraft.createdAt = '2022-01-02T19:10:34.121'
const body = create(transactionDraft)
expect(body.transfer).toBeDefined()
expect(body).toMatchObject({
createdAt: {
seconds: 1641150634,
nanoSeconds: 121000000,
},
versionNumber: '3.3',
type: CrossGroupType.LOCAL,
otherGroup: '',
transfer: {
sender: {
amount: '1000',
},
},
})
})
it('test with local send transaction receive part', () => {
const transactionDraft = new TransactionDraft()
transactionDraft.senderUser = senderUser
transactionDraft.recipientUser = recipientUser
transactionDraft.type = TransactionType.RECEIVE
transactionDraft.amount = new Decimal(1000)
transactionDraft.createdAt = '2022-01-02T19:10:34.121'
const body = create(transactionDraft)
expect(body.transfer).toBeDefined()
expect(body).toMatchObject({
createdAt: {
seconds: 1641150634,
nanoSeconds: 121000000,
},
versionNumber: '3.3',
type: CrossGroupType.LOCAL,
otherGroup: '',
transfer: {
sender: {
amount: '1000',
},
},
})
})
})
describe('test determineCrossGroupType', () => {
const transactionDraft = new TransactionDraft()
transactionDraft.senderUser = new UserIdentifier()
transactionDraft.recipientUser = new UserIdentifier()
it('local transaction', () => {
expect(determineCrossGroupType(transactionDraft)).toEqual(CrossGroupType.LOCAL)
})
it('test with with invalid input', () => {
transactionDraft.recipientUser.communityUuid = 'a72a4a4a-aa12-4f6c-b3d8-7cc65c67e24a'
expect(() => determineCrossGroupType(transactionDraft)).toThrow(
new TransactionError(
TransactionErrorType.NOT_IMPLEMENTED_YET,
'cannot determine CrossGroupType',
),
)
})
it('inbound transaction (send to sender community)', () => {
transactionDraft.type = TransactionType.SEND
expect(determineCrossGroupType(transactionDraft)).toEqual(CrossGroupType.INBOUND)
})
it('outbound transaction (send to recipient community)', () => {
transactionDraft.type = TransactionType.RECEIVE
expect(determineCrossGroupType(transactionDraft)).toEqual(CrossGroupType.OUTBOUND)
})
})
describe('test determineOtherGroup', () => {
const transactionDraft = new TransactionDraft()
transactionDraft.senderUser = new UserIdentifier()
transactionDraft.recipientUser = new UserIdentifier()
it('for inbound transaction, other group is from recipient, missing community id for recipient', () => {
expect(() => determineOtherGroup(CrossGroupType.INBOUND, transactionDraft)).toThrowError(
new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing recipient user community id for cross group transaction',
),
)
})
it('for inbound transaction, other group is from recipient', () => {
transactionDraft.recipientUser.communityUuid = 'b8e9f00a-5a56-4b23-8c44-6823ac9e0d2d'
expect(determineOtherGroup(CrossGroupType.INBOUND, transactionDraft)).toEqual(
'b8e9f00a-5a56-4b23-8c44-6823ac9e0d2d',
)
})
it('for outbound transaction, other group is from sender, missing community id for sender', () => {
expect(() => determineOtherGroup(CrossGroupType.OUTBOUND, transactionDraft)).toThrowError(
new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing sender user community id for cross group transaction',
),
)
})
it('for outbound transaction, other group is from sender', () => {
transactionDraft.senderUser.communityUuid = 'a72a4a4a-aa12-4f6c-b3d8-7cc65c67e24a'
expect(determineOtherGroup(CrossGroupType.OUTBOUND, transactionDraft)).toEqual(
'a72a4a4a-aa12-4f6c-b3d8-7cc65c67e24a',
)
})
})
})

View File

@ -0,0 +1,74 @@
import { CrossGroupType } from '@/graphql/enum/CrossGroupType'
import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType'
import { TransactionType } from '@/graphql/enum/TransactionType'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
import { TransactionError } from '@/graphql/model/TransactionError'
import { GradidoCreation } from '@/proto/3_3/GradidoCreation'
import { GradidoTransfer } from '@/proto/3_3/GradidoTransfer'
import { TransactionBody } from '@/proto/3_3/TransactionBody'
export const create = (transaction: TransactionDraft): TransactionBody => {
const body = new TransactionBody(transaction)
// TODO: load pubkeys for sender and recipient user from db
switch (transaction.type) {
case TransactionType.CREATION:
body.creation = new GradidoCreation(transaction)
body.data = 'gradidoCreation'
break
case TransactionType.SEND:
case TransactionType.RECEIVE:
body.transfer = new GradidoTransfer(transaction)
body.data = 'gradidoTransfer'
break
}
return body
}
export const determineCrossGroupType = ({
senderUser,
recipientUser,
type,
}: TransactionDraft): CrossGroupType => {
if (
!recipientUser.communityUuid ||
recipientUser.communityUuid === '' ||
senderUser.communityUuid === recipientUser.communityUuid ||
type === TransactionType.CREATION
) {
return CrossGroupType.LOCAL
} else if (type === TransactionType.SEND) {
return CrossGroupType.INBOUND
} else if (type === TransactionType.RECEIVE) {
return CrossGroupType.OUTBOUND
}
throw new TransactionError(
TransactionErrorType.NOT_IMPLEMENTED_YET,
'cannot determine CrossGroupType',
)
}
export const determineOtherGroup = (
type: CrossGroupType,
{ senderUser, recipientUser }: TransactionDraft,
): string => {
switch (type) {
case CrossGroupType.LOCAL:
return ''
case CrossGroupType.INBOUND:
if (!recipientUser.communityUuid) {
throw new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing recipient user community id for cross group transaction',
)
}
return recipientUser.communityUuid
case CrossGroupType.OUTBOUND:
if (!senderUser.communityUuid) {
throw new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing sender user community id for cross group transaction',
)
}
return senderUser.communityUuid
}
}

View File

@ -0,0 +1,9 @@
export enum AddressType {
NONE = 0, // if no address was found
COMMUNITY_HUMAN = 1, // creation account for human
COMMUNITY_GMW = 2, // community public budget account
COMMUNITY_AUF = 3, // community compensation and environment founds account
COMMUNITY_PROJECT = 4, // no creations allowed
SUBACCOUNT = 5, // no creations allowed
CRYPTO_ACCOUNT = 6, // user control his keys, no creations
}

View File

@ -0,0 +1,7 @@
export enum CrossGroupType {
LOCAL = 0,
INBOUND = 1,
OUTBOUND = 2,
// for cross group transaction which haven't a direction like group friend update
// CROSS = 3,
}

View File

@ -0,0 +1,11 @@
import { registerEnumType } from 'type-graphql'
export enum TransactionErrorType {
NOT_IMPLEMENTED_YET = 'Not Implemented yet',
MISSING_PARAMETER = 'Missing parameter',
}
registerEnumType(TransactionErrorType, {
name: 'TransactionErrorType',
description: 'Transaction Error Type',
})

View File

@ -0,0 +1,15 @@
import { registerEnumType } from 'type-graphql'
export enum TransactionValidationLevel {
SINGLE = 1, // check only the transaction
SINGLE_PREVIOUS = 2, // check also with previous transaction
DATE_RANGE = 3, // check all transaction from within date range by creation automatic the same month
PAIRED = 4, // check paired transaction on another group by cross group transactions
CONNECTED_GROUP = 5, // check all transactions in the group which connected with this transaction address(es)
CONNECTED_BLOCKCHAIN = 6, // check all transactions which connected with this transaction
}
registerEnumType(TransactionValidationLevel, {
name: 'TransactionValidationLevel',
description: 'Transaction Validation Levels',
})

View File

@ -0,0 +1,39 @@
// https://www.npmjs.com/package/@apollo/protobufjs
import { Decimal } from 'decimal.js-light'
import { TransactionType } from '@enum/TransactionType'
import { InputType, Field } from 'type-graphql'
import { UserIdentifier } from './UserIdentifier'
import { isValidDateString } from '@validator/DateString'
import { IsPositiveDecimal } from '@validator/Decimal'
import { IsEnum, IsObject, ValidateNested } from 'class-validator'
@InputType()
export class TransactionDraft {
@Field(() => UserIdentifier)
@IsObject()
@ValidateNested()
senderUser: UserIdentifier
@Field(() => UserIdentifier)
@IsObject()
@ValidateNested()
recipientUser: UserIdentifier
@Field(() => Decimal)
@IsPositiveDecimal()
amount: Decimal
@Field(() => TransactionType)
@IsEnum(TransactionType)
type: TransactionType
@Field(() => String)
@isValidDateString()
createdAt: string
// only for creation transactions
@Field(() => String, { nullable: true })
@isValidDateString()
targetDate?: string
}

View File

@ -1,21 +0,0 @@
// https://www.npmjs.com/package/@apollo/protobufjs
import { Decimal } from 'decimal.js-light'
import { TransactionType } from '../enum/TransactionType'
import { InputType, Field } from 'type-graphql'
@InputType()
export class TransactionInput {
@Field(() => TransactionType)
type: TransactionType
@Field(() => Decimal)
amount: Decimal
@Field(() => Number)
createdAt: number
// @protoField.d(4, 'string')
// @Field(() => Decimal)
// communitySum: Decimal
}

View File

@ -0,0 +1,19 @@
// https://www.npmjs.com/package/@apollo/protobufjs
import { IsPositive, IsUUID } from 'class-validator'
import { Field, Int, InputType } from 'type-graphql'
@InputType()
export class UserIdentifier {
@Field(() => String)
@IsUUID('4')
uuid: string
@Field(() => String, { nullable: true })
@IsUUID('4')
communityUuid?: string
@Field(() => Int, { defaultValue: 1, nullable: true })
@IsPositive()
accountNr?: number
}

View File

@ -0,0 +1,20 @@
import { ObjectType, Field } from 'type-graphql'
import { TransactionErrorType } from '../enum/TransactionErrorType'
@ObjectType()
export class TransactionError implements Error {
constructor(type: TransactionErrorType, message: string) {
this.type = type
this.message = message
this.name = type.toString()
}
@Field(() => TransactionErrorType)
type: TransactionErrorType
@Field(() => String)
message: string
@Field(() => String)
name: string
}

View File

@ -0,0 +1,21 @@
import { ObjectType, Field } from 'type-graphql'
import { TransactionError } from './TransactionError'
@ObjectType()
export class TransactionResult {
constructor(content: TransactionError | string) {
if (content instanceof TransactionError) {
this.error = content
} else if (typeof content === 'string') {
this.messageId = content
}
}
// the error if one happened
@Field(() => TransactionError, { nullable: true })
error?: TransactionError
// if no error happend, the message id of the iota transaction
@Field(() => String, { nullable: true })
messageId?: string
}

View File

@ -2,6 +2,9 @@ import 'reflect-metadata'
import { ApolloServer } from '@apollo/server'
import { createApolloTestServer } from '@test/ApolloServerMock'
import assert from 'assert'
import { TransactionResult } from '../model/TransactionResult'
let apolloTestServer: ApolloServer
jest.mock('@/client/IotaClient', () => {
return {
@ -11,8 +14,6 @@ jest.mock('@/client/IotaClient', () => {
}
})
let apolloTestServer: ApolloServer
describe('Transaction Resolver Test', () => {
beforeAll(async () => {
apolloTestServer = await createApolloTestServer()
@ -31,30 +32,45 @@ describe('Transaction Resolver Test', () => {
})
it('test mocked sendTransaction', async () => {
const response = await apolloTestServer.executeOperation({
query: 'mutation ($input: TransactionInput!) { sendTransaction(data: $input) }',
query:
'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }',
variables: {
input: {
senderUser: {
uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65',
},
recipientUser: {
uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe',
},
type: 'SEND',
amount: '10',
createdAt: 1688992436,
createdAt: '2012-04-17T17:12:00Z',
},
},
})
assert(response.body.kind === 'single')
expect(response.body.singleResult.errors).toBeUndefined()
expect(response.body.singleResult.data?.sendTransaction).toBe(
const transactionResult = response.body.singleResult.data?.sendTransaction as TransactionResult
expect(transactionResult.messageId).toBe(
'5498130bc3918e1a7143969ce05805502417e3e1bd596d3c44d6a0adeea22710',
)
})
it('test mocked sendTransaction invalid transactionType ', async () => {
const response = await apolloTestServer.executeOperation({
query: 'mutation ($input: TransactionInput!) { sendTransaction(data: $input) }',
query:
'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }',
variables: {
input: {
senderUser: {
uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65',
},
recipientUser: {
uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe',
},
type: 'INVALID',
amount: '10',
createdAt: 1688992436,
createdAt: '2012-04-17T17:12:00Z',
},
},
})
@ -71,12 +87,19 @@ describe('Transaction Resolver Test', () => {
it('test mocked sendTransaction invalid amount ', async () => {
const response = await apolloTestServer.executeOperation({
query: 'mutation ($input: TransactionInput!) { sendTransaction(data: $input) }',
query:
'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }',
variables: {
input: {
senderUser: {
uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65',
},
recipientUser: {
uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe',
},
type: 'SEND',
amount: 'no number',
createdAt: 1688992436,
createdAt: '2012-04-17T17:12:00Z',
},
},
})
@ -93,12 +116,19 @@ describe('Transaction Resolver Test', () => {
it('test mocked sendTransaction invalid created date ', async () => {
const response = await apolloTestServer.executeOperation({
query: 'mutation ($input: TransactionInput!) { sendTransaction(data: $input) }',
query:
'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }',
variables: {
input: {
senderUser: {
uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65',
},
recipientUser: {
uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe',
},
type: 'SEND',
amount: '10',
createdAt: '2023-03-02T10:12:00',
createdAt: 'not valid',
},
},
})
@ -106,10 +136,47 @@ describe('Transaction Resolver Test', () => {
expect(response.body.singleResult).toMatchObject({
errors: [
{
message:
'Variable "$input" got invalid value "2023-03-02T10:12:00" at "input.createdAt"; Float cannot represent non numeric value: "2023-03-02T10:12:00"',
message: 'Argument Validation Error',
extensions: {
code: 'BAD_USER_INPUT',
validationErrors: [
{
value: 'not valid',
property: 'createdAt',
constraints: {
isValidDateString: 'createdAt must be a valid date string',
},
},
],
},
},
],
})
})
it('test mocked sendTransaction missing creationDate for contribution', async () => {
const response = await apolloTestServer.executeOperation({
query:
'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }',
variables: {
input: {
senderUser: {
uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65',
},
recipientUser: {
uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe',
},
type: 'CREATION',
amount: '10',
createdAt: '2012-04-17T17:12:00Z',
},
},
})
assert(response.body.kind === 'single')
expect(response.body.singleResult.data?.sendTransaction).toMatchObject({
error: {
type: 'MISSING_PARAMETER',
message: 'missing targetDate for contribution',
},
})
})
})

View File

@ -1,9 +1,14 @@
import { Resolver, Query, Arg, Mutation } from 'type-graphql'
import { TransactionInput } from '@input/TransactionInput'
import { TransactionBody } from '@proto/TransactionBody'
import { TransactionDraft } from '@input/TransactionDraft'
import { create as createTransactionBody } from '@controller/TransactionBody'
import { create as createGradidoTransaction } from '@controller/GradidoTransaction'
import { sendMessage as iotaSendMessage } from '@/client/IotaClient'
import { GradidoTransaction } from '@/proto/3_3/GradidoTransaction'
import { TransactionResult } from '../model/TransactionResult'
import { TransactionError } from '../model/TransactionError'
@Resolver()
export class TransactionResolver {
@ -18,14 +23,23 @@ export class TransactionResolver {
return '0.1'
}
@Mutation(() => String)
@Mutation(() => TransactionResult)
async sendTransaction(
@Arg('data')
transaction: TransactionInput,
): Promise<string> {
const message = TransactionBody.fromObject(transaction)
const messageBuffer = TransactionBody.encode(message).finish()
const resultMessage = await iotaSendMessage(messageBuffer)
return resultMessage.messageId
transaction: TransactionDraft,
): Promise<TransactionResult> {
try {
const body = createTransactionBody(transaction)
const message = createGradidoTransaction(body)
const messageBuffer = GradidoTransaction.encode(message).finish()
const resultMessage = await iotaSendMessage(messageBuffer)
return new TransactionResult(resultMessage.messageId)
} catch (error) {
if (error instanceof TransactionError) {
return new TransactionResult(error)
} else {
throw error
}
}
}
}

View File

@ -2,7 +2,7 @@
import { Decimal } from 'decimal.js-light'
import { GraphQLScalarType, Kind, ValueNode } from 'graphql'
export const DecimalScalar = new GraphQLScalarType<Decimal, string>({
export const DecimalScalar = new GraphQLScalarType({
name: 'Decimal',
description: 'The `Decimal` scalar type to represent currency values',

View File

@ -9,5 +9,13 @@ export const schema = async (): Promise<GraphQLSchema> => {
return buildSchema({
resolvers: [TransactionResolver],
scalarsMap: [{ type: Decimal, scalar: DecimalScalar }],
validate: {
validationError: { target: false },
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: false,
forbidUnknownValues: true,
stopAtFirstError: true,
},
})
}

View File

@ -0,0 +1,21 @@
import { registerDecorator, ValidationOptions } from 'class-validator'
export function isValidDateString(validationOptions?: ValidationOptions) {
// eslint-disable-next-line @typescript-eslint/ban-types
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isValidDateString',
target: object.constructor,
propertyName,
options: validationOptions,
validator: {
validate(value: string): boolean {
return new Date(value).toString() !== 'Invalid Date'
},
defaultMessage(): string {
return `${propertyName} must be a valid date string`
},
},
})
}
}

View File

@ -0,0 +1,22 @@
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'
import { Decimal } from 'decimal.js-light'
export function IsPositiveDecimal(validationOptions?: ValidationOptions) {
// eslint-disable-next-line @typescript-eslint/ban-types
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isPositiveDecimal',
target: object.constructor,
propertyName,
options: validationOptions,
validator: {
validate(value: Decimal): boolean {
return value.greaterThan(0)
},
defaultMessage(args: ValidationArguments): string {
return `The ${propertyName} must be a positive value ${args.property}`
},
},
})
}
}

View File

@ -0,0 +1,34 @@
import { Field, Message } from '@apollo/protobufjs'
import { GradidoTransaction } from './GradidoTransaction'
import { TimestampSeconds } from './TimestampSeconds'
/*
id will be set by Node server
running_hash will be also set by Node server,
calculated from previous transaction running_hash and this id, transaction and received
*/
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GradidoConfirmedTransaction extends Message<GradidoConfirmedTransaction> {
@Field.d(1, 'uint64')
id: number
@Field.d(2, 'GradidoTransaction')
transaction: GradidoTransaction
@Field.d(3, 'TimestampSeconds')
confirmedAt: TimestampSeconds
@Field.d(4, 'string')
versionNumber: string
@Field.d(5, 'bytes')
runningHash: Buffer
@Field.d(6, 'bytes')
messageId: Buffer
@Field.d(7, 'string')
accountBalance: string
}

View File

@ -0,0 +1,20 @@
import 'reflect-metadata'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
import { GradidoCreation } from './GradidoCreation'
import { TransactionError } from '@/graphql/model/TransactionError'
import { TransactionErrorType } from '@enum/TransactionErrorType'
describe('proto/3.3/GradidoCreation', () => {
it('test with missing targetDate', () => {
const transactionDraft = new TransactionDraft()
expect(() => {
// eslint-disable-next-line no-new
new GradidoCreation(transactionDraft)
}).toThrowError(
new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing targetDate for contribution',
),
)
})
})

View File

@ -0,0 +1,32 @@
import { Field, Message } from '@apollo/protobufjs'
import { TimestampSeconds } from './TimestampSeconds'
import { TransferAmount } from './TransferAmount'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
import { TransactionError } from '@/graphql/model/TransactionError'
import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType'
// need signature from group admin or
// percent of group users another than the receiver
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GradidoCreation extends Message<GradidoCreation> {
constructor(transaction: TransactionDraft) {
if (!transaction.targetDate) {
throw new TransactionError(
TransactionErrorType.MISSING_PARAMETER,
'missing targetDate for contribution',
)
}
super({
recipient: new TransferAmount({ amount: transaction.amount.toString() }),
targetDate: new TimestampSeconds(new Date(transaction.targetDate)),
})
}
@Field.d(1, TransferAmount)
public recipient: TransferAmount
@Field.d(3, 'TimestampSeconds')
public targetDate: TimestampSeconds
}

View File

@ -0,0 +1,31 @@
import { Field, Message } from '@apollo/protobufjs'
import { GradidoTransfer } from './GradidoTransfer'
import { TimestampSeconds } from './TimestampSeconds'
// transaction type for chargeable transactions
// for transaction for people which haven't a account already
// consider using a seed number for key pair generation for recipient
// using seed as redeem key for claiming transaction, technically make a default Transfer transaction from recipient address
// seed must be long enough to prevent brute force, maybe base64 encoded
// to own account
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GradidoDeferredTransfer extends Message<GradidoDeferredTransfer> {
// amount is amount with decay for time span between transaction was received and timeout
// useable amount can be calculated
// recipient address don't need to be registered in blockchain with register address
@Field.d(1, GradidoTransfer)
public transfer: GradidoTransfer
// if timeout timestamp is reached if it wasn't used, it will be booked back minus decay
// technically on blockchain no additional transaction will be created because how should sign it?
// the decay for amount and the seconds until timeout is lost no matter what happened
// consider is as fee for this service
// rest decay could be transferred back as separate transaction
@Field.d(2, 'TimestampSeconds')
public timeout: TimestampSeconds
// split for n recipient
// max gradido per recipient? or per transaction with cool down?
}

View File

@ -0,0 +1,21 @@
import { Field, Message } from '@apollo/protobufjs'
import { SignatureMap } from './SignatureMap'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GradidoTransaction extends Message<GradidoTransaction> {
@Field.d(1, SignatureMap)
public sigMap: SignatureMap
// inspired by Hedera
// bodyBytes are the payload for signature
// bodyBytes are serialized TransactionBody
@Field.d(2, 'bytes')
public bodyBytes: Buffer
// if it is a cross group transaction the parent message
// id from outbound transaction or other by cross
@Field.d(3, 'bytes')
public parentMessageId: Buffer
}

View File

@ -0,0 +1,23 @@
import { Field, Message } from '@apollo/protobufjs'
import { TransferAmount } from './TransferAmount'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GradidoTransfer extends Message<GradidoTransfer> {
constructor(transaction: TransactionDraft, coinOrigin?: string) {
super({
sender: new TransferAmount({
amount: transaction.amount.toString(),
communityId: coinOrigin,
}),
})
}
@Field.d(1, TransferAmount)
public sender: TransferAmount
@Field.d(2, 'bytes')
public recipient: Buffer
}

View File

@ -0,0 +1,15 @@
import { Field, Message } from '@apollo/protobufjs'
// connect group together
// only CrossGroupType CROSS (in TransactionBody)
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class GroupFriendsUpdate extends Message<GroupFriendsUpdate> {
// if set to true, colors of this both groups are trait as the same
// on creation user get coins still in there color
// on transfer into another group which a connection exist,
// coins will be automatic swapped into user group color coin
// (if fusion between src coin and dst coin is enabled)
@Field.d(1, 'bool')
public colorFusion: boolean
}

View File

@ -0,0 +1,19 @@
import { Field, Message } from '@apollo/protobufjs'
import { AddressType } from '@enum/AddressType'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class RegisterAddress extends Message<RegisterAddress> {
@Field.d(1, 'bytes')
public userPubkey: Buffer
@Field.d(2, 'AddressType')
public addressType: AddressType
@Field.d(3, 'bytes')
public nameHash: Buffer
@Field.d(4, 'bytes')
public subaccountPubkey: Buffer
}

View File

@ -0,0 +1,10 @@
import { Field, Message } from '@apollo/protobufjs'
import { SignaturePair } from './SignaturePair'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class SignatureMap extends Message<SignatureMap> {
@Field.d(1, SignaturePair, 'repeated')
public sigPair: SignaturePair
}

View File

@ -0,0 +1,11 @@
import { Field, Message } from '@apollo/protobufjs'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class SignaturePair extends Message<SignaturePair> {
@Field.d(1, 'bytes')
public pubKey: Buffer
@Field.d(2, 'bytes')
public signature: Buffer
}

View File

@ -0,0 +1,16 @@
import { Timestamp } from './Timestamp'
describe('test timestamp constructor', () => {
it('with date input object', () => {
const now = new Date('2011-04-17T12:01:10.109')
const timestamp = new Timestamp(now)
expect(timestamp.seconds).toEqual(1303041670)
expect(timestamp.nanoSeconds).toEqual(109000000)
})
it('with milliseconds number input', () => {
const timestamp = new Timestamp(1303041670109)
expect(timestamp.seconds).toEqual(1303041670)
expect(timestamp.nanoSeconds).toEqual(109000000)
})
})

View File

@ -0,0 +1,27 @@
import { Field, Message } from '@apollo/protobufjs'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class Timestamp extends Message<Timestamp> {
public constructor(input?: Date | number) {
let seconds = 0
let nanoSeconds = 0
if (input instanceof Date) {
seconds = Math.floor(input.getTime() / 1000)
nanoSeconds = (input.getTime() % 1000) * 1000000 // Convert milliseconds to nanoseconds
} else if (typeof input === 'number') {
// Calculate seconds and nanoseconds from milliseconds
seconds = Math.floor(input / 1000)
nanoSeconds = (input % 1000) * 1000000
}
super({ seconds, nanoSeconds })
}
// Number of complete seconds since the start of the epoch
@Field.d(1, 'int64')
public seconds: number
// Number of nanoseconds since the start of the last second
@Field.d(2, 'int32')
public nanoSeconds: number
}

View File

@ -0,0 +1,14 @@
import { TimestampSeconds } from './TimestampSeconds'
describe('test TimestampSeconds constructor', () => {
it('with date input object', () => {
const now = new Date('2011-04-17T12:01:10.109')
const timestamp = new TimestampSeconds(now)
expect(timestamp.seconds).toEqual(1303041670)
})
it('with milliseconds number input', () => {
const timestamp = new TimestampSeconds(1303041670109)
expect(timestamp.seconds).toEqual(1303041670)
})
})

View File

@ -0,0 +1,20 @@
import { Field, Message } from '@apollo/protobufjs'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class TimestampSeconds extends Message<TimestampSeconds> {
public constructor(input?: Date | number) {
let seconds = 0
// Calculate seconds from milliseconds
if (input instanceof Date) {
seconds = Math.floor(input.getTime() / 1000)
} else if (typeof input === 'number') {
seconds = Math.floor(input / 1000)
}
super({ seconds })
}
// Number of complete seconds since the start of the epoch
@Field.d(1, 'int64')
public seconds: number
}

View File

@ -0,0 +1,66 @@
import { Field, Message, OneOf } from '@apollo/protobufjs'
import { CrossGroupType } from '@/graphql/enum/CrossGroupType'
import { Timestamp } from './Timestamp'
import { GradidoTransfer } from './GradidoTransfer'
import { GradidoCreation } from './GradidoCreation'
import { GradidoDeferredTransfer } from './GradidoDeferredTransfer'
import { GroupFriendsUpdate } from './GroupFriendsUpdate'
import { RegisterAddress } from './RegisterAddress'
import { TransactionDraft } from '@/graphql/input/TransactionDraft'
import { determineCrossGroupType, determineOtherGroup } from '@/controller/TransactionBody'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class TransactionBody extends Message<TransactionBody> {
public constructor(transaction: TransactionDraft) {
const type = determineCrossGroupType(transaction)
super({
memo: 'Not implemented yet',
createdAt: new Timestamp(new Date(transaction.createdAt)),
versionNumber: '3.3',
type,
otherGroup: determineOtherGroup(type, transaction),
})
}
@Field.d(1, 'string')
public memo: string
@Field.d(2, Timestamp)
public createdAt: Timestamp
@Field.d(3, 'string')
public versionNumber: string
@Field.d(4, CrossGroupType)
public type: CrossGroupType
@Field.d(5, 'string')
public otherGroup: string
@OneOf.d(
'gradidoTransfer',
'gradidoCreation',
'groupFriendsUpdate',
'registerAddress',
'gradidoDeferredTransfer',
)
public data: string
@Field.d(6, 'GradidoTransfer')
transfer?: GradidoTransfer
@Field.d(7, 'GradidoCreation')
creation?: GradidoCreation
@Field.d(8, 'GroupFriendsUpdate')
groupFriendsUpdate?: GroupFriendsUpdate
@Field.d(9, 'RegisterAddress')
registerAddress?: RegisterAddress
@Field.d(10, 'GradidoDeferredTransfer')
deferredTransfer?: GradidoDeferredTransfer
}

View File

@ -0,0 +1,16 @@
import { Field, Message } from '@apollo/protobufjs'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class TransferAmount extends Message<TransferAmount> {
@Field.d(1, 'bytes')
public pubkey: Buffer
@Field.d(2, 'string')
public amount: string
// community which created this coin
// used for colored coins
@Field.d(3, 'string')
public communityId: string
}

View File

@ -1,36 +0,0 @@
import 'reflect-metadata'
import { TransactionType } from '@enum/TransactionType'
import { TransactionInput } from '@input/TransactionInput'
import Decimal from 'decimal.js-light'
import { TransactionBody } from './TransactionBody'
describe('proto/TransactionBodyTest', () => {
it('test compatible with graphql/input/TransactionInput', async () => {
// test data
const type = TransactionType.SEND
const amount = new Decimal('10')
const createdAt = 1688992436
// init both objects
// graphql input object
const transactionInput = new TransactionInput()
transactionInput.type = type
transactionInput.amount = amount
transactionInput.createdAt = createdAt
// protobuf object
const transactionBody = new TransactionBody()
transactionBody.type = type
transactionBody.amount = amount.toString()
transactionBody.createdAt = createdAt
// create protobuf object from graphql Input object
const message = TransactionBody.fromObject(transactionInput)
// serialize both protobuf objects
const messageBuffer = TransactionBody.encode(message).finish()
const messageBuffer2 = TransactionBody.encode(transactionBody).finish()
// compare
expect(messageBuffer).toStrictEqual(messageBuffer2)
})
})

View File

@ -1,18 +0,0 @@
import { TransactionType } from '../graphql/enum/TransactionType'
import { Field, Message } from '@apollo/protobufjs'
// https://www.npmjs.com/package/@apollo/protobufjs
// eslint-disable-next-line no-use-before-define
export class TransactionBody extends Message<TransactionBody> {
@Field.d(1, TransactionType)
type: TransactionType
@Field.d(2, 'string')
amount: string
@Field.d(3, 'uint64')
createdAt: number
// @protoField.d(4, 'string')
// communitySum: Decimal
}

View File

@ -51,10 +51,13 @@
"@arg/*": ["src/graphql/arg/*"],
"@enum/*": ["src/graphql/enum/*"],
"@input/*": ["src/graphql/input/*"],
"@model/*": ["src/graphql/model/*"],
"@resolver/*": ["src/graphql/resolver/*"],
"@scalar/*": ["src/graphql/scalar/*"],
"@test/*": ["test/*"],
"@proto/*" : ["src/proto/*"],
"@controller/*": ["src/controller/*"],
"@validator/*" : ["src/graphql/validator/*"]
/* external */
},
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */

File diff suppressed because it is too large Load Diff

View File

@ -163,12 +163,12 @@ services:
- internal-net
- external-net
ports:
- 6000:6000
- 6010:6010
restart: always
environment:
# Envs used in Dockerfile
# - DOCKER_WORKDIR="/app"
- PORT=6000
- PORT=6010
- BUILD_DATE
- BUILD_VERSION
- BUILD_COMMIT