From 2ff7adef52312a1086c78596647008fc7843fe4d Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Mon, 23 Oct 2023 19:07:13 +0200 Subject: [PATCH 01/47] first draft --- dlt-connector/@types/bip32-ed25519/index.d.ts | 1 + dlt-connector/package.json | 4 +- .../src/controller/Community.test.ts | 66 ------- dlt-connector/src/controller/Community.ts | 28 --- .../src/controller/GradidoTransaction.ts | 10 -- .../src/controller/KeyManager.test.ts | 22 +++ dlt-connector/src/controller/KeyManager.ts | 123 +++++++++++++ .../src/controller/TransactionBody.test.ts | 162 ------------------ dlt-connector/src/data/Account.repository.ts | 33 ++++ .../src/data/Community.repository.ts | 74 ++++++++ dlt-connector/src/data/KeyPair.ts | 38 ++++ dlt-connector/src/data/Transaction.builder.ts | 147 ++++++++++++++++ .../src/data/Transaction.repository.ts | 48 ++++++ dlt-connector/src/data/account.factory.ts | 42 +++++ dlt-connector/src/data/community.factory.ts | 31 ++++ .../src/data/proto/3_3/CommunityRoot.ts | 40 +++++ .../proto/3_3/ConfirmedTransaction.ts} | 12 +- .../proto/3_3/GradidoCreation.test.ts | 0 .../src/data/proto/3_3/GradidoCreation.ts | 53 ++++++ .../proto/3_3/GradidoDeferredTransfer.ts | 22 ++- .../src/data/proto/3_3/GradidoTransaction.ts | 43 +++++ .../src/data/proto/3_3/GradidoTransfer.ts | 48 ++++++ .../proto/3_3/GroupFriendsUpdate.ts | 16 +- .../src/data/proto/3_3/RegisterAddress.ts | 33 ++++ .../src/{ => data}/proto/3_3/SignatureMap.ts | 8 +- .../src/{ => data}/proto/3_3/SignaturePair.ts | 6 +- .../{ => data}/proto/3_3/Timestamp.test.ts | 0 .../src/{ => data}/proto/3_3/Timestamp.ts | 2 +- .../proto/3_3/TimestampSeconds.test.ts | 0 .../{ => data}/proto/3_3/TimestampSeconds.ts | 2 +- .../src/data/proto/3_3/TransactionBody.ts | 129 ++++++++++++++ .../{ => data}/proto/3_3/TransferAmount.ts | 2 +- .../src/data/proto/3_3/enum/AddressType.ts | 19 ++ .../src/data/proto/3_3/enum/CrossGroupType.ts | 7 + .../proto}/TransactionBase.ts | 3 + .../src/data/proto/TransactionBody.builder.ts | 95 ++++++++++ .../proto/transactionBody.logic.ts} | 32 +--- dlt-connector/src/graphql/arg/CommunityArg.ts | 19 ++ .../src/graphql/enum/InputTransactionType.ts | 12 ++ .../src/graphql/enum/TransactionErrorType.ts | 2 + .../src/graphql/enum/TransactionType.ts | 27 +-- .../src/graphql/input/TransactionDraft.ts | 8 +- dlt-connector/src/graphql/model/Community.ts | 36 ++++ .../src/graphql/model/TransactionRecipe.ts | 25 +++ .../src/graphql/model/TransactionResult.ts | 13 +- .../src/graphql/resolver/CommunityResolver.ts | 82 +++++---- .../graphql/resolver/TransactionsResolver.ts | 74 ++++++-- .../backendToDb/community/Community.role.ts | 6 + .../community/ForeignCommunity.role.ts | 19 ++ .../community/HomeCommunity.role.ts | 28 +++ .../community/community.context.ts | 30 ++++ .../CommunityRootTransaction.role.ts | 24 +++ .../transaction/TransactionRecipe.role.ts | 49 ++++++ .../transaction/transaction.context.ts | 20 +++ .../src/proto/3_3/GradidoCreation.ts | 32 ---- .../src/proto/3_3/GradidoTransaction.ts | 21 --- .../src/proto/3_3/GradidoTransfer.ts | 23 --- .../src/proto/3_3/RegisterAddress.ts | 19 -- .../src/proto/3_3/TransactionBody.ts | 66 ------- dlt-connector/src/utils/cryptoHelper.ts | 6 + .../src/utils/derivationHelper.test.ts | 15 ++ dlt-connector/src/utils/derivationHelper.ts | 17 ++ dlt-connector/src/utils/typeConverter.test.ts | 12 ++ dlt-connector/src/utils/typeConverter.ts | 45 +++++ dlt-connector/tsconfig.json | 3 +- dlt-connector/yarn.lock | 113 +++++++++++- dlt-database/entity/0001-init_db/Account.ts | 2 +- dlt-database/entity/0001-init_db/Community.ts | 2 +- .../0001-init_db/ConfirmedTransaction.ts | 2 +- .../entity/0001-init_db/TransactionRecipe.ts | 4 +- .../ConfirmedTransaction.ts | 2 +- .../Account.ts | 92 ++++++++++ .../Community.ts | 68 ++++++++ .../Transaction.ts | 120 +++++++++++++ dlt-database/entity/Account.ts | 2 +- dlt-database/entity/Community.ts | 2 +- dlt-database/entity/Transaction.ts | 1 + dlt-database/entity/index.ts | 6 +- .../0003-refactor_transaction_recipe.ts | 97 +++++++++++ 79 files changed, 2092 insertions(+), 555 deletions(-) create mode 100644 dlt-connector/@types/bip32-ed25519/index.d.ts delete mode 100644 dlt-connector/src/controller/Community.test.ts delete mode 100644 dlt-connector/src/controller/Community.ts delete mode 100644 dlt-connector/src/controller/GradidoTransaction.ts create mode 100644 dlt-connector/src/controller/KeyManager.test.ts create mode 100644 dlt-connector/src/controller/KeyManager.ts delete mode 100644 dlt-connector/src/controller/TransactionBody.test.ts create mode 100644 dlt-connector/src/data/Account.repository.ts create mode 100644 dlt-connector/src/data/Community.repository.ts create mode 100644 dlt-connector/src/data/KeyPair.ts create mode 100644 dlt-connector/src/data/Transaction.builder.ts create mode 100644 dlt-connector/src/data/Transaction.repository.ts create mode 100644 dlt-connector/src/data/account.factory.ts create mode 100644 dlt-connector/src/data/community.factory.ts create mode 100644 dlt-connector/src/data/proto/3_3/CommunityRoot.ts rename dlt-connector/src/{proto/3_3/GradidoConfirmedTransaction.ts => data/proto/3_3/ConfirmedTransaction.ts} (67%) rename dlt-connector/src/{ => data}/proto/3_3/GradidoCreation.test.ts (100%) create mode 100644 dlt-connector/src/data/proto/3_3/GradidoCreation.ts rename dlt-connector/src/{ => data}/proto/3_3/GradidoDeferredTransfer.ts (65%) create mode 100644 dlt-connector/src/data/proto/3_3/GradidoTransaction.ts create mode 100644 dlt-connector/src/data/proto/3_3/GradidoTransfer.ts rename dlt-connector/src/{ => data}/proto/3_3/GroupFriendsUpdate.ts (52%) create mode 100644 dlt-connector/src/data/proto/3_3/RegisterAddress.ts rename dlt-connector/src/{ => data}/proto/3_3/SignatureMap.ts (66%) rename dlt-connector/src/{ => data}/proto/3_3/SignaturePair.ts (63%) rename dlt-connector/src/{ => data}/proto/3_3/Timestamp.test.ts (100%) rename dlt-connector/src/{ => data}/proto/3_3/Timestamp.ts (94%) rename dlt-connector/src/{ => data}/proto/3_3/TimestampSeconds.test.ts (100%) rename dlt-connector/src/{ => data}/proto/3_3/TimestampSeconds.ts (91%) create mode 100644 dlt-connector/src/data/proto/3_3/TransactionBody.ts rename dlt-connector/src/{ => data}/proto/3_3/TransferAmount.ts (88%) create mode 100644 dlt-connector/src/data/proto/3_3/enum/AddressType.ts create mode 100644 dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts rename dlt-connector/src/{controller => data/proto}/TransactionBase.ts (73%) create mode 100644 dlt-connector/src/data/proto/TransactionBody.builder.ts rename dlt-connector/src/{controller/TransactionBody.ts => data/proto/transactionBody.logic.ts} (60%) create mode 100644 dlt-connector/src/graphql/arg/CommunityArg.ts create mode 100755 dlt-connector/src/graphql/enum/InputTransactionType.ts mode change 100755 => 100644 dlt-connector/src/graphql/enum/TransactionType.ts create mode 100644 dlt-connector/src/graphql/model/Community.ts create mode 100644 dlt-connector/src/graphql/model/TransactionRecipe.ts create mode 100644 dlt-connector/src/interactions/backendToDb/community/Community.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/community/community.context.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts delete mode 100644 dlt-connector/src/proto/3_3/GradidoCreation.ts delete mode 100644 dlt-connector/src/proto/3_3/GradidoTransaction.ts delete mode 100644 dlt-connector/src/proto/3_3/GradidoTransfer.ts delete mode 100644 dlt-connector/src/proto/3_3/RegisterAddress.ts delete mode 100644 dlt-connector/src/proto/3_3/TransactionBody.ts create mode 100644 dlt-connector/src/utils/cryptoHelper.ts create mode 100644 dlt-connector/src/utils/derivationHelper.test.ts create mode 100644 dlt-connector/src/utils/derivationHelper.ts create mode 100644 dlt-connector/src/utils/typeConverter.test.ts create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/Account.ts create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/Community.ts create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts create mode 100644 dlt-database/entity/Transaction.ts create mode 100644 dlt-database/migrations/0003-refactor_transaction_recipe.ts diff --git a/dlt-connector/@types/bip32-ed25519/index.d.ts b/dlt-connector/@types/bip32-ed25519/index.d.ts new file mode 100644 index 000000000..7a3375ab6 --- /dev/null +++ b/dlt-connector/@types/bip32-ed25519/index.d.ts @@ -0,0 +1 @@ +declare module 'bip32-ed25519' diff --git a/dlt-connector/package.json b/dlt-connector/package.json index 47e9136ff..d64b6d743 100644 --- a/dlt-connector/package.json +++ b/dlt-connector/package.json @@ -16,10 +16,11 @@ "test": "cross-env TZ=UTC NODE_ENV=development jest --runInBand --forceExit --detectOpenHandles" }, "dependencies": { - "@apollo/protobufjs": "^1.2.7", "@apollo/server": "^4.7.5", "@apollo/utils.fetcher": "^3.0.0", "@iota/client": "^2.2.4", + "bip32-ed25519": "^0.0.4", + "bip39": "^3.1.0", "body-parser": "^1.20.2", "class-validator": "^0.14.0", "cors": "^2.8.5", @@ -32,6 +33,7 @@ "graphql-scalars": "^1.22.2", "log4js": "^6.7.1", "nodemon": "^2.0.20", + "protobufjs": "^7.2.5", "reflect-metadata": "^0.1.13", "sodium-native": "^4.0.4", "tsconfig-paths": "^4.1.2", diff --git a/dlt-connector/src/controller/Community.test.ts b/dlt-connector/src/controller/Community.test.ts deleted file mode 100644 index d8c5ad0de..000000000 --- a/dlt-connector/src/controller/Community.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import 'reflect-metadata' -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { create as createCommunity, getAllTopics, isExist } from './Community' -import { TestDB } from '@test/TestDB' -import { getDataSource } from '@/typeorm/DataSource' -import { Community } from '@entity/Community' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' - -jest.mock('@typeorm/DataSource', () => ({ - getDataSource: () => TestDB.instance.dbConnect, -})) - -describe('controller/Community', () => { - beforeAll(async () => { - await TestDB.instance.setupTestDB() - // apolloTestServer = await createApolloTestServer() - }) - - afterAll(async () => { - await TestDB.instance.teardownTestDB() - }) - - describe('createCommunity', () => { - it('valid community', async () => { - const communityDraft = new CommunityDraft() - communityDraft.foreign = false - communityDraft.createdAt = '2022-05-01T17:00:12.128Z' - communityDraft.uuid = '3d813cbb-47fb-32ba-91df-831e1593ac29' - - const iotaTopic = iotaTopicFromCommunityUUID(communityDraft.uuid) - expect(iotaTopic).toEqual('204ef6aed15fbf0f9da5819e88f8eea8e3adbe1e2c2d43280780a4b8c2d32b56') - - const createdAtDate = new Date(communityDraft.createdAt) - const communityEntity = createCommunity(communityDraft) - expect(communityEntity).toMatchObject({ - iotaTopic, - createdAt: createdAtDate, - foreign: false, - }) - await getDataSource().manager.save(communityEntity) - }) - }) - - describe('list communities', () => { - it('get all topics', async () => { - expect(await getAllTopics()).toMatchObject([ - '204ef6aed15fbf0f9da5819e88f8eea8e3adbe1e2c2d43280780a4b8c2d32b56', - ]) - }) - - it('isExist with communityDraft', async () => { - const communityDraft = new CommunityDraft() - communityDraft.foreign = false - communityDraft.createdAt = '2022-05-01T17:00:12.128Z' - communityDraft.uuid = '3d813cbb-47fb-32ba-91df-831e1593ac29' - expect(await isExist(communityDraft)).toBe(true) - }) - - it('createdAt with ms precision', async () => { - const list = await Community.findOne({ where: { foreign: false } }) - expect(list).toMatchObject({ - createdAt: new Date('2022-05-01T17:00:12.128Z'), - }) - }) - }) -}) diff --git a/dlt-connector/src/controller/Community.ts b/dlt-connector/src/controller/Community.ts deleted file mode 100644 index eff1b2b64..000000000 --- a/dlt-connector/src/controller/Community.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' -import { Community } from '@entity/Community' - -export const isExist = async (community: CommunityDraft | string): Promise => { - const iotaTopic = - community instanceof CommunityDraft ? iotaTopicFromCommunityUUID(community.uuid) : community - const result = await Community.find({ - where: { iotaTopic }, - }) - return result.length > 0 -} - -export const create = (community: CommunityDraft, topic?: string): Community => { - const communityEntity = Community.create() - communityEntity.iotaTopic = topic ?? iotaTopicFromCommunityUUID(community.uuid) - communityEntity.createdAt = new Date(community.createdAt) - communityEntity.foreign = community.foreign - if (!community.foreign) { - // TODO: generate keys - } - return communityEntity -} - -export const getAllTopics = async (): Promise => { - const communities = await Community.find({ select: { iotaTopic: true } }) - return communities.map((community) => community.iotaTopic) -} diff --git a/dlt-connector/src/controller/GradidoTransaction.ts b/dlt-connector/src/controller/GradidoTransaction.ts deleted file mode 100644 index 671f3f57a..000000000 --- a/dlt-connector/src/controller/GradidoTransaction.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 -} diff --git a/dlt-connector/src/controller/KeyManager.test.ts b/dlt-connector/src/controller/KeyManager.test.ts new file mode 100644 index 000000000..7f3d26932 --- /dev/null +++ b/dlt-connector/src/controller/KeyManager.test.ts @@ -0,0 +1,22 @@ +/* eslint-disable camelcase */ +import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' +import { generateFromSeed, toPublic } from 'bip32-ed25519' + +describe('controller/KeyManager', () => { + describe('test crypto lib', () => { + it('key length', () => { + const mnemonic = entropyToMnemonic( + 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899', + ) + expect(mnemonic).toEqual( + 'primary taxi danger target useless ancient match hammer fever crisp timber crew produce toy jeans that abandon math mimic master filter design carbon carbon', + ) + const seed = mnemonicToSeedSync(mnemonic) + // private key 64 Bytes + 32 Byte ChainCode + const extendPrivkey = generateFromSeed(seed) + expect(extendPrivkey).toHaveLength(96) + // public key 32 Bytes + 32 Bytes ChainCode + expect(toPublic(extendPrivkey)).toHaveLength(64) + }) + }) +}) diff --git a/dlt-connector/src/controller/KeyManager.ts b/dlt-connector/src/controller/KeyManager.ts new file mode 100644 index 000000000..df1e61b33 --- /dev/null +++ b/dlt-connector/src/controller/KeyManager.ts @@ -0,0 +1,123 @@ +// eslint-disable-next-line camelcase +import { randombytes_buf } from 'sodium-native' +import { CONFIG } from '../config' +import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' +// https://www.npmjs.com/package/bip32-ed25519?activeTab=code +import { + generateFromSeed, + derivePrivate, + sign as ed25519Sign, + verify as ed25519Verify, +} from 'bip32-ed25519' +import { logger } from '@/server/logger' +import { LogError } from '@/server/LogError' +import { KeyPair } from '@/data/KeyPair' +import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' +import { CommunityRepository } from '@/data/Community.repository' +import { SignaturePair } from '@/data/proto/3_3/SignaturePair' + +// Source: https://refactoring.guru/design-patterns/singleton/typescript/example +// and ../federation/client/FederationClientFactory.ts +/** + * A Singleton class defines the `getInstance` method that lets clients access + * the unique singleton instance. + */ +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export class KeyManager { + // eslint-disable-next-line no-use-before-define + private static instance: KeyManager + private homeCommunityRootKeys: KeyPair | null = null + + /** + * The Singleton's constructor should always be private to prevent direct + * construction calls with the `new` operator. + */ + // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function + private constructor() {} + + /** + * The static method that controls the access to the singleton instance. + * + * This implementation let you subclass the Singleton class while keeping + * just one instance of each subclass around. + */ + public static getInstance(): KeyManager { + if (!KeyManager.instance) { + KeyManager.instance = new KeyManager() + } + return KeyManager.instance + } + + public async init(): Promise { + try { + this.homeCommunityRootKeys = await CommunityRepository.loadHomeCommunityKeyPair() + return true + } catch (error) { + logger.error('error by init key manager', error) + return false + } + } + + public static generateKeyPair(): KeyPair { + const mnemonic = KeyManager.generateMnemonic(CONFIG.IOTA_HOME_COMMUNITY_SEED ?? undefined) + // logger.info('passphrase for key pair: ' + mnemonic) + const seed = mnemonicToSeedSync(mnemonic) + return new KeyPair(generateFromSeed(seed)) + } + + public setHomeCommunityKeyPair(keyPair: KeyPair) { + this.homeCommunityRootKeys = keyPair + } + + public sign(transaction: GradidoTransaction, keys?: KeyPair[]) { + let localKeys: KeyPair[] = [] + + if (!keys && this.homeCommunityRootKeys) { + localKeys.push(this.homeCommunityRootKeys) + } else if (keys) { + localKeys = keys + } + if (!localKeys.length) { + throw new LogError('no key pair for signing') + } + localKeys.forEach((keyPair: KeyPair) => { + const signature = ed25519Sign(transaction.bodyBytes, keyPair.getExtendPrivateKey()) + const sigPair = new SignaturePair({ pubKey: keyPair.publicKey, signature }) + logger.debug('sign transaction', { + signature: signature.toString('hex'), + publicKey: keyPair.publicKey.toString('hex'), + bodyBytes: transaction.bodyBytes.toString('hex'), + }) + transaction.sigMap.sigPair.push(sigPair) + }) + } + + public getHomeCommunityPublicKey(): Buffer | undefined { + if (!this.homeCommunityRootKeys) return undefined + return this.homeCommunityRootKeys.publicKey + } + + public derive(path: number[], parentKeys?: KeyPair): KeyPair { + const extendedPrivateKey = parentKeys + ? parentKeys.getExtendPrivateKey() + : this.homeCommunityRootKeys?.getExtendPrivateKey() + if (!extendedPrivateKey) { + throw new LogError('missing parent or root key pair') + } + return new KeyPair( + path.reduce( + (extendPrivateKey: Buffer, node: number) => derivePrivate(extendPrivateKey, node), + extendedPrivateKey, + ), + ) + } + + static generateMnemonic(seed?: Buffer | string): string { + if (seed) { + return entropyToMnemonic(seed) + } + const entropy = Buffer.alloc(256) + randombytes_buf(entropy) + return entropyToMnemonic(entropy) + } +} diff --git a/dlt-connector/src/controller/TransactionBody.test.ts b/dlt-connector/src/controller/TransactionBody.test.ts deleted file mode 100644 index eac613ab7..000000000 --- a/dlt-connector/src/controller/TransactionBody.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -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', - ) - }) - }) -}) diff --git a/dlt-connector/src/data/Account.repository.ts b/dlt-connector/src/data/Account.repository.ts new file mode 100644 index 000000000..2a228c261 --- /dev/null +++ b/dlt-connector/src/data/Account.repository.ts @@ -0,0 +1,33 @@ +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { getDataSource } from '@/typeorm/DataSource' +import { Account } from '@entity/Account' +import { User } from '@entity/User' +import { In } from 'typeorm' + +export const AccountRepository = getDataSource() + .getRepository(Account) + .extend({ + findAccountsByPublicKeys(publicKeys: Buffer[]): Promise { + return Account.findBy({ derive2Pubkey: In(publicKeys) }) + }, + + async findAccountByPublicKey(publicKey: Buffer | undefined): Promise { + if (!publicKey) return undefined + return (await Account.findOneBy({ derive2Pubkey: Buffer.from(publicKey) })) ?? undefined + }, + + async findAccountByUserIdentifier({ + uuid, + accountNr, + }: UserIdentifier): Promise { + const user = await User.findOne({ + where: { gradidoID: uuid, accounts: { derivationIndex: accountNr ?? 1 } }, + relations: { accounts: true }, + }) + if (user && user.accounts?.length === 1) { + const account = user.accounts[0] + account.user = user + return account + } + }, + }) diff --git a/dlt-connector/src/data/Community.repository.ts b/dlt-connector/src/data/Community.repository.ts new file mode 100644 index 000000000..1624404d3 --- /dev/null +++ b/dlt-connector/src/data/Community.repository.ts @@ -0,0 +1,74 @@ +import { CommunityArg } from '@/graphql/arg/CommunityArg' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { TransactionError } from '@/graphql/model/TransactionError' +import { getDataSource } from '@/typeorm/DataSource' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' +import { Community } from '@entity/Community' +import { FindOptionsSelect, In, IsNull, Not } from 'typeorm' +import { KeyPair } from './KeyPair' +import { LogError } from '@/server/LogError' + +export const CommunityRepository = getDataSource() + .getRepository(Community) + .extend({ + async isExist(community: CommunityDraft | string): Promise { + const iotaTopic = + community instanceof CommunityDraft ? iotaTopicFromCommunityUUID(community.uuid) : community + const result = await Community.find({ + where: { iotaTopic }, + }) + return result.length > 0 + }, + + async findByCommunityArg({ uuid, foreign, confirmed }: CommunityArg): Promise { + return await Community.find({ + where: { + ...(uuid && { iotaTopic: iotaTopicFromCommunityUUID(uuid) }), + ...(foreign && { foreign }), + ...(confirmed && { confirmedAt: Not(IsNull()) }), + }, + }) + }, + + async findByCommunityUuid(communityUuid: string): Promise { + return await Community.findOneBy({ iotaTopic: iotaTopicFromCommunityUUID(communityUuid) }) + }, + + async findByIotaTopic(iotaTopic: string): Promise { + return await Community.findOneBy({ iotaTopic }) + }, + + findCommunitiesByTopics(topics: string[]): Promise { + return Community.findBy({ iotaTopic: In(topics) }) + }, + + async getCommunityForUserIdentifier( + identifier: UserIdentifier, + ): Promise { + if (!identifier.communityUuid) { + throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community uuid not set') + } + return ( + (await Community.findOneBy({ + iotaTopic: iotaTopicFromCommunityUUID(identifier.communityUuid), + })) ?? undefined + ) + }, + + findAll(select: FindOptionsSelect): Promise { + return Community.find({ select }) + }, + + async loadHomeCommunityKeyPair(): Promise { + const community = await Community.findOneOrFail({ + where: { foreign: false }, + select: { rootChaincode: true, rootPubkey: true, rootPrivkey: true }, + }) + if (!community.rootChaincode || !community.rootPrivkey) { + throw new LogError('Missing chaincode or private key for home community') + } + return new KeyPair(community) + }, + }) diff --git a/dlt-connector/src/data/KeyPair.ts b/dlt-connector/src/data/KeyPair.ts new file mode 100644 index 000000000..3487c1d95 --- /dev/null +++ b/dlt-connector/src/data/KeyPair.ts @@ -0,0 +1,38 @@ +// https://www.npmjs.com/package/bip32-ed25519?activeTab=code +import { toPublic } from 'bip32-ed25519' +import { Community } from '@entity/Community' +import { LogError } from '@/server/LogError' + +export class KeyPair { + /** + * @param input: Buffer = extended private key, returned from bip32-ed25519 generateFromSeed + * @param input: Community = community entity with keys loaded from db + * + */ + public constructor(input: Buffer | Community) { + if (input instanceof Buffer) { + this.privateKey = input.subarray(0, 64) + this.chainCode = input.subarray(64, 96) + this.publicKey = toPublic(input).subarray(0, 32) + } else if (input instanceof Community) { + if (!input.rootPrivkey || !input.rootChaincode || !input.rootPubkey) { + throw new LogError('missing private key or chaincode or public key in commmunity entity') + } + this.privateKey = input.rootPrivkey + this.publicKey = input.rootPubkey + this.chainCode = input.rootChaincode + } + } + + public getExtendPrivateKey(): Buffer { + return Buffer.concat([this.privateKey, this.chainCode]) + } + + public getExtendPublicKey(): Buffer { + return Buffer.concat([this.publicKey, this.chainCode]) + } + + publicKey: Buffer + chainCode: Buffer + privateKey: Buffer +} diff --git a/dlt-connector/src/data/Transaction.builder.ts b/dlt-connector/src/data/Transaction.builder.ts new file mode 100644 index 000000000..4b1b385ab --- /dev/null +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -0,0 +1,147 @@ +import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' +import { TransactionBody } from '@/data/proto/3_3/TransactionBody' +import { bodyBytesToTransactionBody, transactionBodyToBodyBytes } from '@/utils/typeConverter' +import { Transaction } from '@entity/Transaction' +import { AccountRepository } from './Account.repository' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { CommunityRepository } from './Community.repository' +import { LogError } from '@/server/LogError' +import { Account } from '@entity/Account' +import { Community } from '@entity/Community' + +export class TransactionBuilder { + private transaction: Transaction + + // https://refactoring.guru/design-patterns/builder/typescript/example + /** + * A fresh builder instance should contain a blank product object, which is + * used in further assembly. + */ + constructor() { + this.reset() + } + + public reset(): void { + this.transaction = Transaction.create() + } + + /** + * Concrete Builders are supposed to provide their own methods for + * retrieving results. That's because various types of builders may create + * entirely different products that don't follow the same interface. + * Therefore, such methods cannot be declared in the base Builder interface + * (at least in a statically typed programming language). + * + * Usually, after returning the end result to the client, a builder instance + * is expected to be ready to start producing another product. That's why + * it's a usual practice to call the reset method at the end of the + * `getProduct` method body. However, this behavior is not mandatory, and + * you can make your builders wait for an explicit reset call from the + * client code before disposing of the previous result. + */ + public build(): Transaction { + const result = this.transaction + this.reset() + return result + } + + // return transaction without calling reset + public getTransaction(): Transaction { + return this.transaction + } + + public setSigningAccount(signingAccount: Account): TransactionBuilder { + this.transaction.signingAccount = signingAccount + return this + } + + public setRecipientAccount(recipientAccount: Account): TransactionBuilder { + this.transaction.recipientAccount = recipientAccount + return this + } + + public setSenderCommunity(senderCommunity: Community): TransactionBuilder { + this.transaction.senderCommunity = senderCommunity + return this + } + + public setRecipientCommunity(recipientCommunity?: Community): TransactionBuilder { + if (!this.transaction.senderCommunity) { + throw new LogError('Please set sender community first!') + } + + this.transaction.recipientCommunity = + recipientCommunity && + this.transaction.senderCommunity && + this.transaction.senderCommunity.id !== recipientCommunity.id + ? recipientCommunity + : undefined + return this + } + + public setSignature(signature: Buffer): TransactionBuilder { + this.transaction.signature = signature + return this + } + + public async setSenderCommunityFromSenderUser( + senderUser: UserIdentifier, + ): Promise { + // get sender community + const senderCommunity = await CommunityRepository.getCommunityForUserIdentifier(senderUser) + if (!senderCommunity) { + throw new LogError("couldn't find sender community for transaction") + } + return this.setSenderCommunity(senderCommunity) + } + + public async setRecipientCommunityFromRecipientUser( + recipientUser: UserIdentifier, + ): Promise { + // get recipient community + const recipientCommunity = await CommunityRepository.getCommunityForUserIdentifier( + recipientUser, + ) + return this.setRecipientCommunity(recipientCommunity) + } + + public async fromGradidoTransactionSearchForAccounts( + gradidoTransaction: GradidoTransaction, + ): Promise { + this.transaction.bodyBytes = Buffer.from(gradidoTransaction.bodyBytes) + const transactionBody = bodyBytesToTransactionBody(this.transaction.bodyBytes) + this.fromTransactionBody(transactionBody) + + const firstSigPair = gradidoTransaction.getFirstSignature() + // TODO: adapt if transactions with more than one signatures where added + + // get recipient and signer accounts if not already set + this.transaction.signingAccount ??= await AccountRepository.findAccountByPublicKey( + firstSigPair.pubKey, + ) + this.transaction.recipientAccount ??= await AccountRepository.findAccountByPublicKey( + transactionBody.getRecipientPublicKey(), + ) + this.transaction.signature = Buffer.from(firstSigPair.signature) + + return this + } + + public fromGradidoTransaction(gradidoTransaction: GradidoTransaction): TransactionBuilder { + this.transaction.bodyBytes = Buffer.from(gradidoTransaction.bodyBytes) + const transactionBody = bodyBytesToTransactionBody(this.transaction.bodyBytes) + this.fromTransactionBody(transactionBody) + + const firstSigPair = gradidoTransaction.getFirstSignature() + // TODO: adapt if transactions with more than one signatures where added + this.transaction.signature = Buffer.from(firstSigPair.signature) + + return this + } + + public fromTransactionBody(transactionBody: TransactionBody): TransactionBuilder { + transactionBody.fillTransactionRecipe(this.transaction) + this.transaction.bodyBytes ??= transactionBodyToBodyBytes(transactionBody) + return this + } +} diff --git a/dlt-connector/src/data/Transaction.repository.ts b/dlt-connector/src/data/Transaction.repository.ts new file mode 100644 index 000000000..5a2a185bf --- /dev/null +++ b/dlt-connector/src/data/Transaction.repository.ts @@ -0,0 +1,48 @@ +import { getDataSource } from '@/typeorm/DataSource' +import { Transaction } from '@entity/Transaction' +import { IsNull } from 'typeorm' + +// https://www.artima.com/articles/the-dci-architecture-a-new-vision-of-object-oriented-programming +export const TransactionRepository = getDataSource() + .getRepository(Transaction) + .extend({ + findBySignature(signature: Buffer): Promise { + return this.findOneBy({ signature: Buffer.from(signature) }) + }, + findByMessageId(iotaMessageId: string): Promise { + return this.findOneBy({ iotaMessageId: Buffer.from(iotaMessageId, 'hex') }) + }, + async getNextPendingTransaction(): Promise { + return await this.findOne({ + where: { iotaMessageId: IsNull() }, + order: { createdAt: 'ASC' }, + relations: { signingAccount: true }, + }) + }, + async findExistingTransactionAndMissingMessageIds(messageIDsHex: string[]): Promise<{ + existingTransactions: Transaction[] + missingMessageIdsHex: string[] + }> { + const existingTransactions = await this.createQueryBuilder('Transaction') + .where('HEX(Transaction.iota_message_id) IN (:...messageIDs)', { + messageIDs: messageIDsHex, + }) + .leftJoinAndSelect('Transaction.recipientAccount', 'RecipientAccount') + .leftJoinAndSelect('RecipientAccount.user', 'RecipientUser') + .leftJoinAndSelect('Transaction.signingAccount', 'SigningAccount') + .leftJoinAndSelect('SigningAccount.user', 'SigningUser') + .getMany() + + const foundMessageIds = existingTransactions + .map((recipe) => recipe.iotaMessageId?.toString('hex')) + .filter((messageId) => !!messageId) + // find message ids for which we don't already have a transaction recipe + const missingMessageIdsHex = messageIDsHex.filter( + (id: string) => !foundMessageIds.includes(id), + ) + return { existingTransactions, missingMessageIdsHex } + }, + async removeConfirmedTransaction(transactions: Transaction[]): Promise { + return transactions.filter((transaction: Transaction) => transaction.runningHash.length === 0) + }, + }) diff --git a/dlt-connector/src/data/account.factory.ts b/dlt-connector/src/data/account.factory.ts new file mode 100644 index 000000000..d823c8345 --- /dev/null +++ b/dlt-connector/src/data/account.factory.ts @@ -0,0 +1,42 @@ +import { KeyManager } from '@/controller/KeyManager' +import { KeyPair } from '@/data/KeyPair' +import { AddressType } from '@/data/proto/3_3/enum/AddressType' +import { hardenDerivationIndex } from '@/utils/derivationHelper' +import { Account } from '@entity/Account' +import Decimal from 'decimal.js-light' + +const GMW_ACCOUNT_DERIVATION_INDEX = 1 +const AUF_ACCOUNT_DERIVATION_INDEX = 2 + +export const createAccount = ( + keyPair: KeyPair, + createdAt: Date, + derivationIndex: number, + type: AddressType, +): Account => { + const account = Account.create() + account.derivationIndex = derivationIndex + account.derive2Pubkey = KeyManager.getInstance().derive([derivationIndex], keyPair).publicKey + account.type = type.valueOf() + account.createdAt = createdAt + account.balance = new Decimal(0) + return account +} + +export const createGmwAccount = (keyPair: KeyPair, createdAt: Date): Account => { + return createAccount( + keyPair, + createdAt, + hardenDerivationIndex(GMW_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_GMW, + ) +} + +export const createAufAccount = (keyPair: KeyPair, createdAt: Date): Account => { + return createAccount( + keyPair, + createdAt, + hardenDerivationIndex(AUF_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_AUF, + ) +} diff --git a/dlt-connector/src/data/community.factory.ts b/dlt-connector/src/data/community.factory.ts new file mode 100644 index 000000000..d80ff315a --- /dev/null +++ b/dlt-connector/src/data/community.factory.ts @@ -0,0 +1,31 @@ +import { KeyManager } from '@/controller/KeyManager' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' +import { Community } from '@entity/Community' +import { createAufAccount, createGmwAccount } from './account.factory' + +export const createCommunity = (communityDraft: CommunityDraft, topic?: string): Community => { + const communityEntity = Community.create() + communityEntity.iotaTopic = topic ?? iotaTopicFromCommunityUUID(communityDraft.uuid) + communityEntity.createdAt = new Date(communityDraft.createdAt) + communityEntity.foreign = communityDraft.foreign + return communityEntity +} + +export const createHomeCommunity = (communityDraft: CommunityDraft, topic?: string): Community => { + // create community entity + const community = createCommunity(communityDraft, topic) + + // generate key pair for signing transactions and deriving all keys for community + const keyPair = KeyManager.generateKeyPair() + community.rootPubkey = keyPair.publicKey + community.rootPrivkey = keyPair.privateKey + community.rootChaincode = keyPair.chainCode + // we should only have one home community per server + KeyManager.getInstance().setHomeCommunityKeyPair(keyPair) + + // create auf account and gmw account + community.aufAccount = createAufAccount(keyPair, community.createdAt) + community.gmwAccount = createGmwAccount(keyPair, community.createdAt) + return community +} diff --git a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts new file mode 100644 index 000000000..401179d85 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -0,0 +1,40 @@ +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Field, Message } from 'protobufjs' +import { Community } from '@entity/Community' +import { Transaction } from '@entity/Transaction' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class CommunityRoot extends Message implements TransactionBase { + public constructor(community?: Community) { + if (community) { + super({ + rootPubkey: community.rootPubkey, + gmwPubkey: community.gmwAccount?.derive2Pubkey, + aufPubkey: community.aufAccount?.derive2Pubkey, + }) + } else { + super() + } + } + + @Field.d(1, 'bytes') + public rootPubkey: Buffer + + // community public budget account + @Field.d(2, 'bytes') + public gmwPubkey: Buffer + + // community compensation and environment founds account + @Field.d(3, 'bytes') + public aufPubkey: Buffer + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public validate(_level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars + public fillTransactionRecipe(recipe: Transaction): void {} +} diff --git a/dlt-connector/src/proto/3_3/GradidoConfirmedTransaction.ts b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts similarity index 67% rename from dlt-connector/src/proto/3_3/GradidoConfirmedTransaction.ts rename to dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts index 7f0a58109..ce88a54ae 100644 --- a/dlt-connector/src/proto/3_3/GradidoConfirmedTransaction.ts +++ b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts @@ -1,6 +1,8 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' import { GradidoTransaction } from './GradidoTransaction' import { TimestampSeconds } from './TimestampSeconds' +import { base64ToBuffer } from '@/utils/typeConverter' +import Long from 'long' /* id will be set by Node server @@ -10,9 +12,13 @@ import { TimestampSeconds } from './TimestampSeconds' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class GradidoConfirmedTransaction extends Message { +export class ConfirmedTransaction extends Message { + static fromBase64(base64: string): ConfirmedTransaction { + return ConfirmedTransaction.decode(new Uint8Array(base64ToBuffer(base64))) + } + @Field.d(1, 'uint64') - id: number + id: Long @Field.d(2, 'GradidoTransaction') transaction: GradidoTransaction diff --git a/dlt-connector/src/proto/3_3/GradidoCreation.test.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts similarity index 100% rename from dlt-connector/src/proto/3_3/GradidoCreation.test.ts rename to dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts new file mode 100644 index 000000000..354d40671 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -0,0 +1,53 @@ +import { Field, Message } from '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' +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Transaction } from '@entity/Transaction' +import Decimal from 'decimal.js-light' +import { Account } from '@entity/Account' + +// 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 implements TransactionBase { + constructor(transaction?: TransactionDraft, recipientAccount?: Account) { + if (transaction) { + if (!transaction.targetDate) { + throw new TransactionError( + TransactionErrorType.MISSING_PARAMETER, + 'missing targetDate for contribution', + ) + } + super({ + recipient: new TransferAmount({ + amount: transaction.amount.toString(), + pubkey: recipientAccount?.derive2Pubkey, + }), + targetDate: new TimestampSeconds(new Date(transaction.targetDate)), + }) + } else { + super() + } + } + + @Field.d(1, TransferAmount) + public recipient: TransferAmount + + @Field.d(3, 'TimestampSeconds') + public targetDate: TimestampSeconds + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public validate(level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + public fillTransactionRecipe(recipe: Transaction): void { + recipe.amount = new Decimal(this.recipient.amount ?? 0) + } +} diff --git a/dlt-connector/src/proto/3_3/GradidoDeferredTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts similarity index 65% rename from dlt-connector/src/proto/3_3/GradidoDeferredTransfer.ts rename to dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index 7b27c064a..4693df879 100644 --- a/dlt-connector/src/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -1,7 +1,11 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' import { GradidoTransfer } from './GradidoTransfer' import { TimestampSeconds } from './TimestampSeconds' +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Transaction } from '@entity/Transaction' +import Decimal from 'decimal.js-light' // transaction type for chargeable transactions // for transaction for people which haven't a account already @@ -10,8 +14,11 @@ import { TimestampSeconds } from './TimestampSeconds' // 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 { +export class GradidoDeferredTransfer + // eslint-disable-next-line no-use-before-define + extends Message + implements TransactionBase +{ // 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 @@ -28,4 +35,13 @@ export class GradidoDeferredTransfer extends Message { // split for n recipient // max gradido per recipient? or per transaction with cool down? + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public validate(level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + public fillTransactionRecipe(recipe: Transaction): void { + recipe.amount = new Decimal(this.transfer.sender.amount ?? 0) + } } diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts b/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts new file mode 100644 index 000000000..d4eea4836 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts @@ -0,0 +1,43 @@ +import { Field, Message } from 'protobufjs' + +import { SignatureMap } from './SignatureMap' +import { TransactionBody } from './TransactionBody' +import { SignaturePair } from './SignaturePair' +import { LogError } from '@/server/LogError' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class GradidoTransaction extends Message { + constructor(body?: TransactionBody) { + if (body) { + super({ + sigMap: new SignatureMap(), + bodyBytes: Buffer.from(TransactionBody.encode(body).finish()), + }) + } else { + super() + } + } + + @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 + + getFirstSignature(): SignaturePair { + const sigPair = this.sigMap.sigPair + if (sigPair.length !== 1) { + throw new LogError("signature count don't like expected") + } + return sigPair[0] + } +} diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts new file mode 100644 index 000000000..dadddedec --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -0,0 +1,48 @@ +import { Field, Message } from 'protobufjs' + +import { TransferAmount } from './TransferAmount' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Transaction } from '@entity/Transaction' +import Decimal from 'decimal.js-light' +import { Account } from '@entity/Account' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class GradidoTransfer extends Message implements TransactionBase { + constructor( + transaction?: TransactionDraft, + signingAccount?: Account, + recipientAccount?: Account, + coinOrigin?: string, + ) { + if (transaction) { + super({ + sender: new TransferAmount({ + amount: transaction.amount.toString(), + pubkey: signingAccount?.derive2Pubkey, + communityId: coinOrigin, + }), + recipient: recipientAccount?.derive2Pubkey, + }) + } else { + super() + } + } + + @Field.d(1, TransferAmount) + public sender: TransferAmount + + @Field.d(2, 'bytes') + public recipient: Buffer + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public validate(level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + public fillTransactionRecipe(recipe: Transaction): void { + recipe.amount = new Decimal(this.sender?.amount ?? 0) + } +} diff --git a/dlt-connector/src/proto/3_3/GroupFriendsUpdate.ts b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts similarity index 52% rename from dlt-connector/src/proto/3_3/GroupFriendsUpdate.ts rename to dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 64e74a694..3d6811331 100644 --- a/dlt-connector/src/proto/3_3/GroupFriendsUpdate.ts +++ b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts @@ -1,10 +1,14 @@ -import { Field, Message } from '@apollo/protobufjs' +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Field, Message } from 'protobufjs' +import { Transaction } from '@entity/Transaction' // 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 { +export class GroupFriendsUpdate extends Message implements TransactionBase { // 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, @@ -12,4 +16,12 @@ export class GroupFriendsUpdate extends Message { // (if fusion between src coin and dst coin is enabled) @Field.d(1, 'bool') public colorFusion: boolean + + public validate(level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + public fillTransactionRecipe(recipe: Transaction): void { + throw new Error('Method not implemented.') + } } diff --git a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts new file mode 100644 index 000000000..f9eead762 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -0,0 +1,33 @@ +/* eslint-disable @typescript-eslint/no-empty-function */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { Field, Message } from 'protobufjs' + +import { AddressType } from '@/data/proto/3_3/enum/AddressType' +import { TransactionBase } from '../TransactionBase' +import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Transaction } from '@entity/Transaction' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class RegisterAddress extends Message implements TransactionBase { + @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 accountPubkey: Buffer + + @Field.d(5, 'uint32') + public derivationIndex?: number + + public validate(level: TransactionValidationLevel): boolean { + throw new Error('Method not implemented.') + } + + public fillTransactionRecipe(_recipe: Transaction): void {} +} diff --git a/dlt-connector/src/proto/3_3/SignatureMap.ts b/dlt-connector/src/data/proto/3_3/SignatureMap.ts similarity index 66% rename from dlt-connector/src/proto/3_3/SignatureMap.ts rename to dlt-connector/src/data/proto/3_3/SignatureMap.ts index e48b0232d..daf69f05f 100644 --- a/dlt-connector/src/proto/3_3/SignatureMap.ts +++ b/dlt-connector/src/data/proto/3_3/SignatureMap.ts @@ -1,10 +1,14 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from '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 { + constructor() { + super({ sigPair: [] }) + } + @Field.d(1, SignaturePair, 'repeated') - public sigPair: SignaturePair + public sigPair: SignaturePair[] } diff --git a/dlt-connector/src/proto/3_3/SignaturePair.ts b/dlt-connector/src/data/proto/3_3/SignaturePair.ts similarity index 63% rename from dlt-connector/src/proto/3_3/SignaturePair.ts rename to dlt-connector/src/data/proto/3_3/SignaturePair.ts index 07ed4cc55..80a61a871 100644 --- a/dlt-connector/src/proto/3_3/SignaturePair.ts +++ b/dlt-connector/src/data/proto/3_3/SignaturePair.ts @@ -1,4 +1,4 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -8,4 +8,8 @@ export class SignaturePair extends Message { @Field.d(2, 'bytes') public signature: Buffer + + public validate(): boolean { + return this.pubKey.length === 32 && this.signature.length === 64 + } } diff --git a/dlt-connector/src/proto/3_3/Timestamp.test.ts b/dlt-connector/src/data/proto/3_3/Timestamp.test.ts similarity index 100% rename from dlt-connector/src/proto/3_3/Timestamp.test.ts rename to dlt-connector/src/data/proto/3_3/Timestamp.test.ts diff --git a/dlt-connector/src/proto/3_3/Timestamp.ts b/dlt-connector/src/data/proto/3_3/Timestamp.ts similarity index 94% rename from dlt-connector/src/proto/3_3/Timestamp.ts rename to dlt-connector/src/data/proto/3_3/Timestamp.ts index ab060a9bc..91cf06581 100644 --- a/dlt-connector/src/proto/3_3/Timestamp.ts +++ b/dlt-connector/src/data/proto/3_3/Timestamp.ts @@ -1,4 +1,4 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define diff --git a/dlt-connector/src/proto/3_3/TimestampSeconds.test.ts b/dlt-connector/src/data/proto/3_3/TimestampSeconds.test.ts similarity index 100% rename from dlt-connector/src/proto/3_3/TimestampSeconds.test.ts rename to dlt-connector/src/data/proto/3_3/TimestampSeconds.test.ts diff --git a/dlt-connector/src/proto/3_3/TimestampSeconds.ts b/dlt-connector/src/data/proto/3_3/TimestampSeconds.ts similarity index 91% rename from dlt-connector/src/proto/3_3/TimestampSeconds.ts rename to dlt-connector/src/data/proto/3_3/TimestampSeconds.ts index 055094c6d..6d175c6f3 100644 --- a/dlt-connector/src/proto/3_3/TimestampSeconds.ts +++ b/dlt-connector/src/data/proto/3_3/TimestampSeconds.ts @@ -1,4 +1,4 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts new file mode 100644 index 000000000..8bfbf955f --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -0,0 +1,129 @@ +import { Field, Message, OneOf } from 'protobufjs' + +import { CrossGroupType } from './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 '../transactionBody.logic' +import { CommunityRoot } from './CommunityRoot' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionType } from '@/graphql/enum/TransactionType' +import { TransactionBase } from '../TransactionBase' +import { Transaction } from '@entity/Transaction' +import { timestampToDate } from '@/utils/typeConverter' +import { LogError } from '@/server/LogError' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class TransactionBody extends Message { + public constructor(transaction?: TransactionDraft | CommunityDraft) { + if (transaction) { + let type = CrossGroupType.LOCAL + let otherGroup = '' + if (transaction instanceof TransactionDraft) { + type = determineCrossGroupType(transaction) + otherGroup = determineOtherGroup(type, transaction) + } + + super({ + memo: 'Not implemented yet', + createdAt: new Timestamp(new Date(transaction.createdAt)), + versionNumber: '3.3', + type, + otherGroup, + }) + } else { + super() + } + } + + @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', + 'communityRoot', + ) + 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 + + @Field.d(11, 'CommunityRoot') + communityRoot?: CommunityRoot + + public getTransactionType(): TransactionType | undefined { + if (this.transfer) return TransactionType.GRADIDO_TRANSFER + else if (this.creation) return TransactionType.GRADIDO_CREATION + else if (this.groupFriendsUpdate) return TransactionType.GROUP_FRIENDS_UPDATE + else if (this.registerAddress) return TransactionType.REGISTER_ADDRESS + else if (this.deferredTransfer) return TransactionType.GRADIDO_DEFERRED_TRANSFER + else if (this.communityRoot) return TransactionType.COMMUNITY_ROOT + } + + public getTransactionBase(): TransactionBase | undefined { + if (this.transfer) return this.transfer + if (this.creation) return this.creation + if (this.groupFriendsUpdate) return this.groupFriendsUpdate + if (this.registerAddress) return this.registerAddress + if (this.deferredTransfer) return this.deferredTransfer + if (this.communityRoot) return this.communityRoot + } + + public fillTransactionRecipe(recipe: Transaction): void { + recipe.createdAt = timestampToDate(this.createdAt) + recipe.protocolVersion = this.versionNumber + const transactionType = this.getTransactionType() + if (!transactionType) { + throw new LogError("invalid TransactionBody couldn't determine transaction type") + } + recipe.type = transactionType.valueOf() + this.getTransactionBase()?.fillTransactionRecipe(recipe) + } + + public getRecipientPublicKey(): Buffer | undefined { + if (this.transfer) { + return this.transfer.recipient + } + if (this.creation) { + return this.creation.recipient.pubkey + } + if (this.deferredTransfer) { + return this.deferredTransfer.transfer.recipient + } + return undefined + } +} diff --git a/dlt-connector/src/proto/3_3/TransferAmount.ts b/dlt-connector/src/data/proto/3_3/TransferAmount.ts similarity index 88% rename from dlt-connector/src/proto/3_3/TransferAmount.ts rename to dlt-connector/src/data/proto/3_3/TransferAmount.ts index f6adc47ff..42da65256 100644 --- a/dlt-connector/src/proto/3_3/TransferAmount.ts +++ b/dlt-connector/src/data/proto/3_3/TransferAmount.ts @@ -1,4 +1,4 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define diff --git a/dlt-connector/src/data/proto/3_3/enum/AddressType.ts b/dlt-connector/src/data/proto/3_3/enum/AddressType.ts new file mode 100644 index 000000000..49fcf0c4e --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/enum/AddressType.ts @@ -0,0 +1,19 @@ +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 +} + +export function getAddressTypeEnumValue(typeString: string): AddressType | undefined { + // Iterate through all enum values + for (const key in AddressType) { + if (AddressType[key] === typeString) { + return AddressType[key] as unknown as AddressType + } + } + return undefined // If the string is not found +} diff --git a/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts b/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts new file mode 100644 index 000000000..13e968509 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts @@ -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, +} diff --git a/dlt-connector/src/controller/TransactionBase.ts b/dlt-connector/src/data/proto/TransactionBase.ts similarity index 73% rename from dlt-connector/src/controller/TransactionBase.ts rename to dlt-connector/src/data/proto/TransactionBase.ts index 9833226a9..e04b3435e 100644 --- a/dlt-connector/src/controller/TransactionBase.ts +++ b/dlt-connector/src/data/proto/TransactionBase.ts @@ -1,6 +1,9 @@ import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Transaction } from '@entity/Transaction' 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 + + public abstract fillTransactionRecipe(recipe: Transaction): void } diff --git a/dlt-connector/src/data/proto/TransactionBody.builder.ts b/dlt-connector/src/data/proto/TransactionBody.builder.ts new file mode 100644 index 000000000..5f2681824 --- /dev/null +++ b/dlt-connector/src/data/proto/TransactionBody.builder.ts @@ -0,0 +1,95 @@ +import { TransactionBody } from './3_3/TransactionBody' +import { Account } from '@entity/Account' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { InputTransactionType } from '@/graphql/enum/InputTransactionType' +import { GradidoCreation } from './3_3/GradidoCreation' +import { GradidoTransfer } from './3_3/GradidoTransfer' +import { Community } from '@entity/Community' +import { CommunityRoot } from './3_3/CommunityRoot' +import { LogError } from '@/server/LogError' + +export class TransactionBodyBuilder { + private signingAccount?: Account + private recipientAccount?: Account + private body: TransactionBody | undefined + + // https://refactoring.guru/design-patterns/builder/typescript/example + /** + * A fresh builder instance should contain a blank product object, which is + * used in further assembly. + */ + constructor() { + this.reset() + } + + public reset(): void { + this.body = undefined + } + + /** + * Concrete Builders are supposed to provide their own methods for + * retrieving results. That's because various types of builders may create + * entirely different products that don't follow the same interface. + * Therefore, such methods cannot be declared in the base Builder interface + * (at least in a statically typed programming language). + * + * Usually, after returning the end result to the client, a builder instance + * is expected to be ready to start producing another product. That's why + * it's a usual practice to call the reset method at the end of the + * `getProduct` method body. However, this behavior is not mandatory, and + * you can make your builders wait for an explicit reset call from the + * client code before disposing of the previous result. + */ + public build(): TransactionBody { + const result = this.body + if (!result) { + throw new LogError( + 'cannot build Transaction Body, missing information, please call at least fromTransactionDraft or fromCommunityDraft', + ) + } + this.reset() + return result + } + + public setSigningAccount(signingAccount: Account): TransactionBodyBuilder { + this.signingAccount = signingAccount + return this + } + + public setRecipientAccount(recipientAccount: Account): TransactionBodyBuilder { + this.recipientAccount = recipientAccount + return this + } + + public fromTransactionDraft(transactionDraft: TransactionDraft): TransactionBodyBuilder { + this.body = new TransactionBody(transactionDraft) + // TODO: load pubkeys for sender and recipient user from db + switch (transactionDraft.type) { + case InputTransactionType.CREATION: + this.body.creation = new GradidoCreation(transactionDraft, this.recipientAccount) + this.body.data = 'gradidoCreation' + break + case InputTransactionType.SEND: + case InputTransactionType.RECEIVE: + this.body.transfer = new GradidoTransfer( + transactionDraft, + this.signingAccount, + this.recipientAccount, + ) + this.body.data = 'gradidoTransfer' + break + } + return this + } + + public fromCommunityDraft( + communityDraft: CommunityDraft, + community: Community, + ): TransactionBodyBuilder { + this.body = new TransactionBody(communityDraft) + this.body.communityRoot = new CommunityRoot(community) + this.body.data = 'communityRoot' + return this + } +} diff --git a/dlt-connector/src/controller/TransactionBody.ts b/dlt-connector/src/data/proto/transactionBody.logic.ts similarity index 60% rename from dlt-connector/src/controller/TransactionBody.ts rename to dlt-connector/src/data/proto/transactionBody.logic.ts index ae5f37710..872172aac 100644 --- a/dlt-connector/src/controller/TransactionBody.ts +++ b/dlt-connector/src/data/proto/transactionBody.logic.ts @@ -1,28 +1,8 @@ -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 { CrossGroupType } from './3_3/enum/CrossGroupType' +import { InputTransactionType } from '@/graphql/enum/InputTransactionType' 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 -} +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' export const determineCrossGroupType = ({ senderUser, @@ -33,12 +13,12 @@ export const determineCrossGroupType = ({ !recipientUser.communityUuid || recipientUser.communityUuid === '' || senderUser.communityUuid === recipientUser.communityUuid || - type === TransactionType.CREATION + type === InputTransactionType.CREATION ) { return CrossGroupType.LOCAL - } else if (type === TransactionType.SEND) { + } else if (type === InputTransactionType.SEND) { return CrossGroupType.INBOUND - } else if (type === TransactionType.RECEIVE) { + } else if (type === InputTransactionType.RECEIVE) { return CrossGroupType.OUTBOUND } throw new TransactionError( diff --git a/dlt-connector/src/graphql/arg/CommunityArg.ts b/dlt-connector/src/graphql/arg/CommunityArg.ts new file mode 100644 index 000000000..59f65943e --- /dev/null +++ b/dlt-connector/src/graphql/arg/CommunityArg.ts @@ -0,0 +1,19 @@ +// https://www.npmjs.com/package/@apollo/protobufjs + +import { IsBoolean, IsUUID } from 'class-validator' +import { ArgsType, Field } from 'type-graphql' + +@ArgsType() +export class CommunityArg { + @Field(() => String, { nullable: true }) + @IsUUID('4') + uuid?: string + + @Field(() => Boolean, { nullable: true }) + @IsBoolean() + foreign?: boolean + + @Field(() => Boolean, { nullable: true }) + @IsBoolean() + confirmed?: boolean +} diff --git a/dlt-connector/src/graphql/enum/InputTransactionType.ts b/dlt-connector/src/graphql/enum/InputTransactionType.ts new file mode 100755 index 000000000..06d1bb44b --- /dev/null +++ b/dlt-connector/src/graphql/enum/InputTransactionType.ts @@ -0,0 +1,12 @@ +import { registerEnumType } from 'type-graphql' + +export enum InputTransactionType { + CREATION = 1, + SEND = 2, + RECEIVE = 3, +} + +registerEnumType(InputTransactionType, { + name: 'InputTransactionType', // this one is mandatory + description: 'Type of the transaction', // this one is optional +}) diff --git a/dlt-connector/src/graphql/enum/TransactionErrorType.ts b/dlt-connector/src/graphql/enum/TransactionErrorType.ts index 0e72292c1..7f1902c3d 100644 --- a/dlt-connector/src/graphql/enum/TransactionErrorType.ts +++ b/dlt-connector/src/graphql/enum/TransactionErrorType.ts @@ -5,6 +5,8 @@ export enum TransactionErrorType { MISSING_PARAMETER = 'Missing parameter', ALREADY_EXIST = 'Already exist', DB_ERROR = 'DB Error', + PROTO_DECODE_ERROR = 'Proto Decode Error', + PROTO_ENCODE_ERROR = 'Proto Encode Error', } registerEnumType(TransactionErrorType, { diff --git a/dlt-connector/src/graphql/enum/TransactionType.ts b/dlt-connector/src/graphql/enum/TransactionType.ts old mode 100755 new mode 100644 index aaa5bf92e..3647b9ca8 --- a/dlt-connector/src/graphql/enum/TransactionType.ts +++ b/dlt-connector/src/graphql/enum/TransactionType.ts @@ -1,12 +1,15 @@ -import { registerEnumType } from 'type-graphql' - -export enum TransactionType { - CREATION = 1, - SEND = 2, - RECEIVE = 3, -} - -registerEnumType(TransactionType, { - name: 'TransactionType', // this one is mandatory - description: 'Type of the transaction', // this one is optional -}) +import { registerEnumType } from 'type-graphql' + +export enum TransactionType { + GRADIDO_TRANSFER = 1, + GRADIDO_CREATION = 2, + GROUP_FRIENDS_UPDATE = 3, + REGISTER_ADDRESS = 4, + GRADIDO_DEFERRED_TRANSFER = 5, + COMMUNITY_ROOT = 6, +} + +registerEnumType(TransactionType, { + name: 'TransactionType', // this one is mandatory + description: 'Type of the transaction', // this one is optional +}) diff --git a/dlt-connector/src/graphql/input/TransactionDraft.ts b/dlt-connector/src/graphql/input/TransactionDraft.ts index 2021dd9e1..a94c57354 100755 --- a/dlt-connector/src/graphql/input/TransactionDraft.ts +++ b/dlt-connector/src/graphql/input/TransactionDraft.ts @@ -1,7 +1,7 @@ // https://www.npmjs.com/package/@apollo/protobufjs import { Decimal } from 'decimal.js-light' -import { TransactionType } from '@enum/TransactionType' +import { InputTransactionType } from '@enum/InputTransactionType' import { InputType, Field } from 'type-graphql' import { UserIdentifier } from './UserIdentifier' import { isValidDateString } from '@validator/DateString' @@ -24,9 +24,9 @@ export class TransactionDraft { @IsPositiveDecimal() amount: Decimal - @Field(() => TransactionType) - @IsEnum(TransactionType) - type: TransactionType + @Field(() => InputTransactionType) + @IsEnum(InputTransactionType) + type: InputTransactionType @Field(() => String) @isValidDateString() diff --git a/dlt-connector/src/graphql/model/Community.ts b/dlt-connector/src/graphql/model/Community.ts new file mode 100644 index 000000000..214984f15 --- /dev/null +++ b/dlt-connector/src/graphql/model/Community.ts @@ -0,0 +1,36 @@ +import { ObjectType, Field, Int } from 'type-graphql' +import { Community as CommunityEntity } from '@entity/Community' + +@ObjectType() +export class Community { + constructor(entity: CommunityEntity) { + this.id = entity.id + this.iotaTopic = entity.iotaTopic + if (entity.rootPubkey) { + this.rootPublicKeyHex = entity.rootPubkey?.toString('hex') + } + this.foreign = entity.foreign + this.createdAt = entity.createdAt.toString() + if (entity.confirmedAt) { + this.confirmedAt = entity.confirmedAt.toString() + } + } + + @Field(() => Int) + id: number + + @Field(() => String) + iotaTopic: string + + @Field(() => String) + rootPublicKeyHex?: string + + @Field(() => Boolean) + foreign: boolean + + @Field(() => String) + createdAt: string + + @Field(() => String) + confirmedAt?: string +} diff --git a/dlt-connector/src/graphql/model/TransactionRecipe.ts b/dlt-connector/src/graphql/model/TransactionRecipe.ts new file mode 100644 index 000000000..e5e1c74fc --- /dev/null +++ b/dlt-connector/src/graphql/model/TransactionRecipe.ts @@ -0,0 +1,25 @@ +import { Field, Int, ObjectType } from 'type-graphql' +import { TransactionRecipe as TransactionRecipeEntity } from '@entity/TransactionRecipe' +import { TransactionType } from '@enum/TransactionType' + +@ObjectType() +export class TransactionRecipe { + public constructor({ id, createdAt, type, senderCommunity }: TransactionRecipeEntity) { + this.id = id + this.createdAt = createdAt.toString() + this.type = type + this.topic = senderCommunity.iotaTopic + } + + @Field(() => Int) + id: number + + @Field(() => String) + createdAt: string + + @Field(() => TransactionType) + type: TransactionType + + @Field(() => String) + topic: string +} diff --git a/dlt-connector/src/graphql/model/TransactionResult.ts b/dlt-connector/src/graphql/model/TransactionResult.ts index 938c8bcf6..dfa28cf1b 100644 --- a/dlt-connector/src/graphql/model/TransactionResult.ts +++ b/dlt-connector/src/graphql/model/TransactionResult.ts @@ -1,15 +1,16 @@ import { ObjectType, Field } from 'type-graphql' import { TransactionError } from './TransactionError' +import { TransactionRecipe } from './TransactionRecipe' @ObjectType() export class TransactionResult { - constructor(content?: TransactionError | string) { + constructor(content?: TransactionError | TransactionRecipe) { this.succeed = true if (content instanceof TransactionError) { this.error = content this.succeed = false - } else if (typeof content === 'string') { - this.messageId = content + } else if (content instanceof TransactionRecipe) { + this.recipe = content } } @@ -18,9 +19,9 @@ export class TransactionResult { error?: TransactionError // if no error happend, the message id of the iota transaction - @Field(() => String, { nullable: true }) - messageId?: string + @Field(() => TransactionRecipe, { nullable: true }) + recipe?: TransactionRecipe @Field(() => Boolean) succeed: boolean -} +} \ No newline at end of file diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.ts index d6f9f2d46..43a871dd8 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.ts @@ -1,53 +1,59 @@ -import { Resolver, Arg, Mutation } from 'type-graphql' +import { Resolver, Query, Arg, Mutation, Args } from 'type-graphql' import { CommunityDraft } from '@input/CommunityDraft' -import { TransactionResult } from '../model/TransactionResult' -import { TransactionError } from '../model/TransactionError' -import { create as createCommunity, isExist } from '@/controller/Community' -import { TransactionErrorType } from '../enum/TransactionErrorType' -import { logger } from '@/server/logger' +import { TransactionResult } from '@model/TransactionResult' +import { TransactionError } from '@model/TransactionError' +import { TransactionErrorType } from '@enum/TransactionErrorType' import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' +import { Community } from '@model/Community' +import { CommunityArg } from '@arg/CommunityArg' +import { LogError } from '@/server/LogError' +import { logger } from '@/server/logger' +import { CommunityRepository } from '@/data/Community.repository' +import { addCommunity } from '@/interactions/backendToDb/community/community.context' @Resolver() export class CommunityResolver { + @Query(() => Community) + async community(@Args() communityArg: CommunityArg): Promise { + logger.info('community', communityArg) + const result = await CommunityRepository.findByCommunityArg(communityArg) + if (result.length === 0) { + throw new LogError('cannot find community') + } else if (result.length === 1) { + return new Community(result[0]) + } else { + throw new LogError('find multiple communities') + } + } + + @Query(() => Boolean) + async isCommunityExist(@Args() communityArg: CommunityArg): Promise { + logger.info('isCommunity', communityArg) + return (await CommunityRepository.findByCommunityArg(communityArg)).length === 1 + } + + @Query(() => [Community]) + async communities(@Args() communityArg: CommunityArg): Promise { + logger.info('communities', communityArg) + const result = await CommunityRepository.findByCommunityArg(communityArg) + return result.map((communityEntity) => new Community(communityEntity)) + } + @Mutation(() => TransactionResult) async addCommunity( @Arg('data') communityDraft: CommunityDraft, ): Promise { - try { - const topic = iotaTopicFromCommunityUUID(communityDraft.uuid) - - // check if community was already written to db - if (await isExist(topic)) { - return new TransactionResult( - new TransactionError(TransactionErrorType.ALREADY_EXIST, 'community already exist!'), - ) - } - const community = createCommunity(communityDraft, topic) - - let result: TransactionResult - - if (!communityDraft.foreign) { - // TODO: CommunityRoot Transaction for blockchain - } - try { - await community.save() - result = new TransactionResult() - } catch (err) { - logger.error('error saving new community into db: %s', err) - result = new TransactionResult( - new TransactionError(TransactionErrorType.DB_ERROR, 'error saving community into db'), - ) - } - return result - } catch (error) { - if (error instanceof TransactionError) { - return new TransactionResult(error) - } else { - throw error - } + logger.info('addCommunity', communityDraft) + const topic = iotaTopicFromCommunityUUID(communityDraft.uuid) + // check if community was already written to db + if (await CommunityRepository.isExist(topic)) { + return new TransactionResult( + new TransactionError(TransactionErrorType.ALREADY_EXIST, 'community already exist!'), + ) } + return await addCommunity(communityDraft, topic) } } diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts index 282eb11cd..96f6dff65 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -1,12 +1,5 @@ import { Resolver, Query, Arg, Mutation } from 'type-graphql' - 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' @@ -29,11 +22,68 @@ export class TransactionResolver { transaction: TransactionDraft, ): Promise { 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) + logger.info('sendTransaction call', transaction) + const signingAccount = await findAccountByUserIdentifier(transaction.senderUser) + if (!signingAccount) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found sender user account in db", + ) + } + logger.info('signing account', signingAccount) + + const recipientAccount = await findAccountByUserIdentifier(transaction.recipientUser) + if (!recipientAccount) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found recipient user account in db", + ) + } + logger.info('recipient account', recipientAccount) + + const body = createTransactionBody(transaction, signingAccount, recipientAccount) + logger.info('body', body) + const gradidoTransaction = createGradidoTransaction(body) + + const signingKeyPair = getKeyPair(signingAccount) + if (!signingKeyPair) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found signing key pair", + ) + } + logger.info('key pair for signing', signingKeyPair) + + KeyManager.getInstance().sign(gradidoTransaction, [signingKeyPair]) + const recipeTransactionController = await TransactionRecipe.create({ + transaction: gradidoTransaction, + senderUser: transaction.senderUser, + recipientUser: transaction.recipientUser, + signingAccount, + recipientAccount, + backendTransactionId: transaction.backendTransactionId, + }) + try { + await recipeTransactionController.getTransactionRecipeEntity().save() + ConditionalSleepManager.getInstance().signal(TRANSMIT_TO_IOTA_SLEEP_CONDITION_KEY) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (error: any) { + if (error.code === 'ER_DUP_ENTRY' && body.type === CrossGroupType.LOCAL) { + const existingRecipe = await findBySignature( + gradidoTransaction.sigMap.sigPair[0].signature, + ) + if (!existingRecipe) { + throw new TransactionError( + TransactionErrorType.LOGIC_ERROR, + "recipe cannot be added because signature exist but couldn't load this existing receipt", + ) + } + return new TransactionResult(new TransactionRecipeOutput(existingRecipe)) + } else { + throw error + } + } + return new TransactionResult() } catch (error) { if (error instanceof TransactionError) { return new TransactionResult(error) diff --git a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts new file mode 100644 index 000000000..144d3bc5c --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts @@ -0,0 +1,6 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' + +export abstract class CommunityRole { + abstract addCommunity(communityDraft: CommunityDraft, topic: string): Promise +} diff --git a/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts new file mode 100644 index 000000000..76af3026c --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts @@ -0,0 +1,19 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' +import { CommunityRole } from './Community.role' +import { logger } from '@/server/logger' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { createCommunity } from '@/data/community.factory' + +export class ForeignCommunityRole extends CommunityRole { + addCommunity(communityDraft: CommunityDraft, topic: string): Promise { + const community = createCommunity(communityDraft, topic) + try { + return community.save() + } catch (error) { + logger.error('error saving new foreign community into db: %s', error) + throw new TransactionError(TransactionErrorType.DB_ERROR, 'error saving community into db') + } + } +} diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts new file mode 100644 index 000000000..df670398f --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -0,0 +1,28 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' +import { CommunityRole } from './Community.role' +import { getTransaction } from '@/client/GradidoNode' +import { timestampSecondsToDate } from '@/utils/typeConverter' +import { createHomeCommunity } from '@/data/community.factory' +import { createCommunityRootTransactionRecipe } from '../transaction/transaction.context' +import { QueryRunner } from 'typeorm' + +export class HomeCommunityRole extends CommunityRole { + public async addCommunity(communityDraft: CommunityDraft, topic: string): Promise { + const community = createHomeCommunity(communityDraft, topic) + + // check if a CommunityRoot Transaction exist already on iota blockchain + const existingCommunityRootTransaction = await getTransaction(1, community.iotaTopic) + if (existingCommunityRootTransaction) { + community.confirmedAt = timestampSecondsToDate(existingCommunityRootTransaction.confirmedAt) + return community.save() + } else { + createCommunityRootTransactionRecipe(communityDraft, community).storeAsTransaction( + async (queryRunner: QueryRunner): Promise => { + await queryRunner.manager.save(community) + }, + ) + } + return community.save() + } +} diff --git a/dlt-connector/src/interactions/backendToDb/community/community.context.ts b/dlt-connector/src/interactions/backendToDb/community/community.context.ts new file mode 100644 index 000000000..cd55599bf --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/community.context.ts @@ -0,0 +1,30 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionResult } from '@/graphql/model/TransactionResult' +import { ForeignCommunityRole } from './ForeignCommunity.role' +import { HomeCommunityRole } from './HomeCommunity.role' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionsManager } from '@/controller/TransactionsManager' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' + +export const addCommunity = async ( + communityDraft: CommunityDraft, + iotaTopic?: string, +): Promise => { + const communityRole = communityDraft.foreign + ? new ForeignCommunityRole() + : new HomeCommunityRole() + try { + if (!iotaTopic) { + iotaTopic = iotaTopicFromCommunityUUID(communityDraft.uuid) + } + await communityRole.addCommunity(communityDraft, iotaTopic) + await TransactionsManager.getInstance().addTopic(iotaTopic) + return new TransactionResult() + } catch (error) { + if (error instanceof TransactionError) { + return new TransactionResult(error) + } else { + throw error + } + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts new file mode 100644 index 000000000..3bce63461 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts @@ -0,0 +1,24 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionRecipeRole } from './TransactionRecipe.role' +import { Community } from '@entity/Community' +import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' +import { KeyPair } from '@/data/KeyPair' +import { sign } from '@/utils/cryptoHelper' + +export class CommunityRootTransactionRole extends TransactionRecipeRole { + public createFromCommunityDraft( + communityDraft: CommunityDraft, + community: Community, + ): CommunityRootTransactionRole { + // create proto transaction body + const transactionBody = new TransactionBodyBuilder() + .fromCommunityDraft(communityDraft, community) + .build() + // build transaction entity + this.transactionBuilder.fromTransactionBody(transactionBody).setSenderCommunity(community) + const transaction = this.transactionBuilder.getTransaction() + // sign + this.transactionBuilder.setSignature(sign(transaction.bodyBytes, new KeyPair(community))) + return this + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts new file mode 100644 index 000000000..0ab41f0d4 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -0,0 +1,49 @@ +import { TransactionBuilder } from '@/data/Transaction.builder' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionRecipe } from '@/graphql/model/TransactionRecipe' +import { TransactionResult } from '@/graphql/model/TransactionResult' +import { logger } from '@/server/logger' +import { getDataSource } from '@/typeorm/DataSource' +import { QueryRunner } from 'typeorm' + +export class TransactionRecipeRole { + protected transactionBuilder: TransactionBuilder + construct() { + this.transactionBuilder = new TransactionBuilder() + } + + public createFromTransactionDraft(transactionDraft: TransactionDraft): TransactionRecipeRole { + return this + } + + public async storeAsTransaction( + transactionFunction: (queryRunner: QueryRunner) => Promise, + ): Promise { + const queryRunner = getDataSource().createQueryRunner() + await queryRunner.connect() + await queryRunner.startTransaction() + + let result: TransactionResult + try { + const transactionRecipe = this.transactionBuilder.build() + await transactionFunction(queryRunner) + await queryRunner.manager.save(transactionRecipe) + await queryRunner.commitTransaction() + result = new TransactionResult(new TransactionRecipe(transactionRecipe)) + } catch (err) { + logger.error('error saving new transaction recipe into db: %s', err) + result = new TransactionResult( + new TransactionError( + TransactionErrorType.DB_ERROR, + 'error saving transaction recipe into db', + ), + ) + await queryRunner.rollbackTransaction() + } finally { + await queryRunner.release() + } + return result + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts new file mode 100644 index 000000000..5c8bda04f --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts @@ -0,0 +1,20 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' +import { TransactionRecipeRole } from './TransactionRecipe.role' +import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' + +export const createCommunityRootTransactionRecipe = ( + communityDraft: CommunityDraft, + community: Community, +): TransactionRecipeRole => { + const communityRootTransactionRole = new CommunityRootTransactionRole() + return communityRootTransactionRole.createFromCommunityDraft(communityDraft, community) +} + +export const createTransactionRecipe = ( + transactionDraft: TransactionDraft, +): TransactionRecipeRole => { + const transactionRecipeRole = new TransactionRecipeRole() + return transactionRecipeRole.createFromTransactionDraft(transactionDraft) +} diff --git a/dlt-connector/src/proto/3_3/GradidoCreation.ts b/dlt-connector/src/proto/3_3/GradidoCreation.ts deleted file mode 100644 index ba6e93652..000000000 --- a/dlt-connector/src/proto/3_3/GradidoCreation.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 { - 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 -} diff --git a/dlt-connector/src/proto/3_3/GradidoTransaction.ts b/dlt-connector/src/proto/3_3/GradidoTransaction.ts deleted file mode 100644 index ca1a59e30..000000000 --- a/dlt-connector/src/proto/3_3/GradidoTransaction.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 { - @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 -} diff --git a/dlt-connector/src/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/proto/3_3/GradidoTransfer.ts deleted file mode 100644 index 215ffc60f..000000000 --- a/dlt-connector/src/proto/3_3/GradidoTransfer.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 { - 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 -} diff --git a/dlt-connector/src/proto/3_3/RegisterAddress.ts b/dlt-connector/src/proto/3_3/RegisterAddress.ts deleted file mode 100644 index 85b8390df..000000000 --- a/dlt-connector/src/proto/3_3/RegisterAddress.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 { - @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 -} diff --git a/dlt-connector/src/proto/3_3/TransactionBody.ts b/dlt-connector/src/proto/3_3/TransactionBody.ts deleted file mode 100644 index 9e9179b3f..000000000 --- a/dlt-connector/src/proto/3_3/TransactionBody.ts +++ /dev/null @@ -1,66 +0,0 @@ -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 { - 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 -} diff --git a/dlt-connector/src/utils/cryptoHelper.ts b/dlt-connector/src/utils/cryptoHelper.ts new file mode 100644 index 000000000..1eb5db36d --- /dev/null +++ b/dlt-connector/src/utils/cryptoHelper.ts @@ -0,0 +1,6 @@ +import { KeyPair } from '@/data/KeyPair' +import { sign as ed25519Sign } from 'bip32-ed25519' + +export const sign = (message: Buffer, keyPair: KeyPair): Buffer => { + return ed25519Sign(message, keyPair.getExtendPrivateKey()) +} diff --git a/dlt-connector/src/utils/derivationHelper.test.ts b/dlt-connector/src/utils/derivationHelper.test.ts new file mode 100644 index 000000000..0ad381aa8 --- /dev/null +++ b/dlt-connector/src/utils/derivationHelper.test.ts @@ -0,0 +1,15 @@ +import 'reflect-metadata' +import { Timestamp } from '../data/proto/3_3/Timestamp' +import { hardenDerivationIndex, HARDENED_KEY_BITMASK } from './derivationHelper' +import { timestampToDate } from './typeConverter' + +describe('utils', () => { + it('test bitmask for hardened keys', () => { + const derivationIndex = hardenDerivationIndex(1) + expect(derivationIndex).toBeGreaterThan(HARDENED_KEY_BITMASK) + }) + it('test TimestampToDate', () => { + const date = new Date('2011-04-17T12:01:10.109') + expect(timestampToDate(new Timestamp(date))).toEqual(date) + }) +}) diff --git a/dlt-connector/src/utils/derivationHelper.ts b/dlt-connector/src/utils/derivationHelper.ts new file mode 100644 index 000000000..0431ec339 --- /dev/null +++ b/dlt-connector/src/utils/derivationHelper.ts @@ -0,0 +1,17 @@ +export const HARDENED_KEY_BITMASK = 0x80000000 + +/* + * change derivation index from x => x' + * for more infos to hardened keys look here: + * https://en.bitcoin.it/wiki/BIP_0032 + */ +export const hardenDerivationIndex = (derivationIndex: number): number => { + /* + TypeScript uses signed integers by default, + but bip32-ed25519 expects an unsigned value for the derivation index. + The >>> shifts the bits 0 places to the right, which effectively makes no change to the value, + but forces TypeScript to treat derivationIndex as an unsigned value. + Source: ChatGPT + */ + return (derivationIndex | HARDENED_KEY_BITMASK) >>> 0 +} diff --git a/dlt-connector/src/utils/typeConverter.test.ts b/dlt-connector/src/utils/typeConverter.test.ts new file mode 100644 index 000000000..03863d0f2 --- /dev/null +++ b/dlt-connector/src/utils/typeConverter.test.ts @@ -0,0 +1,12 @@ +import 'reflect-metadata' +import { Timestamp } from '@/data/proto/3_3/Timestamp' +import { timestampToDate } from './typeConverter' + +describe('utils/typeConverter', () => { + it('timestampToDate', () => { + const now = new Date('Thu, 05 Oct 2023 11:55:18 +0000') + const timestamp = new Timestamp(now) + expect(timestamp.seconds).toBe(Math.round(now.getTime() / 1000)) + expect(timestampToDate(timestamp)).toEqual(now) + }) +}) diff --git a/dlt-connector/src/utils/typeConverter.ts b/dlt-connector/src/utils/typeConverter.ts index bd9e5f8da..15d4e8826 100644 --- a/dlt-connector/src/utils/typeConverter.ts +++ b/dlt-connector/src/utils/typeConverter.ts @@ -1,5 +1,12 @@ import { crypto_generichash as cryptoHash } from 'sodium-native' +import { Timestamp } from '@/data/proto/3_3/Timestamp' +import { TimestampSeconds } from '@/data/proto/3_3/TimestampSeconds' +import { TransactionBody } from '@/data/proto/3_3/TransactionBody' +import { logger } from '@/server/logger' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' + export const uuid4ToBuffer = (uuid: string): Buffer => { // Remove dashes from the UUIDv4 string const cleanedUUID = uuid.replace(/-/g, '') @@ -15,3 +22,41 @@ export const iotaTopicFromCommunityUUID = (communityUUID: string): string => { cryptoHash(hash, uuid4ToBuffer(communityUUID)) return hash.toString('hex') } + +export const timestampToDate = (timestamp: Timestamp): Date => { + let milliseconds = timestamp.nanoSeconds / 1000000 + milliseconds += timestamp.seconds * 1000 + return new Date(milliseconds) +} + +export const timestampSecondsToDate = (timestamp: TimestampSeconds): Date => { + return new Date(timestamp.seconds * 1000) +} + +export const base64ToBuffer = (base64: string): Buffer => { + return Buffer.from(base64, 'base64') +} + +export const bodyBytesToTransactionBody = (bodyBytes: Buffer): TransactionBody => { + try { + return TransactionBody.decode(new Uint8Array(bodyBytes)) + } catch (error) { + logger.error('error decoding body from gradido transaction: %s', error) + throw new TransactionError( + TransactionErrorType.PROTO_DECODE_ERROR, + 'cannot decode body from gradido transaction', + ) + } +} + +export const transactionBodyToBodyBytes = (transactionBody: TransactionBody): Buffer => { + try { + return Buffer.from(TransactionBody.encode(transactionBody).finish()) + } catch (error) { + logger.error('error encoding transaction body to body bytes', error) + throw new TransactionError( + TransactionErrorType.PROTO_ENCODE_ERROR, + 'cannot encode transaction body', + ) + } +} diff --git a/dlt-connector/tsconfig.json b/dlt-connector/tsconfig.json index 3abf9aead..e37b2a7a0 100644 --- a/dlt-connector/tsconfig.json +++ b/dlt-connector/tsconfig.json @@ -55,8 +55,7 @@ "@resolver/*": ["src/graphql/resolver/*"], "@scalar/*": ["src/graphql/scalar/*"], "@test/*": ["test/*"], - "@proto/*" : ["src/proto/*"], - "@controller/*": ["src/controller/*"], + "@proto/*" : ["src/proto/*"], "@validator/*" : ["src/graphql/validator/*"], "@typeorm/*" : ["src/typeorm/*"], /* external */ diff --git a/dlt-connector/yarn.lock b/dlt-connector/yarn.lock index 136e845f5..e54f2866d 100644 --- a/dlt-connector/yarn.lock +++ b/dlt-connector/yarn.lock @@ -20,7 +20,7 @@ resolved "https://registry.yarnpkg.com/@apollo/cache-control-types/-/cache-control-types-1.0.3.tgz#5da62cf64c3b4419dabfef4536b57a40c8ff0b47" integrity sha512-F17/vCp7QVwom9eG7ToauIKdAxpSoadsJnqIfyryLFSkLSOEqu+eC5Z3N8OXcUVStuOMcNHlyraRsA6rRICu4g== -"@apollo/protobufjs@1.2.7", "@apollo/protobufjs@^1.2.7": +"@apollo/protobufjs@1.2.7": version "1.2.7" resolved "https://registry.yarnpkg.com/@apollo/protobufjs/-/protobufjs-1.2.7.tgz#3a8675512817e4a046a897e5f4f16415f16a7d8a" integrity sha512-Lahx5zntHPZia35myYDBRuF58tlwPskwHc5CWBZC/4bMKB6siTBWwtMrkqXcsNwQiFSzSx5hKdRPUmemrEp3Gg== @@ -843,6 +843,11 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" +"@noble/hashes@^1.2.0": + version "1.3.2" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.2.tgz#6f26dbc8fbc7205873ce3cee2f690eba0d421b39" + integrity sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ== + "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" @@ -1125,6 +1130,13 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-20.7.0.tgz#c03de4572f114a940bc2ca909a33ddb2b925e470" integrity sha512-zI22/pJW2wUZOVyguFaUL1HABdmSVxpXrzIqkjsHmyUjNhPoWM1CKfvVuXfetHhIok4RY573cqS0mZ1SJEnoTg== +"@types/node@>=13.7.0": + version "20.8.7" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.8.7.tgz#ad23827850843de973096edfc5abc9e922492a25" + integrity sha512-21TKHHh3eUHIi2MloeptJWALuCu5H7HQTdTrWIFReA8ad+aggoX+lRes3ex7/FtpC+sVUpFMQ+QTfYr74mruiQ== + dependencies: + undici-types "~5.25.1" + "@types/node@^18.11.18": version "18.18.0" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.18.0.tgz#bd19d5133a6e5e2d0152ec079ac27c120e7f1763" @@ -1628,6 +1640,22 @@ binary-extensions@^2.0.0: resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d" integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA== +bip32-ed25519@^0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/bip32-ed25519/-/bip32-ed25519-0.0.4.tgz#218943e212c2d3152dfd6f3a929305e3fe86534c" + integrity sha512-KfazzGVLwl70WZ1r98dO+8yaJRTGgWHL9ITn4bXHQi2mB4cT3Hjh53tXWUpEWE1zKCln7PbyX8Z337VapAOb5w== + dependencies: + bn.js "^5.1.1" + elliptic "^6.4.1" + hash.js "^1.1.7" + +bip39@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/bip39/-/bip39-3.1.0.tgz#c55a418deaf48826a6ceb34ac55b3ee1577e18a3" + integrity sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A== + dependencies: + "@noble/hashes" "^1.2.0" + bl@^4.0.3: version "4.1.0" resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" @@ -1637,6 +1665,16 @@ bl@^4.0.3: inherits "^2.0.4" readable-stream "^3.4.0" +bn.js@^4.11.9: + version "4.12.0" + resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.12.0.tgz#775b3f278efbb9718eec7361f483fb36fbbfea88" + integrity sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA== + +bn.js@^5.1.1: + version "5.2.1" + resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.1.tgz#0bc527a6a0d18d0aa8d5b0538ce4a77dccfa7b70" + integrity sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ== + body-parser@1.19.0: version "1.19.0" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.0.tgz#96b2709e57c9c4e09a6fd66a8fd979844f69f08a" @@ -1711,6 +1749,11 @@ braces@^3.0.2, braces@~3.0.2: dependencies: fill-range "^7.0.1" +brorand@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" + integrity sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w== + browser-process-hrtime@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz#3c9b4b7d782c8121e56f10106d84c0d0ffc94626" @@ -2343,6 +2386,19 @@ electron-to-chromium@^1.4.530: resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.531.tgz#22966d894c4680726c17cf2908ee82ff5d26ac25" integrity sha512-H6gi5E41Rn3/mhKlPaT1aIMg/71hTAqn0gYEllSuw9igNWtvQwu185jiCZoZD29n7Zukgh7GVZ3zGf0XvkhqjQ== +elliptic@^6.4.1: + version "6.5.4" + resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.4.tgz#da37cebd31e79a1367e941b592ed1fbebd58abbb" + integrity sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ== + dependencies: + bn.js "^4.11.9" + brorand "^1.1.0" + hash.js "^1.0.0" + hmac-drbg "^1.0.1" + inherits "^2.0.4" + minimalistic-assert "^1.0.1" + minimalistic-crypto-utils "^1.0.1" + emittery@^0.8.1: version "0.8.1" resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.8.1.tgz#bb23cc86d03b30aa75a7f734819dee2e1ba70860" @@ -3338,11 +3394,28 @@ has@^1.0.3: dependencies: function-bind "^1.1.1" +hash.js@^1.0.0, hash.js@^1.0.3, hash.js@^1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42" + integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA== + dependencies: + inherits "^2.0.3" + minimalistic-assert "^1.0.1" + highlight.js@^10.7.1: version "10.7.3" resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531" integrity sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A== +hmac-drbg@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" + integrity sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg== + dependencies: + hash.js "^1.0.3" + minimalistic-assert "^1.0.0" + minimalistic-crypto-utils "^1.0.1" + html-encoding-sniffer@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz#42a6dc4fd33f00281176e8b23759ca4e4fa185f3" @@ -4379,6 +4452,11 @@ long@^4.0.0: resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28" integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA== +long@^5.0.0: + version "5.2.3" + resolved "https://registry.yarnpkg.com/long/-/long-5.2.3.tgz#a3ba97f3877cf1d778eccbcb048525ebb77499e1" + integrity sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q== + lower-case@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/lower-case/-/lower-case-2.0.2.tgz#6fa237c63dbdc4a82ca0fd882e4722dc5e634e28" @@ -4494,6 +4572,16 @@ mimic-response@^2.0.0: resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-2.1.0.tgz#d13763d35f613d09ec37ebb30bac0469c0ee8f43" integrity sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA== +minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" + integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== + +minimalistic-crypto-utils@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" + integrity sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg== + minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" @@ -5038,6 +5126,24 @@ prompts@^2.0.1: kleur "^3.0.3" sisteransi "^1.0.5" +protobufjs@^7.2.5: + version "7.2.5" + resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-7.2.5.tgz#45d5c57387a6d29a17aab6846dcc283f9b8e7f2d" + integrity sha512-gGXRSXvxQ7UiPgfw8gevrfRWcTlSbOFg+p/N+JVJEK5VhueL2miT6qTymqAmjr1Q5WbOCyJbyrk6JfWKwlFn6A== + dependencies: + "@protobufjs/aspromise" "^1.1.2" + "@protobufjs/base64" "^1.1.2" + "@protobufjs/codegen" "^2.0.4" + "@protobufjs/eventemitter" "^1.1.0" + "@protobufjs/fetch" "^1.1.0" + "@protobufjs/float" "^1.0.2" + "@protobufjs/inquire" "^1.1.0" + "@protobufjs/path" "^1.1.2" + "@protobufjs/pool" "^1.1.0" + "@protobufjs/utf8" "^1.1.0" + "@types/node" ">=13.7.0" + long "^5.0.0" + proxy-addr@~2.0.5, proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" @@ -6202,6 +6308,11 @@ undefsafe@^2.0.5: resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c" integrity sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA== +undici-types@~5.25.1: + version "5.25.3" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.25.3.tgz#e044115914c85f0bcbb229f346ab739f064998c3" + integrity sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA== + universalify@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" diff --git a/dlt-database/entity/0001-init_db/Account.ts b/dlt-database/entity/0001-init_db/Account.ts index 43910122a..d6d4a3095 100644 --- a/dlt-database/entity/0001-init_db/Account.ts +++ b/dlt-database/entity/0001-init_db/Account.ts @@ -8,7 +8,7 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' -import { TransactionRecipe } from '../TransactionRecipe' +import { TransactionRecipe } from './TransactionRecipe' import { ConfirmedTransaction } from '../ConfirmedTransaction' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Decimal } from 'decimal.js-light' diff --git a/dlt-database/entity/0001-init_db/Community.ts b/dlt-database/entity/0001-init_db/Community.ts index 96ddd59d6..52f8c1155 100644 --- a/dlt-database/entity/0001-init_db/Community.ts +++ b/dlt-database/entity/0001-init_db/Community.ts @@ -8,7 +8,7 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +import { TransactionRecipe } from './TransactionRecipe' import { AccountCommunity } from '../AccountCommunity' @Entity('communities') diff --git a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts index 16786a713..a5d22dc80 100644 --- a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts +++ b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts @@ -10,7 +10,7 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' +import { Account } from './Account' import { TransactionRecipe } from '../TransactionRecipe' @Entity('confirmed_transactions') diff --git a/dlt-database/entity/0001-init_db/TransactionRecipe.ts b/dlt-database/entity/0001-init_db/TransactionRecipe.ts index 934e81d02..db311e64f 100644 --- a/dlt-database/entity/0001-init_db/TransactionRecipe.ts +++ b/dlt-database/entity/0001-init_db/TransactionRecipe.ts @@ -10,8 +10,8 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' -import { Community } from '../Community' +import { Account } from './Account' +import { Community } from './Community' import { ConfirmedTransaction } from '../ConfirmedTransaction' @Entity('transaction_recipes') diff --git a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts index 5d2a38f65..1b8df403b 100644 --- a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts +++ b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts @@ -10,7 +10,7 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' +import { Account } from './Account' import { TransactionRecipe } from '../TransactionRecipe' @Entity('confirmed_transactions') diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts new file mode 100644 index 000000000..067a140eb --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -0,0 +1,92 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, + OneToMany, + BaseEntity, +} from 'typeorm' +import { User } from '../User' +import { Transaction } from '../Transaction' +import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +import { Decimal } from 'decimal.js-light' +import { AccountCommunity } from '../AccountCommunity' + +@Entity('accounts') +export class Account extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true }) + id: number + + @ManyToOne(() => User, (user) => user.accounts, { cascade: true, eager: true }) // Assuming you have a User entity with 'accounts' relation + @JoinColumn({ name: 'user_id' }) + user?: User + + // if user id is null, account belongs to community gmw or auf + @Column({ name: 'user_id', type: 'int', unsigned: true, nullable: true }) + userId?: number + + @Column({ name: 'derivation_index', type: 'int', unsigned: true, nullable: true }) + derivationIndex?: number + + @Column({ name: 'derive2_pubkey', type: 'binary', length: 32, unique: true }) + derive2Pubkey: Buffer + + @Column({ type: 'tinyint', unsigned: true }) + type: number + + @Column({ + name: 'created_at', + type: 'datetime', + precision: 3, + default: () => 'CURRENT_TIMESTAMP(3)', + }) + createdAt: Date + + @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) + confirmedAt?: Date + + @Column({ + type: 'decimal', + precision: 40, + scale: 20, + default: 0, + transformer: DecimalTransformer, + }) + balance: Decimal + + @Column({ + name: 'balance_date', + type: 'datetime', + default: () => 'CURRENT_TIMESTAMP()', + }) + balanceDate: Date + + @Column({ + name: 'balance_created_at', + type: 'decimal', + precision: 40, + scale: 20, + default: 0, + transformer: DecimalTransformer, + }) + balanceCreatedAt: Decimal + + @Column({ + name: 'balance_created_at_date', + type: 'datetime', + precision: 3, + default: () => 'CURRENT_TIMESTAMP(3)', + }) + balanceCreatedAtDate: Date + + @OneToMany(() => AccountCommunity, (accountCommunity) => accountCommunity.account) + @JoinColumn({ name: 'account_id' }) + accountCommunities: AccountCommunity[] + + @OneToMany(() => Transaction, (transaction) => transaction.signingAccount) + transactionSigning?: Transaction[] + + @OneToMany(() => Transaction, (transaction) => transaction.recipientAccount) + transactionRecipient?: Transaction[] +} diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts new file mode 100644 index 000000000..ade3afc90 --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts @@ -0,0 +1,68 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + JoinColumn, + OneToOne, + OneToMany, + BaseEntity, +} from 'typeorm' +import { Account } from '../Account' +import { Transaction } from '../Transaction' +import { AccountCommunity } from '../AccountCommunity' + +@Entity('communities') +export class Community extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true }) + id: number + + @Column({ name: 'iota_topic', collation: 'utf8mb4_unicode_ci', unique: true }) + iotaTopic: string + + @Column({ name: 'root_pubkey', type: 'binary', length: 32, unique: true, nullable: true }) + rootPubkey?: Buffer + + @Column({ name: 'root_privkey', type: 'binary', length: 64, nullable: true }) + rootPrivkey?: Buffer + + @Column({ name: 'root_chaincode', type: 'binary', length: 32, nullable: true }) + rootChaincode?: Buffer + + @Column({ type: 'tinyint', default: true }) + foreign: boolean + + @Column({ name: 'gmw_account_id', type: 'int', unsigned: true, nullable: true }) + gmwAccountId?: number + + @OneToOne(() => Account, { cascade: true }) + @JoinColumn({ name: 'gmw_account_id' }) + gmwAccount?: Account + + @Column({ name: 'auf_account_id', type: 'int', unsigned: true, nullable: true }) + aufAccountId?: number + + @OneToOne(() => Account, { cascade: true }) + @JoinColumn({ name: 'auf_account_id' }) + aufAccount?: Account + + @Column({ + name: 'created_at', + type: 'datetime', + precision: 3, + default: () => 'CURRENT_TIMESTAMP(3)', + }) + createdAt: Date + + @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) + confirmedAt?: Date + + @OneToMany(() => AccountCommunity, (accountCommunity) => accountCommunity.community) + @JoinColumn({ name: 'community_id' }) + accountCommunities: AccountCommunity[] + + @OneToMany(() => Transaction, (recipe) => recipe.senderCommunity) + transactionSender?: Transaction[] + + @OneToMany(() => Transaction, (recipe) => recipe.recipientCommunity) + transactionRecipient?: Transaction[] +} diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts new file mode 100644 index 000000000..ac48f07b6 --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -0,0 +1,120 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + OneToOne, + JoinColumn, + BaseEntity, +} from 'typeorm' +import { Decimal } from 'decimal.js-light' + +import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +import { Account } from '../Account' +import { Community } from '../Community' + +@Entity('transactions') +export class Transaction extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) + id: number + + @Column({ name: 'iota_message_id', type: 'binary', length: 32, nullable: true }) + iotaMessageId?: Buffer + + @Column({ name: 'backend_transaction_id', type: 'bigint', unsigned: true, nullable: true }) + backendTransactionId?: number + + @OneToOne(() => Transaction) + // eslint-disable-next-line no-use-before-define + paringTransaction?: Transaction + + @Column({ name: 'paring_transaction_id', type: 'bigint', unsigned: true, nullable: true }) + paringTransactionId?: number + + // if transaction has a sender than it is also the sender account + @ManyToOne(() => Account, (account) => account.transactionSigning) + @JoinColumn({ name: 'signing_account_id' }) + signingAccount?: Account + + @Column({ name: 'signing_account_id', type: 'int', unsigned: true, nullable: true }) + signingAccountId?: number + + @ManyToOne(() => Account, (account) => account.transactionRecipient) + @JoinColumn({ name: 'recipient_account_id' }) + recipientAccount?: Account + + @Column({ name: 'recipient_account_id', type: 'int', unsigned: true, nullable: true }) + recipientAccountId?: number + + @ManyToOne(() => Community, (community) => community.transactionSender, { + eager: true, + }) + @JoinColumn({ name: 'sender_community_id' }) + senderCommunity: Community + + @Column({ name: 'sender_community_id', type: 'int', unsigned: true }) + senderCommunityId: number + + @ManyToOne(() => Community, (community) => community.transactionRecipient) + @JoinColumn({ name: 'recipient_community_id' }) + recipientCommunity?: Community + + @Column({ name: 'recipient_community_id', type: 'int', unsigned: true, nullable: true }) + recipientCommunityId?: number + + @Column({ + type: 'decimal', + precision: 40, + scale: 20, + nullable: true, + transformer: DecimalTransformer, + }) + amount?: Decimal + + @Column({ + name: 'account_balance_created_at', + type: 'decimal', + precision: 40, + scale: 20, + transformer: DecimalTransformer, + }) + accountBalanceCreatedAt: Decimal + + @Column({ type: 'tinyint' }) + type: number + + @Column({ name: 'created_at', type: 'datetime', precision: 3 }) + createdAt: Date + + @Column({ name: 'body_bytes', type: 'blob' }) + bodyBytes: Buffer + + @Column({ type: 'binary', length: 64, unique: true }) + signature: Buffer + + @Column({ name: 'protocol_version', type: 'varchar', length: 255, default: '1' }) + protocolVersion: string + + @Column({ type: 'bigint' }) + nr: number + + @Column({ name: 'running_hash', type: 'binary', length: 48 }) + runningHash: Buffer + + @Column({ + name: 'account_balance', + type: 'decimal', + precision: 40, + scale: 20, + nullable: false, + default: 0, + transformer: DecimalTransformer, + }) + accountBalanceConfirmedAt: Decimal + + @Column({ name: 'iota_milestone', type: 'bigint', nullable: true }) + iotaMilestone?: number + + @Column({ name: 'confirmed_at', type: 'datetime' }) + confirmedAt: Date +} diff --git a/dlt-database/entity/Account.ts b/dlt-database/entity/Account.ts index ed1e92840..3d7713ba9 100644 --- a/dlt-database/entity/Account.ts +++ b/dlt-database/entity/Account.ts @@ -1 +1 @@ -export { Account } from './0002-refactor_add_community/Account' +export { Account } from './0003-refactor_transaction_recipe/Account' diff --git a/dlt-database/entity/Community.ts b/dlt-database/entity/Community.ts index 211837e40..cb4d34c43 100644 --- a/dlt-database/entity/Community.ts +++ b/dlt-database/entity/Community.ts @@ -1 +1 @@ -export { Community } from './0002-refactor_add_community/Community' +export { Community } from './0003-refactor_transaction_recipe/Community' diff --git a/dlt-database/entity/Transaction.ts b/dlt-database/entity/Transaction.ts new file mode 100644 index 000000000..113eb3450 --- /dev/null +++ b/dlt-database/entity/Transaction.ts @@ -0,0 +1 @@ +export { Transaction } from './0003-refactor_transaction_recipe/Transaction' diff --git a/dlt-database/entity/index.ts b/dlt-database/entity/index.ts index 74c2e2258..ba7ea2663 100644 --- a/dlt-database/entity/index.ts +++ b/dlt-database/entity/index.ts @@ -1,19 +1,17 @@ import { Account } from './Account' import { AccountCommunity } from './AccountCommunity' import { Community } from './Community' -import { ConfirmedTransaction } from './ConfirmedTransaction' import { InvalidTransaction } from './InvalidTransaction' import { Migration } from './Migration' -import { TransactionRecipe } from './TransactionRecipe' +import { Transaction } from './Transaction' import { User } from './User' export const entities = [ AccountCommunity, Account, Community, - ConfirmedTransaction, InvalidTransaction, Migration, - TransactionRecipe, + Transaction, User, ] diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts new file mode 100644 index 000000000..577b24938 --- /dev/null +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -0,0 +1,97 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export async function upgrade(queryFn: (query: string, values?: any[]) => Promise>) { + // write upgrade logic as parameter of queryFn + await queryFn(`DROP TABLE \`transaction_recipes\`;`) + await queryFn(`DROP TABLE \`confirmed_transactions\`;`) + + await queryFn( + `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NULL DEFAULT NULL;`, + ) + await queryFn( + `ALTER TABLE \`accounts\` ADD COLUMN \`account_balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_date\`;`, + ) + await queryFn( + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) AFTER \`account_balance_created_at\`;`, + ) + + await queryFn( + `CREATE TABLE \`transactions\` ( + \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, + \`iota_message_id\` varbinary(32) DEFAULT NULL, + \`backend_transaction_id\` bigint unsigned DEFAULT NULL, + \`paring_transaction_id\` bigint unsigned DEFAULT NULL, + \`signing_account_id\` int unsigned DEFAULT NULL, + \`recipient_account_id\` int unsigned DEFAULT NULL, + \`sender_community_id\` int unsigned NOT NULL, + \`recipient_community_id\` int unsigned DEFAULT NULL, + \`amount\` decimal(40, 20) DEFAULT NULL, + \`account_balance_created_at\` decimal(40, 20) NOT NULL, + \`type\` tinyint NOT NULL, + \`created_at\` datetime(3) NOT NULL, + \`body_bytes\` blob NOT NULL, + \`signature\` varbinary(64) NOT NULL, + \`protocol_version\` varchar(255) NOT NULL DEFAULT '1', + \`nr\` bigint NOT NULL, + \`running_hash\` varbinary(48) NOT NULL, + \`account_balance\` decimal(40, 20) NOT NULL DEFAULT 0.00000000000000000000, + \`iota_milestone\` bigint DEFAULT NULL, + \`confirmed_at\` datetime NOT NULL, + PRIMARY KEY (\`id\`), + UNIQUE KEY \`signature\` (\`signature\`), + FOREIGN KEY (\`signing_account_id\`) REFERENCES accounts(id), + FOREIGN KEY (\`recipient_account_id\`) REFERENCES accounts(id), + FOREIGN KEY (\`sender_community_id\`) REFERENCES communities(id), + FOREIGN KEY (\`recipient_community_id\`) REFERENCES communities(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `, + ) + + await queryFn(`ALTER TABLE \`communities\` ADD UNIQUE(\`iota_topic\`);`) +} + +export async function downgrade(queryFn: (query: string, values?: any[]) => Promise>) { + await queryFn(` + CREATE TABLE IF NOT EXISTS \`transaction_recipes\` ( + \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, + \`iota_message_id\` binary(32) DEFAULT NULL, + \`signing_account_id\` int(10) unsigned NOT NULL, + \`recipient_account_id\` int(10) unsigned DEFAULT NULL, + \`sender_community_id\` int(10) unsigned NOT NULL, + \`recipient_community_id\` int(10) unsigned DEFAULT NULL, + \`amount\` decimal(40,20) DEFAULT NULL, + \`type\` tinyint unsigned NOT NULL, + \`created_at\` datetime(3) NOT NULL, + \`body_bytes\` BLOB NOT NULL, + \`signature\` binary(64) NOT NULL, + \`protocol_version\` int(10) NOT NULL DEFAULT 1, + PRIMARY KEY (\`id\`), + FOREIGN KEY (\`signing_account_id\`) REFERENCES accounts(id), + FOREIGN KEY (\`recipient_account_id\`) REFERENCES accounts(id), + FOREIGN KEY (\`sender_community_id\`) REFERENCES communities(id), + FOREIGN KEY (\`recipient_community_id\`) REFERENCES communities(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) + + await queryFn(` + CREATE TABLE IF NOT EXISTS \`confirmed_transactions\` ( + \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, + \`transaction_recipe_id\` bigint unsigned NOT NULL, + \`nr\` bigint unsigned NOT NULL, + \`running_hash\` binary(48) NOT NULL, + \`account_id\` int(10) unsigned NOT NULL, + \`account_balance\` decimal(40,20) NOT NULL DEFAULT 0, + \`iota_milestone\` bigint NOT NULL, + \`confirmed_at\` datetime NOT NULL, + PRIMARY KEY (\`id\`), + FOREIGN KEY (\`transaction_recipe_id\`) REFERENCES transaction_recipes(id), + FOREIGN KEY (\`account_id\`) REFERENCES accounts(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) + + await queryFn( + `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NOT NULL;`, + ) + await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`account_balance_created_at\`;`) + await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) + await queryFn(`DROP TABLE \`transactions\`;`) +} From 8ccc52ae0a4eb83943512e1b776cd25135219177 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 24 Oct 2023 19:48:01 +0200 Subject: [PATCH 02/47] refactored, not final yet --- dlt-connector/.eslintrc.js | 2 + dlt-connector/package.json | 1 + dlt-connector/src/data/Account.factory.ts | 44 ++++++++++++++++ dlt-connector/src/data/account.factory.ts | 42 --------------- dlt-connector/src/data/community.factory.ts | 31 ----------- .../src/graphql/resolver/CommunityResolver.ts | 18 ++++++- .../community/AddCommunity.context.ts | 30 +++++++++++ .../backendToDb/community/Community.role.ts | 23 ++++++++- .../community/ForeignCommunity.role.ts | 19 +------ .../community/HomeCommunity.role.ts | 51 +++++++++++++------ .../community/community.context.ts | 30 ----------- .../CommunityRootTransaction.role.ts | 2 +- .../CreateTransationRecipe.context.ts | 51 +++++++++++++++++++ .../transaction/TransactionRecipe.role.ts | 6 ++- .../transaction/transaction.context.ts | 20 -------- dlt-connector/yarn.lock | 5 ++ 16 files changed, 214 insertions(+), 161 deletions(-) create mode 100644 dlt-connector/src/data/Account.factory.ts delete mode 100644 dlt-connector/src/data/account.factory.ts delete mode 100644 dlt-connector/src/data/community.factory.ts create mode 100644 dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts delete mode 100644 dlt-connector/src/interactions/backendToDb/community/community.context.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts delete mode 100644 dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts diff --git a/dlt-connector/.eslintrc.js b/dlt-connector/.eslintrc.js index c477a4cb1..b2bc4047e 100644 --- a/dlt-connector/.eslintrc.js +++ b/dlt-connector/.eslintrc.js @@ -14,6 +14,7 @@ module.exports = { // 'plugin:import/typescript', // 'plugin:security/recommended', 'plugin:@eslint-community/eslint-comments/recommended', + 'plugin:dci-lint/recommended', ], settings: { 'import/parsers': { @@ -36,6 +37,7 @@ module.exports = { htmlWhitespaceSensitivity: 'ignore', }, ], + // 'dci-lint/literal-role-contracts': 'off' // import // 'import/export': 'error', // 'import/no-deprecated': 'error', diff --git a/dlt-connector/package.json b/dlt-connector/package.json index d64b6d743..4f9c5a26a 100644 --- a/dlt-connector/package.json +++ b/dlt-connector/package.json @@ -53,6 +53,7 @@ "eslint-config-prettier": "^8.8.0", "eslint-config-standard": "^17.0.0", "eslint-import-resolver-typescript": "^3.5.4", + "eslint-plugin-dci-lint": "^0.3.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-jest": "^27.2.1", "eslint-plugin-n": "^15.7.0", diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts new file mode 100644 index 000000000..c3ad02fa7 --- /dev/null +++ b/dlt-connector/src/data/Account.factory.ts @@ -0,0 +1,44 @@ +import { KeyManager } from '@/controller/KeyManager' +import { KeyPair } from '@/data/KeyPair' +import { AddressType } from '@/data/proto/3_3/enum/AddressType' +import { hardenDerivationIndex } from '@/utils/derivationHelper' +import { Account } from '@entity/Account' +import Decimal from 'decimal.js-light' + +const GMW_ACCOUNT_DERIVATION_INDEX = 1 +const AUF_ACCOUNT_DERIVATION_INDEX = 2 + +export class AccountFactory { + public static createAccount( + keyPair: KeyPair, + createdAt: Date, + derivationIndex: number, + type: AddressType, + ): Account { + const account = Account.create() + account.derivationIndex = derivationIndex + account.derive2Pubkey = KeyManager.getInstance().derive([derivationIndex], keyPair).publicKey + account.type = type.valueOf() + account.createdAt = createdAt + account.balance = new Decimal(0) + return account + } + + public static createGmwAccount(keyPair: KeyPair, createdAt: Date): Account { + return AccountFactory.createAccount( + keyPair, + createdAt, + hardenDerivationIndex(GMW_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_GMW, + ) + } + + public static createAufAccount(keyPair: KeyPair, createdAt: Date): Account { + return AccountFactory.createAccount( + keyPair, + createdAt, + hardenDerivationIndex(AUF_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_AUF, + ) + } +} diff --git a/dlt-connector/src/data/account.factory.ts b/dlt-connector/src/data/account.factory.ts deleted file mode 100644 index d823c8345..000000000 --- a/dlt-connector/src/data/account.factory.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { KeyManager } from '@/controller/KeyManager' -import { KeyPair } from '@/data/KeyPair' -import { AddressType } from '@/data/proto/3_3/enum/AddressType' -import { hardenDerivationIndex } from '@/utils/derivationHelper' -import { Account } from '@entity/Account' -import Decimal from 'decimal.js-light' - -const GMW_ACCOUNT_DERIVATION_INDEX = 1 -const AUF_ACCOUNT_DERIVATION_INDEX = 2 - -export const createAccount = ( - keyPair: KeyPair, - createdAt: Date, - derivationIndex: number, - type: AddressType, -): Account => { - const account = Account.create() - account.derivationIndex = derivationIndex - account.derive2Pubkey = KeyManager.getInstance().derive([derivationIndex], keyPair).publicKey - account.type = type.valueOf() - account.createdAt = createdAt - account.balance = new Decimal(0) - return account -} - -export const createGmwAccount = (keyPair: KeyPair, createdAt: Date): Account => { - return createAccount( - keyPair, - createdAt, - hardenDerivationIndex(GMW_ACCOUNT_DERIVATION_INDEX), - AddressType.COMMUNITY_GMW, - ) -} - -export const createAufAccount = (keyPair: KeyPair, createdAt: Date): Account => { - return createAccount( - keyPair, - createdAt, - hardenDerivationIndex(AUF_ACCOUNT_DERIVATION_INDEX), - AddressType.COMMUNITY_AUF, - ) -} diff --git a/dlt-connector/src/data/community.factory.ts b/dlt-connector/src/data/community.factory.ts deleted file mode 100644 index d80ff315a..000000000 --- a/dlt-connector/src/data/community.factory.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { KeyManager } from '@/controller/KeyManager' -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' -import { Community } from '@entity/Community' -import { createAufAccount, createGmwAccount } from './account.factory' - -export const createCommunity = (communityDraft: CommunityDraft, topic?: string): Community => { - const communityEntity = Community.create() - communityEntity.iotaTopic = topic ?? iotaTopicFromCommunityUUID(communityDraft.uuid) - communityEntity.createdAt = new Date(communityDraft.createdAt) - communityEntity.foreign = communityDraft.foreign - return communityEntity -} - -export const createHomeCommunity = (communityDraft: CommunityDraft, topic?: string): Community => { - // create community entity - const community = createCommunity(communityDraft, topic) - - // generate key pair for signing transactions and deriving all keys for community - const keyPair = KeyManager.generateKeyPair() - community.rootPubkey = keyPair.publicKey - community.rootPrivkey = keyPair.privateKey - community.rootChaincode = keyPair.chainCode - // we should only have one home community per server - KeyManager.getInstance().setHomeCommunityKeyPair(keyPair) - - // create auf account and gmw account - community.aufAccount = createAufAccount(keyPair, community.createdAt) - community.gmwAccount = createGmwAccount(keyPair, community.createdAt) - return community -} diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.ts index 43a871dd8..2259f604c 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.ts @@ -11,7 +11,7 @@ import { CommunityArg } from '@arg/CommunityArg' import { LogError } from '@/server/LogError' import { logger } from '@/server/logger' import { CommunityRepository } from '@/data/Community.repository' -import { addCommunity } from '@/interactions/backendToDb/community/community.context' +import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' @Resolver() export class CommunityResolver { @@ -54,6 +54,20 @@ export class CommunityResolver { new TransactionError(TransactionErrorType.ALREADY_EXIST, 'community already exist!'), ) } - return await addCommunity(communityDraft, topic) + // prepare context for interaction + // shouldn't throw at all + // TODO: write tests to make sure that it doesn't throw + const addCommunityContext = new AddCommunityContext(communityDraft, topic) + try { + // actually run interaction, create community, accounts for foreign community and transactionRecipe + await addCommunityContext.run() + return new TransactionResult() + } catch (error) { + if (error instanceof TransactionError) { + return new TransactionResult(error) + } else { + throw error + } + } } } diff --git a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts new file mode 100644 index 000000000..f2518d45a --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -0,0 +1,30 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { ForeignCommunityRole } from './ForeignCommunity.role' +import { HomeCommunityRole } from './HomeCommunity.role' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' +import { CommunityRole } from './Community.role' + +/** + * @DCI-Context + * Context for adding community to DB + * using roles to distinct between foreign and home communities + */ +export class AddCommunityContext { + private communityRole: CommunityRole + private iotaTopic: string + public constructor(private communityDraft: CommunityDraft, iotaTopic?: string) { + if (!iotaTopic) { + this.iotaTopic = iotaTopicFromCommunityUUID(this.communityDraft.uuid) + } else { + this.iotaTopic = iotaTopic + } + this.communityRole = communityDraft.foreign + ? new ForeignCommunityRole() + : new HomeCommunityRole() + } + + public async run(): Promise { + this.communityRole.create(this.communityDraft, this.iotaTopic) + await this.communityRole.store() + } +} diff --git a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts index 144d3bc5c..f2fa7d0ac 100644 --- a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts @@ -1,6 +1,27 @@ +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionError } from '@/graphql/model/TransactionError' +import { logger } from '@/server/logger' import { Community } from '@entity/Community' export abstract class CommunityRole { - abstract addCommunity(communityDraft: CommunityDraft, topic: string): Promise + protected self: Community + public constructor() { + this.self = Community.create() + } + + public create(communityDraft: CommunityDraft, topic: string): void { + this.self.iotaTopic = topic + this.self.createdAt = new Date(communityDraft.createdAt) + this.self.foreign = communityDraft.foreign + } + + public store(): Promise { + try { + return this.self.save() + } catch (error) { + logger.error('error saving new community into db: %s', error) + throw new TransactionError(TransactionErrorType.DB_ERROR, 'error saving community into db') + } + } } diff --git a/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts index 76af3026c..cf93deaa5 100644 --- a/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts @@ -1,19 +1,4 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { Community } from '@entity/Community' import { CommunityRole } from './Community.role' -import { logger } from '@/server/logger' -import { TransactionError } from '@/graphql/model/TransactionError' -import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { createCommunity } from '@/data/community.factory' -export class ForeignCommunityRole extends CommunityRole { - addCommunity(communityDraft: CommunityDraft, topic: string): Promise { - const community = createCommunity(communityDraft, topic) - try { - return community.save() - } catch (error) { - logger.error('error saving new foreign community into db: %s', error) - throw new TransactionError(TransactionErrorType.DB_ERROR, 'error saving community into db') - } - } -} +// same as base class +export class ForeignCommunityRole extends CommunityRole {} diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index df670398f..4ae946498 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -1,28 +1,47 @@ import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { Community } from '@entity/Community' import { CommunityRole } from './Community.role' -import { getTransaction } from '@/client/GradidoNode' -import { timestampSecondsToDate } from '@/utils/typeConverter' -import { createHomeCommunity } from '@/data/community.factory' -import { createCommunityRootTransactionRecipe } from '../transaction/transaction.context' import { QueryRunner } from 'typeorm' +import { Transaction } from '@entity/Transaction' +import { KeyManager } from '@/controller/KeyManager' +import { AccountFactory } from '@/data/Account.factory' +import { CreateTransactionRecipeContext } from '../transaction/CreateTransationRecipe.context' export class HomeCommunityRole extends CommunityRole { + private transactionRecipe: Transaction + + public create(communityDraft: CommunityDraft, topic: string): void { + super.create(communityDraft, topic) + // generate key pair for signing transactions and deriving all keys for community + const keyPair = KeyManager.generateKeyPair() + this.self.rootPubkey = keyPair.publicKey + this.self.rootPrivkey = keyPair.privateKey + this.self.rootChaincode = keyPair.chainCode + // we should only have one home community per server + KeyManager.getInstance().setHomeCommunityKeyPair(keyPair) + + // create auf account and gmw account + this.self.aufAccount = AccountFactory.createAufAccount(keyPair, this.self.createdAt) + this.self.gmwAccount = AccountFactory.createGmwAccount(keyPair, this.self.createdAt) + + const transactionRecipeContext = new CreateTransactionRecipeContext(communityDraft) + transactionRecipeContext.setCommunity(this.self) + transactionRecipeContext.run() + this.transactionRecipe = transactionRecipeContext.getTransactionRecipe() + } + + public store(): Promise { + + } + public async addCommunity(communityDraft: CommunityDraft, topic: string): Promise { const community = createHomeCommunity(communityDraft, topic) - // check if a CommunityRoot Transaction exist already on iota blockchain - const existingCommunityRootTransaction = await getTransaction(1, community.iotaTopic) - if (existingCommunityRootTransaction) { - community.confirmedAt = timestampSecondsToDate(existingCommunityRootTransaction.confirmedAt) - return community.save() - } else { - createCommunityRootTransactionRecipe(communityDraft, community).storeAsTransaction( - async (queryRunner: QueryRunner): Promise => { - await queryRunner.manager.save(community) - }, - ) - } + createCommunityRootTransactionRecipe(communityDraft, community).storeAsTransaction( + async (queryRunner: QueryRunner): Promise => { + await queryRunner.manager.save(community) + }, + ) return community.save() } } diff --git a/dlt-connector/src/interactions/backendToDb/community/community.context.ts b/dlt-connector/src/interactions/backendToDb/community/community.context.ts deleted file mode 100644 index cd55599bf..000000000 --- a/dlt-connector/src/interactions/backendToDb/community/community.context.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { TransactionResult } from '@/graphql/model/TransactionResult' -import { ForeignCommunityRole } from './ForeignCommunity.role' -import { HomeCommunityRole } from './HomeCommunity.role' -import { TransactionError } from '@/graphql/model/TransactionError' -import { TransactionsManager } from '@/controller/TransactionsManager' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' - -export const addCommunity = async ( - communityDraft: CommunityDraft, - iotaTopic?: string, -): Promise => { - const communityRole = communityDraft.foreign - ? new ForeignCommunityRole() - : new HomeCommunityRole() - try { - if (!iotaTopic) { - iotaTopic = iotaTopicFromCommunityUUID(communityDraft.uuid) - } - await communityRole.addCommunity(communityDraft, iotaTopic) - await TransactionsManager.getInstance().addTopic(iotaTopic) - return new TransactionResult() - } catch (error) { - if (error instanceof TransactionError) { - return new TransactionResult(error) - } else { - throw error - } - } -} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts index 3bce63461..aa09f89b2 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts @@ -6,7 +6,7 @@ import { KeyPair } from '@/data/KeyPair' import { sign } from '@/utils/cryptoHelper' export class CommunityRootTransactionRole extends TransactionRecipeRole { - public createFromCommunityDraft( + public createFromCommunityRoot( communityDraft: CommunityDraft, community: Community, ): CommunityRootTransactionRole { diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts new file mode 100644 index 000000000..454dd5b41 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -0,0 +1,51 @@ +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' +import { TransactionRecipeRole } from './TransactionRecipe.role' +import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { Transaction } from '@entity/Transaction' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' + +/** + * @DCI-Context + * Context for create and add Transaction Recipe to DB + */ + +export class CreateTransactionRecipeContext { + private transactionRecipeRole: TransactionRecipeRole + private community?: Community + public constructor(private draft: CommunityDraft | TransactionDraft) { + if (draft instanceof CommunityDraft) { + this.transactionRecipeRole = new CommunityRootTransactionRole() + } else if (draft instanceof TransactionDraft) { + this.transactionRecipeRole = new TransactionRecipeRole() + } + } + + public setCommunity(community: Community) { + this.community = community + } + + public getCommunity() { + return this.community + } + + public getTransactionRecipe(): Transaction { + return this.transactionRecipeRole.getTransaction() + } + + public run(): void { + if (this.draft instanceof TransactionDraft) { + this.transactionRecipeRole = new TransactionRecipeRole().create(this.draft) + } else if (this.draft instanceof CommunityDraft) { + if (!this.community) { + throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community was not set') + } + this.transactionRecipeRole = new CommunityRootTransactionRole().createFromCommunityRoot( + this.draft, + this.community, + ) + } + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 0ab41f0d4..4a432f67e 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -14,10 +14,14 @@ export class TransactionRecipeRole { this.transactionBuilder = new TransactionBuilder() } - public createFromTransactionDraft(transactionDraft: TransactionDraft): TransactionRecipeRole { + public create(transactionDraft: TransactionDraft): TransactionRecipeRole { return this } + public getTransaction(): Transaction { + return this.transactionBuilder.getTransaction() + } + public async storeAsTransaction( transactionFunction: (queryRunner: QueryRunner) => Promise, ): Promise { diff --git a/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts deleted file mode 100644 index 5c8bda04f..000000000 --- a/dlt-connector/src/interactions/backendToDb/transaction/transaction.context.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { Community } from '@entity/Community' -import { TransactionRecipeRole } from './TransactionRecipe.role' -import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' - -export const createCommunityRootTransactionRecipe = ( - communityDraft: CommunityDraft, - community: Community, -): TransactionRecipeRole => { - const communityRootTransactionRole = new CommunityRootTransactionRole() - return communityRootTransactionRole.createFromCommunityDraft(communityDraft, community) -} - -export const createTransactionRecipe = ( - transactionDraft: TransactionDraft, -): TransactionRecipeRole => { - const transactionRecipeRole = new TransactionRecipeRole() - return transactionRecipeRole.createFromTransactionDraft(transactionDraft) -} diff --git a/dlt-connector/yarn.lock b/dlt-connector/yarn.lock index e54f2866d..3c7a8bf36 100644 --- a/dlt-connector/yarn.lock +++ b/dlt-connector/yarn.lock @@ -2586,6 +2586,11 @@ eslint-module-utils@^2.7.4, eslint-module-utils@^2.8.0: dependencies: debug "^3.2.7" +eslint-plugin-dci-lint@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-dci-lint/-/eslint-plugin-dci-lint-0.3.0.tgz#dcd73c50505b589b415017cdb72716f98e9495c3" + integrity sha512-BhgrwJ5k3eMN41NwCZ/tYQGDTMOrHXpH8XOfRZrGtPqmlnOZCVGWow+KyZMz0/wOFVpXx/q9B0y7R7qtU7lnqg== + eslint-plugin-es@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-4.1.0.tgz#f0822f0c18a535a97c3e714e89f88586a7641ec9" From d23098590653f6ce1ea06505aeffee1fd8720737 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Sat, 28 Oct 2023 16:29:37 +0200 Subject: [PATCH 03/47] finish implementing with DCI, test next --- dlt-connector/src/data/Transaction.builder.ts | 25 +++++ .../src/data/proto/TransactionBody.builder.ts | 28 +++++- .../src/graphql/enum/TransactionErrorType.ts | 3 + .../src/graphql/input/TransactionDraft.ts | 8 +- .../src/graphql/model/TransactionRecipe.ts | 4 +- .../src/graphql/model/TransactionResult.ts | 2 +- .../src/graphql/resolver/CommunityResolver.ts | 2 +- .../graphql/resolver/TransactionsResolver.ts | 93 +++++-------------- .../community/HomeCommunity.role.ts | 35 +++---- .../CreateTransationRecipe.context.ts | 7 +- .../transaction/TransactionRecipe.role.ts | 80 +++++++++------- 11 files changed, 151 insertions(+), 136 deletions(-) diff --git a/dlt-connector/src/data/Transaction.builder.ts b/dlt-connector/src/data/Transaction.builder.ts index 4b1b385ab..321dda76b 100644 --- a/dlt-connector/src/data/Transaction.builder.ts +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -8,6 +8,7 @@ import { CommunityRepository } from './Community.repository' import { LogError } from '@/server/LogError' import { Account } from '@entity/Account' import { Community } from '@entity/Community' +import { TransactionBodyBuilder } from './proto/TransactionBody.builder' export class TransactionBuilder { private transaction: Transaction @@ -50,6 +51,10 @@ export class TransactionBuilder { return this.transaction } + public getSenderCommunity(): Community { + return this.transaction.senderCommunity + } + public setSigningAccount(signingAccount: Account): TransactionBuilder { this.transaction.signingAccount = signingAccount return this @@ -84,6 +89,11 @@ export class TransactionBuilder { return this } + public setBackendTransactionId(backendTransactionId: number): TransactionBuilder { + this.transaction.backendTransactionId = backendTransactionId + return this + } + public async setSenderCommunityFromSenderUser( senderUser: UserIdentifier, ): Promise { @@ -144,4 +154,19 @@ export class TransactionBuilder { this.transaction.bodyBytes ??= transactionBodyToBodyBytes(transactionBody) return this } + + public fromTransactionBodyBuilder( + transactionBodyBuilder: TransactionBodyBuilder, + ): TransactionBuilder { + const signingAccount = transactionBodyBuilder.getSigningAccount() + if (signingAccount) { + this.setSigningAccount(signingAccount) + } + const recipientAccount = transactionBodyBuilder.getRecipientAccount() + if (recipientAccount) { + this.setRecipientAccount(recipientAccount) + } + this.fromTransactionBody(transactionBodyBuilder.getTransactionBody()) + return this + } } diff --git a/dlt-connector/src/data/proto/TransactionBody.builder.ts b/dlt-connector/src/data/proto/TransactionBody.builder.ts index 5f2681824..b0e0a9f79 100644 --- a/dlt-connector/src/data/proto/TransactionBody.builder.ts +++ b/dlt-connector/src/data/proto/TransactionBody.builder.ts @@ -25,6 +25,8 @@ export class TransactionBodyBuilder { public reset(): void { this.body = undefined + this.signingAccount = undefined + this.recipientAccount = undefined } /** @@ -42,14 +44,26 @@ export class TransactionBodyBuilder { * client code before disposing of the previous result. */ public build(): TransactionBody { - const result = this.body - if (!result) { + const result = this.getTransactionBody() + this.reset() + return result + } + + public getTransactionBody(): TransactionBody { + if (!this.body) { throw new LogError( 'cannot build Transaction Body, missing information, please call at least fromTransactionDraft or fromCommunityDraft', ) } - this.reset() - return result + return this.body + } + + public getSigningAccount(): Account | undefined { + return this.signingAccount + } + + public getRecipientAccount(): Account | undefined { + return this.recipientAccount } public setSigningAccount(signingAccount: Account): TransactionBodyBuilder { @@ -67,11 +81,17 @@ export class TransactionBodyBuilder { // TODO: load pubkeys for sender and recipient user from db switch (transactionDraft.type) { case InputTransactionType.CREATION: + if (!this.recipientAccount) { + throw new LogError('missing recipient account for creation transaction!') + } this.body.creation = new GradidoCreation(transactionDraft, this.recipientAccount) this.body.data = 'gradidoCreation' break case InputTransactionType.SEND: case InputTransactionType.RECEIVE: + if (!this.recipientAccount || !this.signingAccount) { + throw new LogError('missing signing and/or recipient account for transfer transaction!') + } this.body.transfer = new GradidoTransfer( transactionDraft, this.signingAccount, diff --git a/dlt-connector/src/graphql/enum/TransactionErrorType.ts b/dlt-connector/src/graphql/enum/TransactionErrorType.ts index 7f1902c3d..8238eae08 100644 --- a/dlt-connector/src/graphql/enum/TransactionErrorType.ts +++ b/dlt-connector/src/graphql/enum/TransactionErrorType.ts @@ -7,6 +7,9 @@ export enum TransactionErrorType { DB_ERROR = 'DB Error', PROTO_DECODE_ERROR = 'Proto Decode Error', PROTO_ENCODE_ERROR = 'Proto Encode Error', + INVALID_SIGNATURE = 'Invalid Signature', + LOGIC_ERROR = 'Logic Error', + NOT_FOUND = 'Not found', } registerEnumType(TransactionErrorType, { diff --git a/dlt-connector/src/graphql/input/TransactionDraft.ts b/dlt-connector/src/graphql/input/TransactionDraft.ts index a94c57354..3cd497eec 100755 --- a/dlt-connector/src/graphql/input/TransactionDraft.ts +++ b/dlt-connector/src/graphql/input/TransactionDraft.ts @@ -2,11 +2,11 @@ import { Decimal } from 'decimal.js-light' import { InputTransactionType } from '@enum/InputTransactionType' -import { InputType, Field } from 'type-graphql' +import { InputType, Field, Int } from 'type-graphql' import { UserIdentifier } from './UserIdentifier' import { isValidDateString } from '@validator/DateString' import { IsPositiveDecimal } from '@validator/Decimal' -import { IsEnum, IsObject, ValidateNested } from 'class-validator' +import { IsEnum, IsObject, IsPositive, ValidateNested } from 'class-validator' @InputType() export class TransactionDraft { @@ -20,6 +20,10 @@ export class TransactionDraft { @ValidateNested() recipientUser: UserIdentifier + @Field(() => Int) + @IsPositive() + backendTransactionId: number + @Field(() => Decimal) @IsPositiveDecimal() amount: Decimal diff --git a/dlt-connector/src/graphql/model/TransactionRecipe.ts b/dlt-connector/src/graphql/model/TransactionRecipe.ts index e5e1c74fc..3b37ba4ea 100644 --- a/dlt-connector/src/graphql/model/TransactionRecipe.ts +++ b/dlt-connector/src/graphql/model/TransactionRecipe.ts @@ -1,10 +1,10 @@ import { Field, Int, ObjectType } from 'type-graphql' -import { TransactionRecipe as TransactionRecipeEntity } from '@entity/TransactionRecipe' import { TransactionType } from '@enum/TransactionType' +import { Transaction } from '@entity/Transaction' @ObjectType() export class TransactionRecipe { - public constructor({ id, createdAt, type, senderCommunity }: TransactionRecipeEntity) { + public constructor({ id, createdAt, type, senderCommunity }: Transaction) { this.id = id this.createdAt = createdAt.toString() this.type = type diff --git a/dlt-connector/src/graphql/model/TransactionResult.ts b/dlt-connector/src/graphql/model/TransactionResult.ts index dfa28cf1b..bc443ad1f 100644 --- a/dlt-connector/src/graphql/model/TransactionResult.ts +++ b/dlt-connector/src/graphql/model/TransactionResult.ts @@ -24,4 +24,4 @@ export class TransactionResult { @Field(() => Boolean) succeed: boolean -} \ No newline at end of file +} diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.ts index 2259f604c..9b6d8f3f2 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.ts @@ -59,7 +59,7 @@ export class CommunityResolver { // TODO: write tests to make sure that it doesn't throw const addCommunityContext = new AddCommunityContext(communityDraft, topic) try { - // actually run interaction, create community, accounts for foreign community and transactionRecipe + // actually run interaction, create community, accounts for foreign community and transactionRecipe await addCommunityContext.run() return new TransactionResult() } catch (error) { diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts index 96f6dff65..e2b558668 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -1,90 +1,39 @@ -import { Resolver, Query, Arg, Mutation } from 'type-graphql' +import { Resolver, Arg, Mutation } from 'type-graphql' import { TransactionDraft } from '@input/TransactionDraft' import { TransactionResult } from '../model/TransactionResult' import { TransactionError } from '../model/TransactionError' +import { CreateTransactionRecipeContext } from '@/interactions/backendToDb/transaction/CreateTransationRecipe.context' +import { TransactionRecipe } from '../model/TransactionRecipe' +import { TransactionRepository } from '@/data/Transaction.repository' +import { TransactionErrorType } from '../enum/TransactionErrorType' @Resolver() export class TransactionResolver { - // Why a dummy function? - // to prevent this error by start: - // GeneratingSchemaError: Some errors occurred while generating GraphQL schema: - // Type Query must define one or more fields. - // it seems that at least one query must be defined - // https://github.com/ardatan/graphql-tools/issues/764 - @Query(() => String) - version(): string { - return '0.1' - } - @Mutation(() => TransactionResult) async sendTransaction( @Arg('data') - transaction: TransactionDraft, + transactionDraft: TransactionDraft, ): Promise { + const createTransactionRecipeContext = new CreateTransactionRecipeContext(transactionDraft) try { - logger.info('sendTransaction call', transaction) - const signingAccount = await findAccountByUserIdentifier(transaction.senderUser) - if (!signingAccount) { - throw new TransactionError( - TransactionErrorType.NOT_FOUND, - "couldn't found sender user account in db", + await createTransactionRecipeContext.run() + const transactionRecipe = createTransactionRecipeContext.getTransactionRecipe() + transactionRecipe.save() + return new TransactionResult(new TransactionRecipe(transactionRecipe)) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (error: any) { + if (error.code === 'ER_DUP_ENTRY') { + const existingRecipe = await TransactionRepository.findBySignature( + createTransactionRecipeContext.getTransactionRecipe().signature, ) - } - logger.info('signing account', signingAccount) - - const recipientAccount = await findAccountByUserIdentifier(transaction.recipientUser) - if (!recipientAccount) { - throw new TransactionError( - TransactionErrorType.NOT_FOUND, - "couldn't found recipient user account in db", - ) - } - logger.info('recipient account', recipientAccount) - - const body = createTransactionBody(transaction, signingAccount, recipientAccount) - logger.info('body', body) - const gradidoTransaction = createGradidoTransaction(body) - - const signingKeyPair = getKeyPair(signingAccount) - if (!signingKeyPair) { - throw new TransactionError( - TransactionErrorType.NOT_FOUND, - "couldn't found signing key pair", - ) - } - logger.info('key pair for signing', signingKeyPair) - - KeyManager.getInstance().sign(gradidoTransaction, [signingKeyPair]) - const recipeTransactionController = await TransactionRecipe.create({ - transaction: gradidoTransaction, - senderUser: transaction.senderUser, - recipientUser: transaction.recipientUser, - signingAccount, - recipientAccount, - backendTransactionId: transaction.backendTransactionId, - }) - try { - await recipeTransactionController.getTransactionRecipeEntity().save() - ConditionalSleepManager.getInstance().signal(TRANSMIT_TO_IOTA_SLEEP_CONDITION_KEY) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } catch (error: any) { - if (error.code === 'ER_DUP_ENTRY' && body.type === CrossGroupType.LOCAL) { - const existingRecipe = await findBySignature( - gradidoTransaction.sigMap.sigPair[0].signature, + if (!existingRecipe) { + throw new TransactionError( + TransactionErrorType.LOGIC_ERROR, + "recipe cannot be added because signature exist but couldn't load this existing receipt", ) - if (!existingRecipe) { - throw new TransactionError( - TransactionErrorType.LOGIC_ERROR, - "recipe cannot be added because signature exist but couldn't load this existing receipt", - ) - } - return new TransactionResult(new TransactionRecipeOutput(existingRecipe)) - } else { - throw error } + return new TransactionResult(new TransactionRecipe(existingRecipe)) } - return new TransactionResult() - } catch (error) { if (error instanceof TransactionError) { return new TransactionResult(error) } else { diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index 4ae946498..cd52d6de1 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -1,16 +1,19 @@ import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { Community } from '@entity/Community' import { CommunityRole } from './Community.role' -import { QueryRunner } from 'typeorm' import { Transaction } from '@entity/Transaction' import { KeyManager } from '@/controller/KeyManager' import { AccountFactory } from '@/data/Account.factory' import { CreateTransactionRecipeContext } from '../transaction/CreateTransationRecipe.context' +import { logger } from '@/server/logger' +import { TransactionError } from '@/graphql/model/TransactionError' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { getDataSource } from '@/typeorm/DataSource' export class HomeCommunityRole extends CommunityRole { private transactionRecipe: Transaction - public create(communityDraft: CommunityDraft, topic: string): void { + public async create(communityDraft: CommunityDraft, topic: string): Promise { super.create(communityDraft, topic) // generate key pair for signing transactions and deriving all keys for community const keyPair = KeyManager.generateKeyPair() @@ -26,22 +29,22 @@ export class HomeCommunityRole extends CommunityRole { const transactionRecipeContext = new CreateTransactionRecipeContext(communityDraft) transactionRecipeContext.setCommunity(this.self) - transactionRecipeContext.run() + await transactionRecipeContext.run() this.transactionRecipe = transactionRecipeContext.getTransactionRecipe() } - public store(): Promise { - - } - - public async addCommunity(communityDraft: CommunityDraft, topic: string): Promise { - const community = createHomeCommunity(communityDraft, topic) - - createCommunityRootTransactionRecipe(communityDraft, community).storeAsTransaction( - async (queryRunner: QueryRunner): Promise => { - await queryRunner.manager.save(community) - }, - ) - return community.save() + public async store(): Promise { + try { + return await getDataSource().transaction(async (transactionalEntityManager) => { + await transactionalEntityManager.save(this.transactionRecipe) + return await transactionalEntityManager.save(this.self) + }) + } catch (error) { + logger.error('error saving home community into db: %s', error) + throw new TransactionError( + TransactionErrorType.DB_ERROR, + 'error saving home community into db', + ) + } } } diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts index 454dd5b41..a5da13dcd 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -27,7 +27,7 @@ export class CreateTransactionRecipeContext { this.community = community } - public getCommunity() { + public getCommunity(): Community | undefined { return this.community } @@ -35,9 +35,10 @@ export class CreateTransactionRecipeContext { return this.transactionRecipeRole.getTransaction() } - public run(): void { + public async run(): Promise { if (this.draft instanceof TransactionDraft) { - this.transactionRecipeRole = new TransactionRecipeRole().create(this.draft) + this.transactionRecipeRole = new TransactionRecipeRole() + await this.transactionRecipeRole.create(this.draft) } else if (this.draft instanceof CommunityDraft) { if (!this.community) { throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community was not set') diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 4a432f67e..4107a37b1 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -1,12 +1,12 @@ +import { AccountRepository } from '@/data/Account.repository' +import { KeyPair } from '@/data/KeyPair' import { TransactionBuilder } from '@/data/Transaction.builder' +import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' -import { TransactionRecipe } from '@/graphql/model/TransactionRecipe' -import { TransactionResult } from '@/graphql/model/TransactionResult' -import { logger } from '@/server/logger' -import { getDataSource } from '@/typeorm/DataSource' -import { QueryRunner } from 'typeorm' +import { sign } from '@/utils/cryptoHelper' +import { Transaction } from '@entity/Transaction' export class TransactionRecipeRole { protected transactionBuilder: TransactionBuilder @@ -14,40 +14,50 @@ export class TransactionRecipeRole { this.transactionBuilder = new TransactionBuilder() } - public create(transactionDraft: TransactionDraft): TransactionRecipeRole { + public async create(transactionDraft: TransactionDraft): Promise { + const senderUser = transactionDraft.senderUser + const recipientUser = transactionDraft.recipientUser + + // loading signing and recipient account + // TODO: look for ways to use only one db call for both + const signingAccount = await AccountRepository.findAccountByUserIdentifier(senderUser) + if (!signingAccount) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found sender user account in db", + ) + } + const recipientAccount = await AccountRepository.findAccountByUserIdentifier(recipientUser) + if (!recipientAccount) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found recipient user account in db", + ) + } + + // create proto transaction body + const transactionBodyBuilder = new TransactionBodyBuilder() + .setSigningAccount(signingAccount) + .setRecipientAccount(recipientAccount) + .fromTransactionDraft(transactionDraft) + // build transaction entity + + this.transactionBuilder + .fromTransactionBodyBuilder(transactionBodyBuilder) + .setBackendTransactionId(transactionDraft.backendTransactionId) + await this.transactionBuilder.setSenderCommunityFromSenderUser(senderUser) + if (recipientUser.uuid !== senderUser.uuid) { + await this.transactionBuilder.setRecipientCommunityFromRecipientUser(recipientUser) + } + const transaction = this.transactionBuilder.getTransaction() + // sign + this.transactionBuilder.setSignature( + sign(transaction.bodyBytes, new KeyPair(this.transactionBuilder.getSenderCommunity())), + ) return this } public getTransaction(): Transaction { return this.transactionBuilder.getTransaction() } - - public async storeAsTransaction( - transactionFunction: (queryRunner: QueryRunner) => Promise, - ): Promise { - const queryRunner = getDataSource().createQueryRunner() - await queryRunner.connect() - await queryRunner.startTransaction() - - let result: TransactionResult - try { - const transactionRecipe = this.transactionBuilder.build() - await transactionFunction(queryRunner) - await queryRunner.manager.save(transactionRecipe) - await queryRunner.commitTransaction() - result = new TransactionResult(new TransactionRecipe(transactionRecipe)) - } catch (err) { - logger.error('error saving new transaction recipe into db: %s', err) - result = new TransactionResult( - new TransactionError( - TransactionErrorType.DB_ERROR, - 'error saving transaction recipe into db', - ), - ) - await queryRunner.rollbackTransaction() - } finally { - await queryRunner.release() - } - return result - } } From b5b1eb8a297be78d88999f956ce91bde1a4207aa Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Mon, 30 Oct 2023 15:02:32 +0100 Subject: [PATCH 04/47] changed controller to manager --- dlt-connector/src/data/Account.factory.ts | 2 +- .../interactions/backendToDb/community/HomeCommunity.role.ts | 2 +- dlt-connector/src/{controller => manager}/KeyManager.test.ts | 0 dlt-connector/src/{controller => manager}/KeyManager.ts | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename dlt-connector/src/{controller => manager}/KeyManager.test.ts (100%) rename dlt-connector/src/{controller => manager}/KeyManager.ts (100%) diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index c3ad02fa7..35555a590 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -1,4 +1,4 @@ -import { KeyManager } from '@/controller/KeyManager' +import { KeyManager } from '@/manager/KeyManager' import { KeyPair } from '@/data/KeyPair' import { AddressType } from '@/data/proto/3_3/enum/AddressType' import { hardenDerivationIndex } from '@/utils/derivationHelper' diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index cd52d6de1..f78abb8f6 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -2,7 +2,7 @@ import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { Community } from '@entity/Community' import { CommunityRole } from './Community.role' import { Transaction } from '@entity/Transaction' -import { KeyManager } from '@/controller/KeyManager' +import { KeyManager } from '@/manager/KeyManager' import { AccountFactory } from '@/data/Account.factory' import { CreateTransactionRecipeContext } from '../transaction/CreateTransationRecipe.context' import { logger } from '@/server/logger' diff --git a/dlt-connector/src/controller/KeyManager.test.ts b/dlt-connector/src/manager/KeyManager.test.ts similarity index 100% rename from dlt-connector/src/controller/KeyManager.test.ts rename to dlt-connector/src/manager/KeyManager.test.ts diff --git a/dlt-connector/src/controller/KeyManager.ts b/dlt-connector/src/manager/KeyManager.ts similarity index 100% rename from dlt-connector/src/controller/KeyManager.ts rename to dlt-connector/src/manager/KeyManager.ts From f6264879bae3b0372c20a03a8100a0bce21987d2 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 31 Oct 2023 16:12:19 +0100 Subject: [PATCH 05/47] fix community resolver test and riddle why db had stopped working in test --- dlt-connector/jest.config.js | 1 + dlt-connector/src/data/Account.factory.ts | 1 + dlt-connector/src/data/Account.repository.ts | 4 +- .../src/data/Community.repository.ts | 16 +-- .../src/data/Transaction.repository.ts | 5 +- dlt-connector/src/data/User.repository.ts | 23 +++++ .../data/proto/3_3/ConfirmedTransaction.ts | 1 - .../resolver/CommunityResolver.test.ts | 36 +++---- .../resolver/TransactionsResolver.test.ts | 42 ++++---- dlt-connector/src/graphql/schema.ts | 1 + .../community/AddCommunity.context.ts | 2 +- .../backendToDb/community/Community.role.ts | 2 +- .../community/HomeCommunity.role.ts | 5 +- .../transaction/TransactionRecipe.role.ts | 8 +- dlt-connector/src/manager/KeyManager.ts | 7 +- dlt-connector/src/server/createServer.ts | 3 + dlt-connector/src/typeorm/DBVersion.ts | 28 ------ dlt-connector/src/typeorm/DataSource.ts | 97 +++++++++++++++---- .../Transaction.ts | 20 ++-- .../0003-refactor_transaction_recipe.ts | 24 ++--- 20 files changed, 197 insertions(+), 129 deletions(-) create mode 100644 dlt-connector/src/data/User.repository.ts delete mode 100644 dlt-connector/src/typeorm/DBVersion.ts diff --git a/dlt-connector/jest.config.js b/dlt-connector/jest.config.js index 723aa840b..ae7931cdf 100644 --- a/dlt-connector/jest.config.js +++ b/dlt-connector/jest.config.js @@ -17,6 +17,7 @@ module.exports = { '@arg/(.*)': '/src/graphql/arg/$1', '@controller/(.*)': '/src/controller/$1', '@enum/(.*)': '/src/graphql/enum/$1', + '@model/(.*)': '/src/graphql/model/$1', '@resolver/(.*)': '/src/graphql/resolver/$1', '@input/(.*)': '/src/graphql/input/$1', '@proto/(.*)': '/src/proto/$1', diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index 35555a590..14cc68351 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -21,6 +21,7 @@ export class AccountFactory { account.type = type.valueOf() account.createdAt = createdAt account.balance = new Decimal(0) + account.balanceCreatedAt = new Decimal(0) return account } diff --git a/dlt-connector/src/data/Account.repository.ts b/dlt-connector/src/data/Account.repository.ts index 2a228c261..ea97080fd 100644 --- a/dlt-connector/src/data/Account.repository.ts +++ b/dlt-connector/src/data/Account.repository.ts @@ -8,12 +8,12 @@ export const AccountRepository = getDataSource() .getRepository(Account) .extend({ findAccountsByPublicKeys(publicKeys: Buffer[]): Promise { - return Account.findBy({ derive2Pubkey: In(publicKeys) }) + return this.findBy({ derive2Pubkey: In(publicKeys) }) }, async findAccountByPublicKey(publicKey: Buffer | undefined): Promise { if (!publicKey) return undefined - return (await Account.findOneBy({ derive2Pubkey: Buffer.from(publicKey) })) ?? undefined + return (await this.findOneBy({ derive2Pubkey: Buffer.from(publicKey) })) ?? undefined }, async findAccountByUserIdentifier({ diff --git a/dlt-connector/src/data/Community.repository.ts b/dlt-connector/src/data/Community.repository.ts index 1624404d3..848d7b962 100644 --- a/dlt-connector/src/data/Community.repository.ts +++ b/dlt-connector/src/data/Community.repository.ts @@ -16,14 +16,14 @@ export const CommunityRepository = getDataSource() async isExist(community: CommunityDraft | string): Promise { const iotaTopic = community instanceof CommunityDraft ? iotaTopicFromCommunityUUID(community.uuid) : community - const result = await Community.find({ + const result = await this.find({ where: { iotaTopic }, }) return result.length > 0 }, async findByCommunityArg({ uuid, foreign, confirmed }: CommunityArg): Promise { - return await Community.find({ + return await this.find({ where: { ...(uuid && { iotaTopic: iotaTopicFromCommunityUUID(uuid) }), ...(foreign && { foreign }), @@ -33,15 +33,15 @@ export const CommunityRepository = getDataSource() }, async findByCommunityUuid(communityUuid: string): Promise { - return await Community.findOneBy({ iotaTopic: iotaTopicFromCommunityUUID(communityUuid) }) + return await this.findOneBy({ iotaTopic: iotaTopicFromCommunityUUID(communityUuid) }) }, async findByIotaTopic(iotaTopic: string): Promise { - return await Community.findOneBy({ iotaTopic }) + return await this.findOneBy({ iotaTopic }) }, findCommunitiesByTopics(topics: string[]): Promise { - return Community.findBy({ iotaTopic: In(topics) }) + return this.findBy({ iotaTopic: In(topics) }) }, async getCommunityForUserIdentifier( @@ -51,18 +51,18 @@ export const CommunityRepository = getDataSource() throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community uuid not set') } return ( - (await Community.findOneBy({ + (await this.findOneBy({ iotaTopic: iotaTopicFromCommunityUUID(identifier.communityUuid), })) ?? undefined ) }, findAll(select: FindOptionsSelect): Promise { - return Community.find({ select }) + return this.find({ select }) }, async loadHomeCommunityKeyPair(): Promise { - const community = await Community.findOneOrFail({ + const community = await this.findOneOrFail({ where: { foreign: false }, select: { rootChaincode: true, rootPubkey: true, rootPrivkey: true }, }) diff --git a/dlt-connector/src/data/Transaction.repository.ts b/dlt-connector/src/data/Transaction.repository.ts index 5a2a185bf..8a1eac02e 100644 --- a/dlt-connector/src/data/Transaction.repository.ts +++ b/dlt-connector/src/data/Transaction.repository.ts @@ -43,6 +43,9 @@ export const TransactionRepository = getDataSource() return { existingTransactions, missingMessageIdsHex } }, async removeConfirmedTransaction(transactions: Transaction[]): Promise { - return transactions.filter((transaction: Transaction) => transaction.runningHash.length === 0) + return transactions.filter( + (transaction: Transaction) => + transaction.runningHash === undefined || transaction.runningHash.length === 0, + ) }, }) diff --git a/dlt-connector/src/data/User.repository.ts b/dlt-connector/src/data/User.repository.ts new file mode 100644 index 000000000..abd64ac46 --- /dev/null +++ b/dlt-connector/src/data/User.repository.ts @@ -0,0 +1,23 @@ +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { getDataSource } from '@/typeorm/DataSource' +import { Account } from '@entity/Account' +import { User } from '@entity/User' + +export const UserRepository = getDataSource() + .getRepository(User) + .extend({ + async findAccountByUserIdentifier({ + uuid, + accountNr, + }: UserIdentifier): Promise { + const user = await this.findOne({ + where: { gradidoID: uuid, accounts: { derivationIndex: accountNr ?? 1 } }, + relations: { accounts: true }, + }) + if (user && user.accounts?.length === 1) { + const account = user.accounts[0] + account.user = user + return account + } + }, + }) diff --git a/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts index ce88a54ae..9c6491128 100644 --- a/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts +++ b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts @@ -2,7 +2,6 @@ import { Field, Message } from 'protobufjs' import { GradidoTransaction } from './GradidoTransaction' import { TimestampSeconds } from './TimestampSeconds' import { base64ToBuffer } from '@/utils/typeConverter' -import Long from 'long' /* id will be set by Node server diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts index 7f1f3ea3c..9b106b3f6 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts @@ -1,34 +1,35 @@ import 'reflect-metadata' import { ApolloServer } from '@apollo/server' +import { TestDB } from '@test/TestDB' import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' -import { TestDB } from '@test/TestDB' -import { TransactionResult } from '../model/TransactionResult' +import { TransactionResult } from '@model/TransactionResult' +import { CONFIG } from '@/config' + +CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' + +const con = TestDB.instance + +jest.mock('@typeorm/DataSource', () => ({ + getDataSource: jest.fn(() => TestDB.instance.dbConnect), +})) let apolloTestServer: ApolloServer -jest.mock('@typeorm/DataSource', () => ({ - getDataSource: () => TestDB.instance.dbConnect, -})) - describe('graphql/resolver/CommunityResolver', () => { beforeAll(async () => { + await con.setupTestDB() apolloTestServer = await createApolloTestServer() }) + afterAll(async () => { + await con.teardownTestDB() + }) describe('tests with db', () => { - beforeAll(async () => { - await TestDB.instance.setupTestDB() - // apolloTestServer = await createApolloTestServer() - }) - - afterAll(async () => { - await TestDB.instance.teardownTestDB() - }) - it('test add foreign community', async () => { const response = await apolloTestServer.executeOperation({ - query: 'mutation ($input: CommunityDraft!) { addCommunity(data: $input) {succeed} }', + query: + 'mutation ($input: CommunityDraft!) { addCommunity(data: $input) {succeed, error {message}} }', variables: { input: { uuid: '3d813cbb-37fb-42ba-91df-831e1593ac29', @@ -45,7 +46,8 @@ describe('graphql/resolver/CommunityResolver', () => { it('test add home community', async () => { const response = await apolloTestServer.executeOperation({ - query: 'mutation ($input: CommunityDraft!) { addCommunity(data: $input) {succeed} }', + query: + 'mutation ($input: CommunityDraft!) { addCommunity(data: $input) {succeed, error {message}} }', variables: { input: { uuid: '3d823cad-37fb-41cd-91df-152e1593ac29', diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index 7c02a4306..716d5d235 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -1,8 +1,9 @@ import 'reflect-metadata' import { ApolloServer } from '@apollo/server' +import { TestDB } from '@test/TestDB' import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' -import { TransactionResult } from '../model/TransactionResult' +import { TransactionResult } from '@model/TransactionResult' let apolloTestServer: ApolloServer @@ -14,26 +15,24 @@ jest.mock('@/client/IotaClient', () => { } }) +jest.mock('@typeorm/DataSource', () => ({ + getDataSource: jest.fn(() => TestDB.instance.dbConnect), +})) + describe('Transaction Resolver Test', () => { beforeAll(async () => { apolloTestServer = await createApolloTestServer() + await TestDB.instance.setupTestDB() }) - it('test version query', async () => { - const response = await apolloTestServer.executeOperation({ - query: '{ version }', - }) - // Note the use of Node's assert rather than Jest's expect; if using - // TypeScript, `assert`` will appropriately narrow the type of `body` - // and `expect` will not. - // Source: https://www.apollographql.com/docs/apollo-server/testing/testing - assert(response.body.kind === 'single') - expect(response.body.singleResult.errors).toBeUndefined() - expect(response.body.singleResult.data?.version).toBe('0.1') + + afterAll(async () => { + await TestDB.instance.teardownTestDB() }) + it('test mocked sendTransaction', async () => { const response = await apolloTestServer.executeOperation({ query: - 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { senderUser: { @@ -45,21 +44,20 @@ describe('Transaction Resolver Test', () => { type: 'SEND', amount: '10', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) assert(response.body.kind === 'single') expect(response.body.singleResult.errors).toBeUndefined() const transactionResult = response.body.singleResult.data?.sendTransaction as TransactionResult - expect(transactionResult.messageId).toBe( - '5498130bc3918e1a7143969ce05805502417e3e1bd596d3c44d6a0adeea22710', - ) + expect(transactionResult.succeed).toBe(true) }) it('test mocked sendTransaction invalid transactionType ', async () => { const response = await apolloTestServer.executeOperation({ query: - 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { senderUser: { @@ -71,6 +69,7 @@ describe('Transaction Resolver Test', () => { type: 'INVALID', amount: '10', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) @@ -88,7 +87,7 @@ describe('Transaction Resolver Test', () => { it('test mocked sendTransaction invalid amount ', async () => { const response = await apolloTestServer.executeOperation({ query: - 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { senderUser: { @@ -100,6 +99,7 @@ describe('Transaction Resolver Test', () => { type: 'SEND', amount: 'no number', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) @@ -117,7 +117,7 @@ describe('Transaction Resolver Test', () => { it('test mocked sendTransaction invalid created date ', async () => { const response = await apolloTestServer.executeOperation({ query: - 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, messageId} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { senderUser: { @@ -129,6 +129,7 @@ describe('Transaction Resolver Test', () => { type: 'SEND', amount: '10', createdAt: 'not valid', + backendTransactionId: 1, }, }, }) @@ -156,7 +157,7 @@ describe('Transaction Resolver Test', () => { 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} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { senderUser: { @@ -168,6 +169,7 @@ describe('Transaction Resolver Test', () => { type: 'CREATION', amount: '10', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) diff --git a/dlt-connector/src/graphql/schema.ts b/dlt-connector/src/graphql/schema.ts index fc9c26919..ac3119d1a 100755 --- a/dlt-connector/src/graphql/schema.ts +++ b/dlt-connector/src/graphql/schema.ts @@ -10,6 +10,7 @@ export const schema = async (): Promise => { return buildSchema({ resolvers: [TransactionResolver, CommunityResolver], scalarsMap: [{ type: Decimal, scalar: DecimalScalar }], + emitSchemaFile: true, validate: { validationError: { target: false }, skipMissingProperties: true, diff --git a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts index f2518d45a..ff46de4d3 100644 --- a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -24,7 +24,7 @@ export class AddCommunityContext { } public async run(): Promise { - this.communityRole.create(this.communityDraft, this.iotaTopic) + await this.communityRole.create(this.communityDraft, this.iotaTopic) await this.communityRole.store() } } diff --git a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts index f2fa7d0ac..f08dc25a0 100644 --- a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts @@ -10,7 +10,7 @@ export abstract class CommunityRole { this.self = Community.create() } - public create(communityDraft: CommunityDraft, topic: string): void { + public async create(communityDraft: CommunityDraft, topic: string): Promise { this.self.iotaTopic = topic this.self.createdAt = new Date(communityDraft.createdAt) this.self.foreign = communityDraft.foreign diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index f78abb8f6..a4438f780 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -35,12 +35,15 @@ export class HomeCommunityRole extends CommunityRole { public async store(): Promise { try { + console.log('store transaction: %s', JSON.stringify(this.transactionRecipe, null, 2)) return await getDataSource().transaction(async (transactionalEntityManager) => { + const community = await transactionalEntityManager.save(this.self) await transactionalEntityManager.save(this.transactionRecipe) - return await transactionalEntityManager.save(this.self) + return community }) } catch (error) { logger.error('error saving home community into db: %s', error) + console.log(error) throw new TransactionError( TransactionErrorType.DB_ERROR, 'error saving home community into db', diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 4107a37b1..9fb53f3be 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -1,6 +1,7 @@ import { AccountRepository } from '@/data/Account.repository' import { KeyPair } from '@/data/KeyPair' import { TransactionBuilder } from '@/data/Transaction.builder' +import { UserRepository } from '@/data/User.repository' import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { TransactionDraft } from '@/graphql/input/TransactionDraft' @@ -10,7 +11,8 @@ import { Transaction } from '@entity/Transaction' export class TransactionRecipeRole { protected transactionBuilder: TransactionBuilder - construct() { + + public constructor() { this.transactionBuilder = new TransactionBuilder() } @@ -20,14 +22,14 @@ export class TransactionRecipeRole { // loading signing and recipient account // TODO: look for ways to use only one db call for both - const signingAccount = await AccountRepository.findAccountByUserIdentifier(senderUser) + const signingAccount = await UserRepository.findAccountByUserIdentifier(senderUser) if (!signingAccount) { throw new TransactionError( TransactionErrorType.NOT_FOUND, "couldn't found sender user account in db", ) } - const recipientAccount = await AccountRepository.findAccountByUserIdentifier(recipientUser) + const recipientAccount = await UserRepository.findAccountByUserIdentifier(recipientUser) if (!recipientAccount) { throw new TransactionError( TransactionErrorType.NOT_FOUND, diff --git a/dlt-connector/src/manager/KeyManager.ts b/dlt-connector/src/manager/KeyManager.ts index df1e61b33..2e8b615aa 100644 --- a/dlt-connector/src/manager/KeyManager.ts +++ b/dlt-connector/src/manager/KeyManager.ts @@ -3,12 +3,7 @@ import { randombytes_buf } from 'sodium-native' import { CONFIG } from '../config' import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' // https://www.npmjs.com/package/bip32-ed25519?activeTab=code -import { - generateFromSeed, - derivePrivate, - sign as ed25519Sign, - verify as ed25519Verify, -} from 'bip32-ed25519' +import { generateFromSeed, derivePrivate, sign as ed25519Sign } from 'bip32-ed25519' import { logger } from '@/server/logger' import { LogError } from '@/server/LogError' import { KeyPair } from '@/data/KeyPair' diff --git a/dlt-connector/src/server/createServer.ts b/dlt-connector/src/server/createServer.ts index 00ba0a912..f3a3b1de7 100755 --- a/dlt-connector/src/server/createServer.ts +++ b/dlt-connector/src/server/createServer.ts @@ -11,6 +11,7 @@ import { logger as dltLogger } from './logger' import { Logger } from 'log4js' import cors from 'cors' import bodyParser from 'body-parser' +import { Connection } from '@/typeorm/DataSource' type ServerDef = { apollo: ApolloServer; app: Express } @@ -27,6 +28,8 @@ const createServer = async ( logger.addContext('user', 'unknown') logger.debug('createServer...') + // connect to db and test db version + await Connection.getInstance().init() // Express Server const app = express() diff --git a/dlt-connector/src/typeorm/DBVersion.ts b/dlt-connector/src/typeorm/DBVersion.ts deleted file mode 100644 index 14da39368..000000000 --- a/dlt-connector/src/typeorm/DBVersion.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Migration } from '@entity/Migration' - -import { logger } from '@/server/logger' - -const getDBVersion = async (): Promise => { - try { - const [dbVersion] = await Migration.find({ order: { version: 'DESC' }, take: 1 }) - return dbVersion ? dbVersion.fileName : null - } catch (error) { - logger.error(error) - return null - } -} - -const checkDBVersion = async (DB_VERSION: string): Promise => { - const dbVersion = await getDBVersion() - if (!dbVersion?.includes(DB_VERSION)) { - logger.error( - `Wrong database version detected - the backend requires '${DB_VERSION}' but found '${ - dbVersion ?? 'None' - }`, - ) - return false - } - return true -} - -export { checkDBVersion, getDBVersion } diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index eafa977aa..1dab441c2 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -4,23 +4,84 @@ import { DataSource as DBDataSource, FileLogger } from '@dbTools/typeorm' import { entities } from '@entity/index' import { CONFIG } from '@/config' +import { logger } from '@/server/logger' +import { Migration } from '@entity/Migration' +import { LogError } from '@/server/LogError' -const DataSource = new DBDataSource({ - type: 'mysql', - host: CONFIG.DB_HOST, - port: CONFIG.DB_PORT, - username: CONFIG.DB_USER, - password: CONFIG.DB_PASSWORD, - database: CONFIG.DB_DATABASE, - entities, - synchronize: false, - logging: true, - logger: new FileLogger('all', { - logPath: CONFIG.TYPEORM_LOGGING_RELATIVE_PATH, - }), - extra: { - charset: 'utf8mb4_unicode_ci', - }, -}) +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export class Connection { + // eslint-disable-next-line no-use-before-define + private static instance: Connection + private connection: DBDataSource -export const getDataSource = () => DataSource + /** + * The Singleton's constructor should always be private to prevent direct + * construction calls with the `new` operator. + */ + // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function + private constructor() { + this.connection = new DBDataSource({ + type: 'mysql', + host: CONFIG.DB_HOST, + port: CONFIG.DB_PORT, + username: CONFIG.DB_USER, + password: CONFIG.DB_PASSWORD, + database: CONFIG.DB_DATABASE, + entities, + synchronize: false, + logging: true, + logger: new FileLogger('all', { + logPath: CONFIG.TYPEORM_LOGGING_RELATIVE_PATH, + }), + extra: { + charset: 'utf8mb4_unicode_ci', + }, + }) + } + + /** + * The static method that controls the access to the singleton instance. + * + * This implementation let you subclass the Singleton class while keeping + * just one instance of each subclass around. + */ + public static getInstance(): Connection { + if (!Connection.instance) { + Connection.instance = new Connection() + } + return Connection.instance + } + + public getDataSource(): DBDataSource { + console.log('production getDataSource called!') + return this.connection + } + + public async init(): Promise { + await this.connection.initialize() + try { + await Connection.getInstance() + } catch (error) { + // try and catch for logging + logger.fatal(`Couldn't open connection to database!`) + throw error + } + + // check for correct database version + await this.checkDBVersion(CONFIG.DB_VERSION) + } + + async checkDBVersion(DB_VERSION: string): Promise { + const dbVersion = await Migration.findOneOrFail({ order: { version: 'DESC' } }) + // return dbVersion ? dbVersion.fileName : null + if (!dbVersion.fileName.includes(DB_VERSION)) { + throw new LogError( + `Wrong database version detected - the backend requires '${DB_VERSION}' but found '${ + dbVersion ?? 'None' + }`, + ) + } + } +} + +export const getDataSource = () => Connection.getInstance().getDataSource() diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index ac48f07b6..f1167043f 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -76,9 +76,10 @@ export class Transaction extends BaseEntity { type: 'decimal', precision: 40, scale: 20, + nullable: true, transformer: DecimalTransformer, }) - accountBalanceCreatedAt: Decimal + accountBalanceCreatedAt?: Decimal @Column({ type: 'tinyint' }) type: number @@ -95,26 +96,25 @@ export class Transaction extends BaseEntity { @Column({ name: 'protocol_version', type: 'varchar', length: 255, default: '1' }) protocolVersion: string - @Column({ type: 'bigint' }) - nr: number + @Column({ type: 'bigint', nullable: true }) + nr?: number - @Column({ name: 'running_hash', type: 'binary', length: 48 }) - runningHash: Buffer + @Column({ name: 'running_hash', type: 'binary', length: 48, nullable: true }) + runningHash?: Buffer @Column({ name: 'account_balance', type: 'decimal', precision: 40, scale: 20, - nullable: false, - default: 0, + nullable: true, transformer: DecimalTransformer, }) - accountBalanceConfirmedAt: Decimal + accountBalanceConfirmedAt?: Decimal @Column({ name: 'iota_milestone', type: 'bigint', nullable: true }) iotaMilestone?: number - @Column({ name: 'confirmed_at', type: 'datetime' }) - confirmedAt: Date + @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) + confirmedAt?: Date } diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index 577b24938..5a6ba9a78 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -19,25 +19,25 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis await queryFn( `CREATE TABLE \`transactions\` ( \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, - \`iota_message_id\` varbinary(32) DEFAULT NULL, - \`backend_transaction_id\` bigint unsigned DEFAULT NULL, - \`paring_transaction_id\` bigint unsigned DEFAULT NULL, - \`signing_account_id\` int unsigned DEFAULT NULL, - \`recipient_account_id\` int unsigned DEFAULT NULL, + \`iota_message_id\` varbinary(32) NULL DEFAULT NULL, + \`backend_transaction_id\` bigint unsigned NULL DEFAULT NULL, + \`paring_transaction_id\` bigint unsigned NULL DEFAULT NULL, + \`signing_account_id\` int unsigned NULL DEFAULT NULL, + \`recipient_account_id\` int unsigned NULL DEFAULT NULL, \`sender_community_id\` int unsigned NOT NULL, - \`recipient_community_id\` int unsigned DEFAULT NULL, - \`amount\` decimal(40, 20) DEFAULT NULL, + \`recipient_community_id\` int unsigned NULL DEFAULT NULL, + \`amount\` decimal(40, 20) NULL DEFAULT NULL, \`account_balance_created_at\` decimal(40, 20) NOT NULL, \`type\` tinyint NOT NULL, \`created_at\` datetime(3) NOT NULL, \`body_bytes\` blob NOT NULL, \`signature\` varbinary(64) NOT NULL, \`protocol_version\` varchar(255) NOT NULL DEFAULT '1', - \`nr\` bigint NOT NULL, - \`running_hash\` varbinary(48) NOT NULL, - \`account_balance\` decimal(40, 20) NOT NULL DEFAULT 0.00000000000000000000, - \`iota_milestone\` bigint DEFAULT NULL, - \`confirmed_at\` datetime NOT NULL, + \`nr\` bigint NULL DEFAULT NULL, + \`running_hash\` varbinary(48) NULL DEFAULT NULL, + \`account_balance\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, + \`iota_milestone\` bigint NULL DEFAULT NULL, + \`confirmed_at\` datetime NULL DEFAULT NULL, PRIMARY KEY (\`id\`), UNIQUE KEY \`signature\` (\`signature\`), FOREIGN KEY (\`signing_account_id\`) REFERENCES accounts(id), From 7d31626a400903df4d90a676a282fd97f72bdc3a Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Wed, 1 Nov 2023 10:35:49 +0100 Subject: [PATCH 06/47] fix tests, added some more stuff from main dlt working branch --- dlt-connector/jest.config.js | 2 +- dlt-connector/src/data/Account.factory.ts | 25 ++++- dlt-connector/src/data/User.factory.ts | 16 ++++ dlt-connector/src/data/User.logic.ts | 41 ++++++++ dlt-connector/src/graphql/enum/AccountType.ts | 16 ++++ .../src/graphql/input/UserAccountDraft.ts | 23 +++++ .../resolver/CommunityResolver.test.ts | 1 + .../resolver/TransactionsResolver.test.ts | 93 ++++++++++++------- .../graphql/resolver/TransactionsResolver.ts | 2 +- .../community/AddCommunity.context.ts | 1 + .../community/HomeCommunity.role.ts | 2 - .../transaction/TransactionRecipe.role.ts | 1 - dlt-connector/src/utils/typeConverter.ts | 45 +++++++++ 13 files changed, 226 insertions(+), 42 deletions(-) create mode 100644 dlt-connector/src/data/User.factory.ts create mode 100644 dlt-connector/src/data/User.logic.ts create mode 100644 dlt-connector/src/graphql/enum/AccountType.ts create mode 100644 dlt-connector/src/graphql/input/UserAccountDraft.ts diff --git a/dlt-connector/jest.config.js b/dlt-connector/jest.config.js index ae7931cdf..1faef9414 100644 --- a/dlt-connector/jest.config.js +++ b/dlt-connector/jest.config.js @@ -6,7 +6,7 @@ module.exports = { collectCoverageFrom: ['src/**/*.ts', '!**/node_modules/**', '!src/seeds/**', '!build/**'], coverageThreshold: { global: { - lines: 77, + lines: 70, }, }, setupFiles: ['/test/testSetup.ts'], diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index 14cc68351..808551b87 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -4,20 +4,25 @@ import { AddressType } from '@/data/proto/3_3/enum/AddressType' import { hardenDerivationIndex } from '@/utils/derivationHelper' import { Account } from '@entity/Account' import Decimal from 'decimal.js-light' +import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' +import { accountTypeToAddressType } from '@/utils/typeConverter' const GMW_ACCOUNT_DERIVATION_INDEX = 1 const AUF_ACCOUNT_DERIVATION_INDEX = 2 export class AccountFactory { public static createAccount( - keyPair: KeyPair, createdAt: Date, derivationIndex: number, type: AddressType, + parentKeyPair?: KeyPair, ): Account { const account = Account.create() account.derivationIndex = derivationIndex - account.derive2Pubkey = KeyManager.getInstance().derive([derivationIndex], keyPair).publicKey + account.derive2Pubkey = KeyManager.getInstance().derive( + [derivationIndex], + parentKeyPair, + ).publicKey account.type = type.valueOf() account.createdAt = createdAt account.balance = new Decimal(0) @@ -25,21 +30,33 @@ export class AccountFactory { return account } + public static createAccountFromUserAccountDraft( + { createdAt, accountType, user }: UserAccountDraft, + parentKeyPair?: KeyPair, + ): Account { + return AccountFactory.createAccount( + new Date(createdAt), + user.accountNr ?? 1, + accountTypeToAddressType(accountType), + parentKeyPair, + ) + } + public static createGmwAccount(keyPair: KeyPair, createdAt: Date): Account { return AccountFactory.createAccount( - keyPair, createdAt, hardenDerivationIndex(GMW_ACCOUNT_DERIVATION_INDEX), AddressType.COMMUNITY_GMW, + keyPair, ) } public static createAufAccount(keyPair: KeyPair, createdAt: Date): Account { return AccountFactory.createAccount( - keyPair, createdAt, hardenDerivationIndex(AUF_ACCOUNT_DERIVATION_INDEX), AddressType.COMMUNITY_AUF, + keyPair, ) } } diff --git a/dlt-connector/src/data/User.factory.ts b/dlt-connector/src/data/User.factory.ts new file mode 100644 index 000000000..1844cff64 --- /dev/null +++ b/dlt-connector/src/data/User.factory.ts @@ -0,0 +1,16 @@ +import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' +import { User } from '@entity/User' +import { UserLogic } from './User.logic' +import { KeyPair } from './KeyPair' + +export class UserFactory { + static create(userAccountDraft: UserAccountDraft, parentKeys?: KeyPair): User { + const user = User.create() + user.createdAt = new Date(userAccountDraft.createdAt) + user.gradidoID = userAccountDraft.user.uuid + const userLogic = new UserLogic(user) + // store generated pubkey into entity + userLogic.calculateKeyPair(parentKeys) + return user + } +} diff --git a/dlt-connector/src/data/User.logic.ts b/dlt-connector/src/data/User.logic.ts new file mode 100644 index 000000000..58b441561 --- /dev/null +++ b/dlt-connector/src/data/User.logic.ts @@ -0,0 +1,41 @@ +import { User } from '@entity/User' +import { KeyPair } from './KeyPair' +import { LogError } from '@/server/LogError' +import { uuid4ToBuffer } from '@/utils/typeConverter' +import { hardenDerivationIndex } from '@/utils/derivationHelper' +import { KeyManager } from '@/manager/KeyManager' + +export class UserLogic { + // eslint-disable-next-line no-useless-constructor + constructor(private user: User) {} + + /** + * + * @param parentKeys if undefined use home community key pair + * @returns + */ + + calculateKeyPair = (parentKeys?: KeyPair): KeyPair => { + if (!this.user.gradidoID) { + throw new LogError('missing GradidoID for user.', { id: this.user.id }) + } + // example gradido id: 03857ac1-9cc2-483e-8a91-e5b10f5b8d16 => + // wholeHex: '03857ac19cc2483e8a91e5b10f5b8d16'] + const wholeHex = uuid4ToBuffer(this.user.gradidoID) + const parts = [] + for (let i = 0; i < 4; i++) { + parts[i] = hardenDerivationIndex(wholeHex.subarray(i * 4, (i + 1) * 4).readUInt32BE()) + } + // parts: [2206563009, 2629978174, 2324817329, 2405141782] + const keyPair = KeyManager.getInstance().derive(parts, parentKeys) + if (this.user.derive1Pubkey && this.user.derive1Pubkey.compare(keyPair.publicKey) !== 0) { + throw new LogError( + 'The freshly derived public key does not correspond to the stored public key', + ) + } + if (!this.user.derive1Pubkey) { + this.user.derive1Pubkey = keyPair.publicKey + } + return keyPair + } +} diff --git a/dlt-connector/src/graphql/enum/AccountType.ts b/dlt-connector/src/graphql/enum/AccountType.ts new file mode 100644 index 000000000..a6946275b --- /dev/null +++ b/dlt-connector/src/graphql/enum/AccountType.ts @@ -0,0 +1,16 @@ +import { registerEnumType } from 'type-graphql' + +export enum AccountType { + NONE = 'none', // if no address was found + COMMUNITY_HUMAN = 'COMMUNITY_HUMAN', // creation account for human + COMMUNITY_GMW = 'COMMUNITY_GMW', // community public budget account + COMMUNITY_AUF = 'COMMUNITY_AUF', // community compensation and environment founds account + COMMUNITY_PROJECT = 'COMMUNITY_PROJECT', // no creations allowed + SUBACCOUNT = 'SUBACCOUNT', // no creations allowed + CRYPTO_ACCOUNT = 'CRYPTO_ACCOUNT', // user control his keys, no creations +} + +registerEnumType(AccountType, { + name: 'AccountType', // this one is mandatory + description: 'Type of account', // this one is optional +}) diff --git a/dlt-connector/src/graphql/input/UserAccountDraft.ts b/dlt-connector/src/graphql/input/UserAccountDraft.ts new file mode 100644 index 000000000..bae9c0694 --- /dev/null +++ b/dlt-connector/src/graphql/input/UserAccountDraft.ts @@ -0,0 +1,23 @@ +// https://www.npmjs.com/package/@apollo/protobufjs + +import { InputType, Field } from 'type-graphql' +import { UserIdentifier } from './UserIdentifier' +import { isValidDateString } from '@validator/DateString' +import { IsEnum, IsObject, ValidateNested } from 'class-validator' +import { AccountType } from '@/graphql/enum/AccountType' + +@InputType() +export class UserAccountDraft { + @Field(() => UserIdentifier) + @IsObject() + @ValidateNested() + user: UserIdentifier + + @Field(() => String) + @isValidDateString() + createdAt: string + + @Field(() => AccountType) + @IsEnum(AccountType) + accountType: AccountType +} diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts index 9b106b3f6..2c402c537 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts @@ -1,5 +1,6 @@ import 'reflect-metadata' import { ApolloServer } from '@apollo/server' +// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories import { TestDB } from '@test/TestDB' import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index 716d5d235..cc5b27c76 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -1,9 +1,23 @@ import 'reflect-metadata' import { ApolloServer } from '@apollo/server' +// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories import { TestDB } from '@test/TestDB' import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' import { TransactionResult } from '@model/TransactionResult' +import { AccountFactory } from '@/data/Account.factory' +import { CONFIG } from '@/config' +import { KeyManager } from '@/manager/KeyManager' +import { UserFactory } from '@/data/User.factory' +import { UserAccountDraft } from '../input/UserAccountDraft' +import { UserLogic } from '@/data/User.logic' +import { AccountType } from '../enum/AccountType' +import { UserIdentifier } from '../input/UserIdentifier' +import { KeyPair } from '@/data/KeyPair' +import { CommunityDraft } from '../input/CommunityDraft' +import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' + +CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' let apolloTestServer: ApolloServer @@ -19,10 +33,42 @@ jest.mock('@typeorm/DataSource', () => ({ getDataSource: jest.fn(() => TestDB.instance.dbConnect), })) +const communityUUID = '3d813cbb-37fb-42ba-91df-831e1593ac29' + +const createUserStoreAccount = async (uuid: string): Promise => { + const senderUserAccountDraft = new UserAccountDraft() + senderUserAccountDraft.accountType = AccountType.COMMUNITY_HUMAN + senderUserAccountDraft.createdAt = new Date().toString() + senderUserAccountDraft.user = new UserIdentifier() + senderUserAccountDraft.user.uuid = uuid + senderUserAccountDraft.user.communityUuid = communityUUID + const senderUser = UserFactory.create(senderUserAccountDraft) + const senderUserLogic = new UserLogic(senderUser) + const senderAccount = AccountFactory.createAccountFromUserAccountDraft( + senderUserAccountDraft, + senderUserLogic.calculateKeyPair(), + ) + senderAccount.user = senderUser + // user is set to cascade true will be saved together with account + await senderAccount.save() + return senderUserAccountDraft.user +} + describe('Transaction Resolver Test', () => { + let senderUser: UserIdentifier + let recipientUser: UserIdentifier beforeAll(async () => { - apolloTestServer = await createApolloTestServer() await TestDB.instance.setupTestDB() + apolloTestServer = await createApolloTestServer() + + const communityDraft = new CommunityDraft() + communityDraft.uuid = communityUUID + communityDraft.foreign = false + communityDraft.createdAt = new Date().toString() + const addCommunityContext = new AddCommunityContext(communityDraft) + await addCommunityContext.run() + senderUser = await createUserStoreAccount('0ec72b74-48c2-446f-91ce-31ad7d9f4d65') + recipientUser = await createUserStoreAccount('ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe') }) afterAll(async () => { @@ -32,15 +78,11 @@ describe('Transaction Resolver Test', () => { it('test mocked sendTransaction', async () => { const response = await apolloTestServer.executeOperation({ query: - 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', + 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {succeed, recipe { id, topic }} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + senderUser, + recipientUser, type: 'SEND', amount: '10', createdAt: '2012-04-17T17:12:00Z', @@ -51,6 +93,7 @@ describe('Transaction Resolver Test', () => { assert(response.body.kind === 'single') expect(response.body.singleResult.errors).toBeUndefined() const transactionResult = response.body.singleResult.data?.sendTransaction as TransactionResult + expect(transactionResult.recipe).toBeDefined() expect(transactionResult.succeed).toBe(true) }) @@ -60,12 +103,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + senderUser, + recipientUser, type: 'INVALID', amount: '10', createdAt: '2012-04-17T17:12:00Z', @@ -78,7 +117,7 @@ describe('Transaction Resolver Test', () => { errors: [ { message: - 'Variable "$input" got invalid value "INVALID" at "input.type"; Value "INVALID" does not exist in "TransactionType" enum.', + 'Variable "$input" got invalid value "INVALID" at "input.type"; Value "INVALID" does not exist in "InputTransactionType" enum.', }, ], }) @@ -90,12 +129,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + senderUser, + recipientUser, type: 'SEND', amount: 'no number', createdAt: '2012-04-17T17:12:00Z', @@ -120,12 +155,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + senderUser, + recipientUser, type: 'SEND', amount: '10', createdAt: 'not valid', @@ -160,12 +191,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + senderUser, + recipientUser, type: 'CREATION', amount: '10', createdAt: '2012-04-17T17:12:00Z', diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts index e2b558668..eb1cb769b 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -18,7 +18,7 @@ export class TransactionResolver { try { await createTransactionRecipeContext.run() const transactionRecipe = createTransactionRecipeContext.getTransactionRecipe() - transactionRecipe.save() + await transactionRecipe.save() return new TransactionResult(new TransactionRecipe(transactionRecipe)) // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { diff --git a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts index ff46de4d3..5cf48a793 100644 --- a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -3,6 +3,7 @@ import { ForeignCommunityRole } from './ForeignCommunity.role' import { HomeCommunityRole } from './HomeCommunity.role' import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' import { CommunityRole } from './Community.role' +import { Community } from '@entity/Community' /** * @DCI-Context diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index a4438f780..57155d8ff 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -35,7 +35,6 @@ export class HomeCommunityRole extends CommunityRole { public async store(): Promise { try { - console.log('store transaction: %s', JSON.stringify(this.transactionRecipe, null, 2)) return await getDataSource().transaction(async (transactionalEntityManager) => { const community = await transactionalEntityManager.save(this.self) await transactionalEntityManager.save(this.transactionRecipe) @@ -43,7 +42,6 @@ export class HomeCommunityRole extends CommunityRole { }) } catch (error) { logger.error('error saving home community into db: %s', error) - console.log(error) throw new TransactionError( TransactionErrorType.DB_ERROR, 'error saving home community into db', diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 9fb53f3be..3005ccb7a 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -36,7 +36,6 @@ export class TransactionRecipeRole { "couldn't found recipient user account in db", ) } - // create proto transaction body const transactionBodyBuilder = new TransactionBodyBuilder() .setSigningAccount(signingAccount) diff --git a/dlt-connector/src/utils/typeConverter.ts b/dlt-connector/src/utils/typeConverter.ts index 15d4e8826..d21e7964b 100644 --- a/dlt-connector/src/utils/typeConverter.ts +++ b/dlt-connector/src/utils/typeConverter.ts @@ -6,6 +6,9 @@ import { TransactionBody } from '@/data/proto/3_3/TransactionBody' import { logger } from '@/server/logger' import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { AccountType } from '@/graphql/enum/AccountType' +import { AddressType } from '@/graphql/enum/AddressType' +import { LogError } from '@/server/LogError' export const uuid4ToBuffer = (uuid: string): Buffer => { // Remove dashes from the UUIDv4 string @@ -60,3 +63,45 @@ export const transactionBodyToBodyBytes = (transactionBody: TransactionBody): Bu ) } } + +export const accountTypeToAddressType = (accountType: AccountType): AddressType => { + switch (accountType) { + case AccountType.NONE: + return AddressType.NONE + case AccountType.COMMUNITY_HUMAN: + return AddressType.COMMUNITY_HUMAN + case AccountType.COMMUNITY_GMW: + return AddressType.COMMUNITY_GMW + case AccountType.COMMUNITY_AUF: + return AddressType.COMMUNITY_AUF + case AccountType.COMMUNITY_PROJECT: + return AddressType.COMMUNITY_PROJECT + case AccountType.SUBACCOUNT: + return AddressType.SUBACCOUNT + case AccountType.CRYPTO_ACCOUNT: + return AddressType.CRYPTO_ACCOUNT + default: + throw new LogError(`Unsupported AccountType: ${accountType}`) + } +} + +export const addressTypeToAccountType = (addressType: AddressType): AccountType => { + switch (addressType) { + case AddressType.NONE: + return AccountType.NONE + case AddressType.COMMUNITY_HUMAN: + return AccountType.COMMUNITY_HUMAN + case AddressType.COMMUNITY_GMW: + return AccountType.COMMUNITY_GMW + case AddressType.COMMUNITY_AUF: + return AccountType.COMMUNITY_AUF + case AddressType.COMMUNITY_PROJECT: + return AccountType.COMMUNITY_PROJECT + case AddressType.SUBACCOUNT: + return AccountType.SUBACCOUNT + case AddressType.CRYPTO_ACCOUNT: + return AccountType.CRYPTO_ACCOUNT + default: + throw new LogError(`Unsupported AddressType: ${addressType}`) + } +} From 81dc6245ffb3731808edcb4067d3d9cae4fb2a28 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Wed, 1 Nov 2023 10:44:49 +0100 Subject: [PATCH 07/47] fix lint and precise cascade --- .../resolver/TransactionsResolver.test.ts | 32 +++++++++---------- .../community/AddCommunity.context.ts | 1 - .../transaction/TransactionRecipe.role.ts | 1 - dlt-connector/src/typeorm/DataSource.ts | 1 - .../Account.ts | 2 +- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index cc5b27c76..b137717c5 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -7,13 +7,11 @@ import assert from 'assert' import { TransactionResult } from '@model/TransactionResult' import { AccountFactory } from '@/data/Account.factory' import { CONFIG } from '@/config' -import { KeyManager } from '@/manager/KeyManager' import { UserFactory } from '@/data/User.factory' import { UserAccountDraft } from '../input/UserAccountDraft' import { UserLogic } from '@/data/User.logic' import { AccountType } from '../enum/AccountType' import { UserIdentifier } from '../input/UserIdentifier' -import { KeyPair } from '@/data/KeyPair' import { CommunityDraft } from '../input/CommunityDraft' import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' @@ -36,22 +34,22 @@ jest.mock('@typeorm/DataSource', () => ({ const communityUUID = '3d813cbb-37fb-42ba-91df-831e1593ac29' const createUserStoreAccount = async (uuid: string): Promise => { - const senderUserAccountDraft = new UserAccountDraft() - senderUserAccountDraft.accountType = AccountType.COMMUNITY_HUMAN - senderUserAccountDraft.createdAt = new Date().toString() - senderUserAccountDraft.user = new UserIdentifier() - senderUserAccountDraft.user.uuid = uuid - senderUserAccountDraft.user.communityUuid = communityUUID - const senderUser = UserFactory.create(senderUserAccountDraft) - const senderUserLogic = new UserLogic(senderUser) - const senderAccount = AccountFactory.createAccountFromUserAccountDraft( - senderUserAccountDraft, - senderUserLogic.calculateKeyPair(), + const userAccountDraft = new UserAccountDraft() + userAccountDraft.accountType = AccountType.COMMUNITY_HUMAN + userAccountDraft.createdAt = new Date().toString() + userAccountDraft.user = new UserIdentifier() + userAccountDraft.user.uuid = uuid + userAccountDraft.user.communityUuid = communityUUID + const user = UserFactory.create(userAccountDraft) + const userLogic = new UserLogic(user) + const account = AccountFactory.createAccountFromUserAccountDraft( + userAccountDraft, + userLogic.calculateKeyPair(), ) - senderAccount.user = senderUser - // user is set to cascade true will be saved together with account - await senderAccount.save() - return senderUserAccountDraft.user + account.user = user + // user is set to cascade: ['insert'] will be saved together with account + await account.save() + return userAccountDraft.user } describe('Transaction Resolver Test', () => { diff --git a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts index 5cf48a793..ff46de4d3 100644 --- a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -3,7 +3,6 @@ import { ForeignCommunityRole } from './ForeignCommunity.role' import { HomeCommunityRole } from './HomeCommunity.role' import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' import { CommunityRole } from './Community.role' -import { Community } from '@entity/Community' /** * @DCI-Context diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 3005ccb7a..7eb9d5f69 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -1,4 +1,3 @@ -import { AccountRepository } from '@/data/Account.repository' import { KeyPair } from '@/data/KeyPair' import { TransactionBuilder } from '@/data/Transaction.builder' import { UserRepository } from '@/data/User.repository' diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index 1dab441c2..62cdbf755 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -53,7 +53,6 @@ export class Connection { } public getDataSource(): DBDataSource { - console.log('production getDataSource called!') return this.connection } diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts index 067a140eb..1f94a9d55 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -18,7 +18,7 @@ export class Account extends BaseEntity { @PrimaryGeneratedColumn('increment', { unsigned: true }) id: number - @ManyToOne(() => User, (user) => user.accounts, { cascade: true, eager: true }) // Assuming you have a User entity with 'accounts' relation + @ManyToOne(() => User, (user) => user.accounts, { cascade: ['insert'], eager: true }) // Assuming you have a User entity with 'accounts' relation @JoinColumn({ name: 'user_id' }) user?: User From a82aa2403ce1176abc6357d148a8d7dd33444d4e Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 7 Nov 2023 16:51:02 +0100 Subject: [PATCH 08/47] change order because constraints --- dlt-database/migrations/0003-refactor_transaction_recipe.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index 5a6ba9a78..e860e4926 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -3,9 +3,9 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promise>) { // write upgrade logic as parameter of queryFn - await queryFn(`DROP TABLE \`transaction_recipes\`;`) await queryFn(`DROP TABLE \`confirmed_transactions\`;`) - + await queryFn(`DROP TABLE \`transaction_recipes\`;`) + await queryFn( `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NULL DEFAULT NULL;`, ) From aa149e09f6c20443acd94eb509413cb320a9350f Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 20:21:03 +0100 Subject: [PATCH 09/47] use constant for proto version number --- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 3 ++- dlt-connector/src/data/proto/3_3/const.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 dlt-connector/src/data/proto/3_3/const.ts diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 8bfbf955f..0783873cd 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -17,6 +17,7 @@ import { TransactionBase } from '../TransactionBase' import { Transaction } from '@entity/Transaction' import { timestampToDate } from '@/utils/typeConverter' import { LogError } from '@/server/LogError' +import { PROTO_TRANSACTION_BODY_VERSION_NUMBER } from './const' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -33,7 +34,7 @@ export class TransactionBody extends Message { super({ memo: 'Not implemented yet', createdAt: new Timestamp(new Date(transaction.createdAt)), - versionNumber: '3.3', + versionNumber: PROTO_TRANSACTION_BODY_VERSION_NUMBER, type, otherGroup, }) diff --git a/dlt-connector/src/data/proto/3_3/const.ts b/dlt-connector/src/data/proto/3_3/const.ts new file mode 100644 index 000000000..96924e856 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/const.ts @@ -0,0 +1 @@ +export const PROTO_TRANSACTION_BODY_VERSION_NUMBER = '3.3' \ No newline at end of file From 45ee5561addf18eec904fe297d42b33a482c1abc Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 20:28:10 +0100 Subject: [PATCH 10/47] change naming --- dlt-connector/src/data/proto/3_3/CommunityRoot.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoCreation.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoTransfer.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts | 4 ++-- dlt-connector/src/data/proto/3_3/RegisterAddress.ts | 4 ++-- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 4 ++-- dlt-connector/src/data/proto/TransactionBase.ts | 2 +- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts index 401179d85..ec69be4f6 100644 --- a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -1,4 +1,4 @@ -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Community } from '@entity/Community' @@ -6,7 +6,7 @@ import { Transaction } from '@entity/Transaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class CommunityRoot extends Message implements TransactionBase { +export class CommunityRoot extends Message implements AbstractTransaction { public constructor(community?: Community) { if (community) { super({ diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts index 354d40671..4a3ff91f9 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -5,7 +5,7 @@ import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -15,7 +15,7 @@ import { Account } from '@entity/Account' // 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 implements TransactionBase { +export class GradidoCreation extends Message implements AbstractTransaction { constructor(transaction?: TransactionDraft, recipientAccount?: Account) { if (transaction) { if (!transaction.targetDate) { diff --git a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index 4693df879..ceedf579d 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { GradidoTransfer } from './GradidoTransfer' import { TimestampSeconds } from './TimestampSeconds' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -17,7 +17,7 @@ import Decimal from 'decimal.js-light' export class GradidoDeferredTransfer // eslint-disable-next-line no-use-before-define extends Message - implements TransactionBase + implements AbstractTransaction { // amount is amount with decay for time span between transaction was received and timeout // useable amount can be calculated diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts index dadddedec..d68b8ccf7 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -10,7 +10,7 @@ import { Account } from '@entity/Account' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class GradidoTransfer extends Message implements TransactionBase { +export class GradidoTransfer extends Message implements AbstractTransaction { constructor( transaction?: TransactionDraft, signingAccount?: Account, diff --git a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 3d6811331..91d3693b0 100644 --- a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts +++ b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Transaction } from '@entity/Transaction' @@ -8,7 +8,7 @@ import { Transaction } from '@entity/Transaction' // 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 implements TransactionBase { +export class GroupFriendsUpdate extends Message implements AbstractTransaction { // 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, diff --git a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts index f9eead762..639b01a54 100644 --- a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -3,13 +3,13 @@ import { Field, Message } from 'protobufjs' import { AddressType } from '@/data/proto/3_3/enum/AddressType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class RegisterAddress extends Message implements TransactionBase { +export class RegisterAddress extends Message implements AbstractTransaction { @Field.d(1, 'bytes') public userPubkey: Buffer diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 0783873cd..4ea5bc23c 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -13,7 +13,7 @@ import { determineCrossGroupType, determineOtherGroup } from '../transactionBody import { CommunityRoot } from './CommunityRoot' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { TransactionType } from '@/graphql/enum/TransactionType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { Transaction } from '@entity/Transaction' import { timestampToDate } from '@/utils/typeConverter' import { LogError } from '@/server/LogError' @@ -95,7 +95,7 @@ export class TransactionBody extends Message { else if (this.communityRoot) return TransactionType.COMMUNITY_ROOT } - public getTransactionBase(): TransactionBase | undefined { + public getTransactionBase(): AbstractTransaction | undefined { if (this.transfer) return this.transfer if (this.creation) return this.creation if (this.groupFriendsUpdate) return this.groupFriendsUpdate diff --git a/dlt-connector/src/data/proto/TransactionBase.ts b/dlt-connector/src/data/proto/TransactionBase.ts index e04b3435e..82c50dcb0 100644 --- a/dlt-connector/src/data/proto/TransactionBase.ts +++ b/dlt-connector/src/data/proto/TransactionBase.ts @@ -1,7 +1,7 @@ import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' -export abstract class TransactionBase { +export abstract class AbstractTransaction { // validate if transaction is valid, maybe expensive because depending on level several transactions will be fetched from db public abstract validate(level: TransactionValidationLevel): boolean From 55bed604d67a31a640cd4788ae9c585f661e7419 Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 20:28:10 +0100 Subject: [PATCH 11/47] change naming --- dlt-connector/src/data/proto/3_3/CommunityRoot.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoCreation.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GradidoTransfer.ts | 4 ++-- dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts | 4 ++-- dlt-connector/src/data/proto/3_3/RegisterAddress.ts | 4 ++-- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 6 +++--- dlt-connector/src/data/proto/TransactionBase.ts | 2 +- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts index 401179d85..ec69be4f6 100644 --- a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -1,4 +1,4 @@ -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Community } from '@entity/Community' @@ -6,7 +6,7 @@ import { Transaction } from '@entity/Transaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class CommunityRoot extends Message implements TransactionBase { +export class CommunityRoot extends Message implements AbstractTransaction { public constructor(community?: Community) { if (community) { super({ diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts index 354d40671..4a3ff91f9 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -5,7 +5,7 @@ import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -15,7 +15,7 @@ import { Account } from '@entity/Account' // 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 implements TransactionBase { +export class GradidoCreation extends Message implements AbstractTransaction { constructor(transaction?: TransactionDraft, recipientAccount?: Account) { if (transaction) { if (!transaction.targetDate) { diff --git a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index 4693df879..ceedf579d 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { GradidoTransfer } from './GradidoTransfer' import { TimestampSeconds } from './TimestampSeconds' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -17,7 +17,7 @@ import Decimal from 'decimal.js-light' export class GradidoDeferredTransfer // eslint-disable-next-line no-use-before-define extends Message - implements TransactionBase + implements AbstractTransaction { // amount is amount with decay for time span between transaction was received and timeout // useable amount can be calculated diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts index dadddedec..d68b8ccf7 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' @@ -10,7 +10,7 @@ import { Account } from '@entity/Account' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class GradidoTransfer extends Message implements TransactionBase { +export class GradidoTransfer extends Message implements AbstractTransaction { constructor( transaction?: TransactionDraft, signingAccount?: Account, diff --git a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 3d6811331..91d3693b0 100644 --- a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts +++ b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Transaction } from '@entity/Transaction' @@ -8,7 +8,7 @@ import { Transaction } from '@entity/Transaction' // 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 implements TransactionBase { +export class GroupFriendsUpdate extends Message implements AbstractTransaction { // 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, diff --git a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts index f9eead762..639b01a54 100644 --- a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -3,13 +3,13 @@ import { Field, Message } from 'protobufjs' import { AddressType } from '@/data/proto/3_3/enum/AddressType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define -export class RegisterAddress extends Message implements TransactionBase { +export class RegisterAddress extends Message implements AbstractTransaction { @Field.d(1, 'bytes') public userPubkey: Buffer diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 0783873cd..9e7eaeddd 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -13,7 +13,7 @@ import { determineCrossGroupType, determineOtherGroup } from '../transactionBody import { CommunityRoot } from './CommunityRoot' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { TransactionType } from '@/graphql/enum/TransactionType' -import { TransactionBase } from '../TransactionBase' +import { AbstractTransaction } from '../TransactionBase' import { Transaction } from '@entity/Transaction' import { timestampToDate } from '@/utils/typeConverter' import { LogError } from '@/server/LogError' @@ -95,7 +95,7 @@ export class TransactionBody extends Message { else if (this.communityRoot) return TransactionType.COMMUNITY_ROOT } - public getTransactionBase(): TransactionBase | undefined { + public getTransactionDetails(): AbstractTransaction | undefined { if (this.transfer) return this.transfer if (this.creation) return this.creation if (this.groupFriendsUpdate) return this.groupFriendsUpdate @@ -112,7 +112,7 @@ export class TransactionBody extends Message { throw new LogError("invalid TransactionBody couldn't determine transaction type") } recipe.type = transactionType.valueOf() - this.getTransactionBase()?.fillTransactionRecipe(recipe) + this.getTransactionDetails()?.fillTransactionRecipe(recipe) } public getRecipientPublicKey(): Buffer | undefined { diff --git a/dlt-connector/src/data/proto/TransactionBase.ts b/dlt-connector/src/data/proto/TransactionBase.ts index e04b3435e..82c50dcb0 100644 --- a/dlt-connector/src/data/proto/TransactionBase.ts +++ b/dlt-connector/src/data/proto/TransactionBase.ts @@ -1,7 +1,7 @@ import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' -export abstract class TransactionBase { +export abstract class AbstractTransaction { // validate if transaction is valid, maybe expensive because depending on level several transactions will be fetched from db public abstract validate(level: TransactionValidationLevel): boolean From 3b608d49a61ac917046f71b7daf3a05c7105dd3e Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 21:35:14 +0100 Subject: [PATCH 12/47] fix bug claus peter has detected --- .../backendToDb/transaction/TransactionRecipe.role.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 7eb9d5f69..caebb4fc4 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -46,7 +46,7 @@ export class TransactionRecipeRole { .fromTransactionBodyBuilder(transactionBodyBuilder) .setBackendTransactionId(transactionDraft.backendTransactionId) await this.transactionBuilder.setSenderCommunityFromSenderUser(senderUser) - if (recipientUser.uuid !== senderUser.uuid) { + if (recipientUser.communityUuid !== senderUser.communityUuid) { await this.transactionBuilder.setRecipientCommunityFromRecipientUser(recipientUser) } const transaction = this.transactionBuilder.getTransaction() From 3b1d49004040b6101cd2323c9962cffd4976cc7b Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 21:39:36 +0100 Subject: [PATCH 13/47] use enum instead hardcoded --- .../src/graphql/resolver/TransactionsResolver.test.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index b137717c5..88fb4ffb7 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -14,6 +14,7 @@ import { AccountType } from '../enum/AccountType' import { UserIdentifier } from '../input/UserIdentifier' import { CommunityDraft } from '../input/CommunityDraft' import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' +import { InputTransactionType } from '../enum/InputTransactionType' CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' @@ -81,7 +82,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: 'SEND', + type: InputTransactionType.SEND, amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -129,7 +130,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: 'SEND', + type: InputTransactionType.SEND, amount: 'no number', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -155,7 +156,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: 'SEND', + type: InputTransactionType.SEND, amount: '10', createdAt: 'not valid', backendTransactionId: 1, @@ -191,7 +192,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: 'CREATION', + type: InputTransactionType.CREATION, amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, From c3d72cb8df380a83ef69315c9dba8bd427fb00c8 Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 21:50:30 +0100 Subject: [PATCH 14/47] add missing init call for key manager --- dlt-connector/src/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dlt-connector/src/index.ts b/dlt-connector/src/index.ts index 5284d9b1e..7e1ea1adc 100644 --- a/dlt-connector/src/index.ts +++ b/dlt-connector/src/index.ts @@ -1,12 +1,14 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { CONFIG } from '@/config' import createServer from './server/createServer' +import { KeyManager } from './manager/KeyManager' async function main() { // eslint-disable-next-line no-console console.log(`DLT_CONNECTOR_PORT=${CONFIG.DLT_CONNECTOR_PORT}`) const { app } = await createServer() + await KeyManager.getInstance().init() app.listen(CONFIG.DLT_CONNECTOR_PORT, () => { // eslint-disable-next-line no-console console.log(`Server is running at http://localhost:${CONFIG.DLT_CONNECTOR_PORT}`) From 7a9f52e440ba6d954b5a2a564a123f56d2eeccb0 Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Wed, 6 Dec 2023 22:42:47 +0100 Subject: [PATCH 15/47] update entity and migration --- .../Account.ts | 9 ++++---- .../Transaction.ts | 4 +++- .../0003-refactor_transaction_recipe.ts | 22 ++++++++++++++----- 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts index 1f94a9d55..c0c8aef98 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -18,7 +18,7 @@ export class Account extends BaseEntity { @PrimaryGeneratedColumn('increment', { unsigned: true }) id: number - @ManyToOne(() => User, (user) => user.accounts, { cascade: ['insert'], eager: true }) // Assuming you have a User entity with 'accounts' relation + @ManyToOne(() => User, (user) => user.accounts, { cascade: ['insert', 'update'], eager: true }) // Assuming you have a User entity with 'accounts' relation @JoinColumn({ name: 'user_id' }) user?: User @@ -47,20 +47,21 @@ export class Account extends BaseEntity { confirmedAt?: Date @Column({ + name: 'balance_confirmed_at', type: 'decimal', precision: 40, scale: 20, default: 0, transformer: DecimalTransformer, }) - balance: Decimal + balanceConfirmedAt: Decimal @Column({ - name: 'balance_date', + name: 'balance_confirmed_at_date', type: 'datetime', default: () => 'CURRENT_TIMESTAMP()', }) - balanceDate: Date + balanceConfirmedAtDate: Date @Column({ name: 'balance_created_at', diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index f1167043f..66c5cf189 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -71,6 +71,7 @@ export class Transaction extends BaseEntity { }) amount?: Decimal + // account balance for sender based on creation date @Column({ name: 'account_balance_created_at', type: 'decimal', @@ -102,8 +103,9 @@ export class Transaction extends BaseEntity { @Column({ name: 'running_hash', type: 'binary', length: 48, nullable: true }) runningHash?: Buffer + // account balance for sender based on confirmation date (iota milestone) @Column({ - name: 'account_balance', + name: 'account_balance_confirmed_at', type: 'decimal', precision: 40, scale: 20, diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index e860e4926..5d6f6af41 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -5,15 +5,21 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis // write upgrade logic as parameter of queryFn await queryFn(`DROP TABLE \`confirmed_transactions\`;`) await queryFn(`DROP TABLE \`transaction_recipes\`;`) - + + await queryFn(` + ALTER TABLE \`accounts\` + RENAME COLUMN \`balance\` TO \`balance_confirmed_at\`, + RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at_date\`, + `) + await queryFn( `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NULL DEFAULT NULL;`, ) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`account_balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_date\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_date\`;`, ) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) AFTER \`account_balance_created_at\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) AFTER \`balance_created_at\`;`, ) await queryFn( @@ -35,7 +41,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`protocol_version\` varchar(255) NOT NULL DEFAULT '1', \`nr\` bigint NULL DEFAULT NULL, \`running_hash\` varbinary(48) NULL DEFAULT NULL, - \`account_balance\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, + \`account_balance_confirmed_at\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, \`iota_milestone\` bigint NULL DEFAULT NULL, \`confirmed_at\` datetime NULL DEFAULT NULL, PRIMARY KEY (\`id\`), @@ -88,10 +94,16 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom FOREIGN KEY (\`account_id\`) REFERENCES accounts(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) + await queryFn(` + ALTER TABLE \`accounts\` + RENAME COLUMN \`balance_confirmed_at\` TO \`balance\`, + RENAME COLUMN \`balance_confirmed_at_date\` TO \`balance_date\`, + `) + await queryFn( `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NOT NULL;`, ) - await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`account_balance_created_at\`;`) + await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at\`;`) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) await queryFn(`DROP TABLE \`transactions\`;`) } From bf71f91bc386d0b7abcfcbe28f0a5b8d78b12f55 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Thu, 7 Dec 2023 13:44:18 +0100 Subject: [PATCH 16/47] fix linting and build error --- dlt-connector/src/data/Account.factory.ts | 2 +- dlt-connector/src/data/proto/3_3/const.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index 808551b87..32ffe9ff1 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -25,7 +25,7 @@ export class AccountFactory { ).publicKey account.type = type.valueOf() account.createdAt = createdAt - account.balance = new Decimal(0) + account.balanceConfirmedAt = new Decimal(0) account.balanceCreatedAt = new Decimal(0) return account } diff --git a/dlt-connector/src/data/proto/3_3/const.ts b/dlt-connector/src/data/proto/3_3/const.ts index 96924e856..9733e14a2 100644 --- a/dlt-connector/src/data/proto/3_3/const.ts +++ b/dlt-connector/src/data/proto/3_3/const.ts @@ -1 +1 @@ -export const PROTO_TRANSACTION_BODY_VERSION_NUMBER = '3.3' \ No newline at end of file +export const PROTO_TRANSACTION_BODY_VERSION_NUMBER = '3.3' From c113d95a3cfe8fead64fcc0b070e2c5ee3eba19f Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Thu, 7 Dec 2023 13:56:43 +0100 Subject: [PATCH 17/47] fix test, remove not longer used files --- dlt-connector/src/graphql/enum/AddressType.ts | 9 ------- .../src/graphql/enum/CrossGroupType.ts | 7 ----- .../src/graphql/enum/InputTransactionType.ts | 12 +++++++++ .../src/graphql/input/TransactionInput.ts | 27 ------------------- .../resolver/TransactionsResolver.test.ts | 12 ++++----- dlt-connector/src/utils/typeConverter.ts | 2 +- 6 files changed, 19 insertions(+), 50 deletions(-) delete mode 100644 dlt-connector/src/graphql/enum/AddressType.ts delete mode 100644 dlt-connector/src/graphql/enum/CrossGroupType.ts delete mode 100755 dlt-connector/src/graphql/input/TransactionInput.ts diff --git a/dlt-connector/src/graphql/enum/AddressType.ts b/dlt-connector/src/graphql/enum/AddressType.ts deleted file mode 100644 index 26efd2825..000000000 --- a/dlt-connector/src/graphql/enum/AddressType.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 -} diff --git a/dlt-connector/src/graphql/enum/CrossGroupType.ts b/dlt-connector/src/graphql/enum/CrossGroupType.ts deleted file mode 100644 index 13e968509..000000000 --- a/dlt-connector/src/graphql/enum/CrossGroupType.ts +++ /dev/null @@ -1,7 +0,0 @@ -export enum CrossGroupType { - LOCAL = 0, - INBOUND = 1, - OUTBOUND = 2, - // for cross group transaction which haven't a direction like group friend update - // CROSS = 3, -} diff --git a/dlt-connector/src/graphql/enum/InputTransactionType.ts b/dlt-connector/src/graphql/enum/InputTransactionType.ts index 06d1bb44b..f35a26658 100755 --- a/dlt-connector/src/graphql/enum/InputTransactionType.ts +++ b/dlt-connector/src/graphql/enum/InputTransactionType.ts @@ -1,3 +1,4 @@ +import { LogError } from '@/server/LogError' import { registerEnumType } from 'type-graphql' export enum InputTransactionType { @@ -10,3 +11,14 @@ registerEnumType(InputTransactionType, { name: 'InputTransactionType', // this one is mandatory description: 'Type of the transaction', // this one is optional }) + +// from ChatGPT +export function getTransactionTypeString(id: InputTransactionType): string { + const key = Object.keys(InputTransactionType).find( + (key) => InputTransactionType[key as keyof typeof InputTransactionType] === id, + ) + if (key === undefined) { + throw new LogError('invalid transaction type id: ' + id.toString()) + } + return key +} diff --git a/dlt-connector/src/graphql/input/TransactionInput.ts b/dlt-connector/src/graphql/input/TransactionInput.ts deleted file mode 100755 index d20b6ff27..000000000 --- a/dlt-connector/src/graphql/input/TransactionInput.ts +++ /dev/null @@ -1,27 +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' -import { IsEnum, IsInt, Min } from 'class-validator' -import { IsPositiveDecimal } from '../validator/Decimal' - -@InputType() -export class TransactionInput { - @Field(() => TransactionType) - @IsEnum(TransactionType) - type: TransactionType - - @Field(() => Decimal) - @IsPositiveDecimal() - amount: Decimal - - @Field(() => Number) - @IsInt() - @Min(978346800) - createdAt: number - - // @protoField.d(4, 'string') - // @Field(() => Decimal) - // communitySum: Decimal -} diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index 88fb4ffb7..71044805c 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -10,11 +10,11 @@ import { CONFIG } from '@/config' import { UserFactory } from '@/data/User.factory' import { UserAccountDraft } from '../input/UserAccountDraft' import { UserLogic } from '@/data/User.logic' -import { AccountType } from '../enum/AccountType' +import { AccountType } from '@enum/AccountType' import { UserIdentifier } from '../input/UserIdentifier' import { CommunityDraft } from '../input/CommunityDraft' import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' -import { InputTransactionType } from '../enum/InputTransactionType' +import { InputTransactionType, getTransactionTypeString } from '../enum/InputTransactionType' CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' @@ -82,7 +82,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: InputTransactionType.SEND, + type: getTransactionTypeString(InputTransactionType.SEND), amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -130,7 +130,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: InputTransactionType.SEND, + type: getTransactionTypeString(InputTransactionType.SEND), amount: 'no number', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -156,7 +156,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: InputTransactionType.SEND, + type: getTransactionTypeString(InputTransactionType.SEND), amount: '10', createdAt: 'not valid', backendTransactionId: 1, @@ -192,7 +192,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: InputTransactionType.CREATION, + type: getTransactionTypeString(InputTransactionType.CREATION), amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, diff --git a/dlt-connector/src/utils/typeConverter.ts b/dlt-connector/src/utils/typeConverter.ts index d21e7964b..ecf090c45 100644 --- a/dlt-connector/src/utils/typeConverter.ts +++ b/dlt-connector/src/utils/typeConverter.ts @@ -7,8 +7,8 @@ import { logger } from '@/server/logger' import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { AccountType } from '@/graphql/enum/AccountType' -import { AddressType } from '@/graphql/enum/AddressType' import { LogError } from '@/server/LogError' +import { AddressType } from '@/data/proto/3_3/enum/AddressType' export const uuid4ToBuffer = (uuid: string): Buffer => { // Remove dashes from the UUIDv4 string From 35670ded960b65eccfec78067576bbe423069276 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Thu, 7 Dec 2023 14:46:35 +0100 Subject: [PATCH 18/47] refactor db --- dlt-database/entity/0001-init_db/Account.ts | 2 +- .../0001-init_db/ConfirmedTransaction.ts | 2 +- .../entity/0001-init_db/TransactionRecipe.ts | 2 +- .../0002-refactor_add_community/Account.ts | 4 +-- .../0002-refactor_add_community/Community.ts | 2 +- .../ConfirmedTransaction.ts | 2 +- .../Account.ts | 12 +++---- .../Community.ts | 8 ++--- .../Transaction.ts | 1 + .../0003-refactor_transaction_recipe/User.ts | 35 +++++++++++++++++++ dlt-database/entity/ConfirmedTransaction.ts | 1 - dlt-database/entity/TransactionRecipe.ts | 1 - dlt-database/entity/User.ts | 2 +- dlt-database/migrations/0001-init_db.ts | 6 ++-- .../0003-refactor_transaction_recipe.ts | 34 +++++++++++++++--- 15 files changed, 83 insertions(+), 31 deletions(-) create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/User.ts delete mode 100644 dlt-database/entity/ConfirmedTransaction.ts delete mode 100644 dlt-database/entity/TransactionRecipe.ts diff --git a/dlt-database/entity/0001-init_db/Account.ts b/dlt-database/entity/0001-init_db/Account.ts index d6d4a3095..4a7801c0e 100644 --- a/dlt-database/entity/0001-init_db/Account.ts +++ b/dlt-database/entity/0001-init_db/Account.ts @@ -9,7 +9,7 @@ import { } from 'typeorm' import { User } from '../User' import { TransactionRecipe } from './TransactionRecipe' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +import { ConfirmedTransaction } from './ConfirmedTransaction' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Decimal } from 'decimal.js-light' import { AccountCommunity } from '../AccountCommunity' diff --git a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts index a5d22dc80..b195e17c2 100644 --- a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts +++ b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts @@ -11,7 +11,7 @@ import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Account } from './Account' -import { TransactionRecipe } from '../TransactionRecipe' +import { TransactionRecipe } from './TransactionRecipe' @Entity('confirmed_transactions') export class ConfirmedTransaction extends BaseEntity { diff --git a/dlt-database/entity/0001-init_db/TransactionRecipe.ts b/dlt-database/entity/0001-init_db/TransactionRecipe.ts index db311e64f..1222cfbdd 100644 --- a/dlt-database/entity/0001-init_db/TransactionRecipe.ts +++ b/dlt-database/entity/0001-init_db/TransactionRecipe.ts @@ -12,7 +12,7 @@ import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Account } from './Account' import { Community } from './Community' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +import { ConfirmedTransaction } from './ConfirmedTransaction' @Entity('transaction_recipes') export class TransactionRecipe extends BaseEntity { diff --git a/dlt-database/entity/0002-refactor_add_community/Account.ts b/dlt-database/entity/0002-refactor_add_community/Account.ts index 9edba933d..644b1b9a8 100644 --- a/dlt-database/entity/0002-refactor_add_community/Account.ts +++ b/dlt-database/entity/0002-refactor_add_community/Account.ts @@ -8,8 +8,8 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' -import { TransactionRecipe } from '../TransactionRecipe' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' +import { ConfirmedTransaction } from './ConfirmedTransaction' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Decimal } from 'decimal.js-light' import { AccountCommunity } from '../AccountCommunity' diff --git a/dlt-database/entity/0002-refactor_add_community/Community.ts b/dlt-database/entity/0002-refactor_add_community/Community.ts index 25f9e3265..2961d5af3 100644 --- a/dlt-database/entity/0002-refactor_add_community/Community.ts +++ b/dlt-database/entity/0002-refactor_add_community/Community.ts @@ -8,7 +8,7 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' import { AccountCommunity } from '../AccountCommunity' @Entity('communities') diff --git a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts index 1b8df403b..33ab13b52 100644 --- a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts +++ b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts @@ -11,7 +11,7 @@ import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Account } from './Account' -import { TransactionRecipe } from '../TransactionRecipe' +import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' @Entity('confirmed_transactions') export class ConfirmedTransaction extends BaseEntity { diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts index c0c8aef98..a6e8a8b7e 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -35,14 +35,10 @@ export class Account extends BaseEntity { @Column({ type: 'tinyint', unsigned: true }) type: number - @Column({ - name: 'created_at', - type: 'datetime', - precision: 3, - default: () => 'CURRENT_TIMESTAMP(3)', - }) + @Column({ name: 'created_at', type: 'datetime', precision: 3 }) createdAt: Date + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) confirmedAt?: Date @@ -56,10 +52,11 @@ export class Account extends BaseEntity { }) balanceConfirmedAt: Decimal + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ name: 'balance_confirmed_at_date', type: 'datetime', - default: () => 'CURRENT_TIMESTAMP()', + nullable: true, }) balanceConfirmedAtDate: Date @@ -77,7 +74,6 @@ export class Account extends BaseEntity { name: 'balance_created_at_date', type: 'datetime', precision: 3, - default: () => 'CURRENT_TIMESTAMP(3)', }) balanceCreatedAtDate: Date diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts index ade3afc90..f403064b4 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts @@ -45,14 +45,10 @@ export class Community extends BaseEntity { @JoinColumn({ name: 'auf_account_id' }) aufAccount?: Account - @Column({ - name: 'created_at', - type: 'datetime', - precision: 3, - default: () => 'CURRENT_TIMESTAMP(3)', - }) + @Column({ name: 'created_at', type: 'datetime', precision: 3 }) createdAt: Date + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) confirmedAt?: Date diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index 66c5cf189..e9d8c6a0e 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -117,6 +117,7 @@ export class Transaction extends BaseEntity { @Column({ name: 'iota_milestone', type: 'bigint', nullable: true }) iotaMilestone?: number + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) confirmedAt?: Date } diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/User.ts b/dlt-database/entity/0003-refactor_transaction_recipe/User.ts new file mode 100644 index 000000000..fdfeb9830 --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/User.ts @@ -0,0 +1,35 @@ +import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, OneToMany, JoinColumn } from 'typeorm' + +import { Account } from '../Account' + +@Entity('users', { engine: 'InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci' }) +export class User extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true }) + id: number + + @Column({ + name: 'gradido_id', + length: 36, + nullable: true, + collation: 'utf8mb4_unicode_ci', + }) + gradidoID?: string + + @Column({ name: 'derive1_pubkey', type: 'binary', length: 32, unique: true }) + derive1Pubkey: Buffer + + @Column({ name: 'created_at', type: 'datetime', precision: 3 }) + createdAt: Date + + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here + @Column({ + name: 'confirmed_at', + type: 'datetime', + nullable: true, + }) + confirmedAt?: Date + + @OneToMany(() => Account, (account) => account.user) + @JoinColumn({ name: 'user_id' }) + accounts?: Account[] +} diff --git a/dlt-database/entity/ConfirmedTransaction.ts b/dlt-database/entity/ConfirmedTransaction.ts deleted file mode 100644 index 765e0b2e6..000000000 --- a/dlt-database/entity/ConfirmedTransaction.ts +++ /dev/null @@ -1 +0,0 @@ -export { ConfirmedTransaction } from './0002-refactor_add_community/ConfirmedTransaction' diff --git a/dlt-database/entity/TransactionRecipe.ts b/dlt-database/entity/TransactionRecipe.ts deleted file mode 100644 index e59a09ef9..000000000 --- a/dlt-database/entity/TransactionRecipe.ts +++ /dev/null @@ -1 +0,0 @@ -export { TransactionRecipe } from './0001-init_db/TransactionRecipe' diff --git a/dlt-database/entity/User.ts b/dlt-database/entity/User.ts index 3c803d783..4f1b039ff 100644 --- a/dlt-database/entity/User.ts +++ b/dlt-database/entity/User.ts @@ -1 +1 @@ -export { User } from './0002-refactor_add_community/User' +export { User } from './0003-refactor_transaction_recipe/User' diff --git a/dlt-database/migrations/0001-init_db.ts b/dlt-database/migrations/0001-init_db.ts index 85fed59e0..8188a889d 100644 --- a/dlt-database/migrations/0001-init_db.ts +++ b/dlt-database/migrations/0001-init_db.ts @@ -23,7 +23,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`confirmed_at\` datetime(3) DEFAULT NULL, PRIMARY KEY (\`id\`), INDEX \`gradido_id\` (\`gradido_id\`), - UNIQUE KEY \`pubkey\` (\`pubkey\`) + UNIQUE KEY \`derive1_pubkey\` (\`derive1_pubkey\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) await queryFn(` @@ -38,7 +38,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`balance\` decimal(40,20) NOT NULL DEFAULT 0, \`balance_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), PRIMARY KEY (\`id\`), - UNIQUE KEY \`pubkey\` (\`pubkey\`), + UNIQUE KEY \`derive2_pubkey\` (\`derive2_pubkey\`), FOREIGN KEY (\`user_id\`) REFERENCES users(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `) @@ -56,7 +56,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`created_at\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), \`confirmed_at\` datetime(3) DEFAULT NULL, PRIMARY KEY (\`id\`), - UNIQUE KEY \`pubkey\` (\`pubkey\`), + UNIQUE KEY \`root_pubkey\` (\`root_pubkey\`), FOREIGN KEY (\`gmw_account_id\`) REFERENCES accounts(id), FOREIGN KEY (\`auf_account_id\`) REFERENCES accounts(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index 5d6f6af41..cf5657485 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -9,17 +9,21 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis await queryFn(` ALTER TABLE \`accounts\` RENAME COLUMN \`balance\` TO \`balance_confirmed_at\`, - RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at_date\`, + RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at_date\` + ; `) await queryFn( `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NULL DEFAULT NULL;`, ) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_date\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_confirmed_at_date\`;`, ) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) AFTER \`balance_created_at\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL AFTER \`balance_created_at\`;`, + ) + await queryFn( + `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at_date\` datetime NULL DEFAULT NULL;`, ) await queryFn( @@ -55,6 +59,14 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis ) await queryFn(`ALTER TABLE \`communities\` ADD UNIQUE(\`iota_topic\`);`) + + await queryFn(`ALTER TABLE \`users\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL;`) + await queryFn( + `ALTER TABLE \`communities\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL;`, + ) + await queryFn( + `ALTER TABLE \`accounts\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL;`, + ) } export async function downgrade(queryFn: (query: string, values?: any[]) => Promise>) { @@ -94,10 +106,14 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom FOREIGN KEY (\`account_id\`) REFERENCES accounts(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`) + await queryFn( + `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, + ) await queryFn(` ALTER TABLE \`accounts\` RENAME COLUMN \`balance_confirmed_at\` TO \`balance\`, - RENAME COLUMN \`balance_confirmed_at_date\` TO \`balance_date\`, + RENAME COLUMN \`balance_confirmed_at_date\` TO \`balance_date\` + ; `) await queryFn( @@ -106,4 +122,14 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at\`;`) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) await queryFn(`DROP TABLE \`transactions\`;`) + + await queryFn( + `ALTER TABLE \`users\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, + ) + await queryFn( + `ALTER TABLE \`communities\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, + ) + await queryFn( + `ALTER TABLE \`accounts\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, + ) } From 0e10dc5353480f0bd1b32a7add6376f342da4140 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Thu, 7 Dec 2023 21:25:40 +0100 Subject: [PATCH 19/47] add Account.test, increase coverage by 1% --- dlt-connector/jest.config.js | 2 +- dlt-connector/src/data/Account.factory.ts | 1 + dlt-connector/src/data/Account.test.ts | 180 ++++++++++++++++++++++ dlt-connector/src/utils/cryptoHelper.ts | 19 ++- dlt-connector/test/TestDB.ts | 1 + 5 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 dlt-connector/src/data/Account.test.ts diff --git a/dlt-connector/jest.config.js b/dlt-connector/jest.config.js index 1faef9414..2de18cf50 100644 --- a/dlt-connector/jest.config.js +++ b/dlt-connector/jest.config.js @@ -6,7 +6,7 @@ module.exports = { collectCoverageFrom: ['src/**/*.ts', '!**/node_modules/**', '!src/seeds/**', '!build/**'], coverageThreshold: { global: { - lines: 70, + lines: 71, }, }, setupFiles: ['/test/testSetup.ts'], diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index 32ffe9ff1..493e394bb 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -27,6 +27,7 @@ export class AccountFactory { account.createdAt = createdAt account.balanceConfirmedAt = new Decimal(0) account.balanceCreatedAt = new Decimal(0) + account.balanceCreatedAtDate = createdAt return account } diff --git a/dlt-connector/src/data/Account.test.ts b/dlt-connector/src/data/Account.test.ts new file mode 100644 index 000000000..5a1e00277 --- /dev/null +++ b/dlt-connector/src/data/Account.test.ts @@ -0,0 +1,180 @@ +import 'reflect-metadata' +import { TestDB } from '@test/TestDB' +import { AccountFactory } from './Account.factory' +import { AddressType } from './proto/3_3/enum/AddressType' +import { generateKeyPair, generateMnemonic } from '@/utils/cryptoHelper' +import { Decimal } from 'decimal.js-light' +import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' +import { AccountType } from '@/graphql/enum/AccountType' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { AccountRepository } from './Account.repository' +import { UserFactory } from './User.factory' +// eslint-disable-next-line n/no-extraneous-import +import { v4 as uuidv4 } from 'uuid' +import { UserLogic } from './User.logic' + +const con = TestDB.instance + +jest.mock('@typeorm/DataSource', () => ({ + getDataSource: jest.fn(() => TestDB.instance.dbConnect), +})) + +describe('data/Account test factory and repository', () => { + const now = new Date() + const keyPair1 = generateKeyPair(generateMnemonic('62ef251edc2416f162cd24ab1711982b')) + const keyPair2 = generateKeyPair(generateMnemonic('000a0000000002000000000003000070')) + const keyPair3 = generateKeyPair(generateMnemonic('00ba541a1000020000000000300bda70')) + const userGradidoID = '6be949ab-8198-4acf-ba63-740089081d61' + + describe('test factory methods', () => { + beforeAll(async () => { + await con.setupTestDB() + }) + afterAll(async () => { + await con.teardownTestDB() + }) + + it('test createAccount', () => { + const account = AccountFactory.createAccount(now, 1, AddressType.COMMUNITY_HUMAN, keyPair1) + expect(account).toMatchObject({ + derivationIndex: 1, + type: AddressType.COMMUNITY_HUMAN, + createdAt: now, + balanceCreatedAtDate: now, + balanceConfirmedAt: new Decimal(0), + balanceCreatedAt: new Decimal(0), + }) + }) + + it('test createAccountFromUserAccountDraft', () => { + const userAccountDraft = new UserAccountDraft() + userAccountDraft.createdAt = now.toISOString() + userAccountDraft.accountType = AccountType.COMMUNITY_HUMAN + userAccountDraft.user = new UserIdentifier() + userAccountDraft.user.accountNr = 1 + const account = AccountFactory.createAccountFromUserAccountDraft(userAccountDraft, keyPair1) + expect(account).toMatchObject({ + derivationIndex: 1, + type: AddressType.COMMUNITY_HUMAN, + createdAt: now, + balanceCreatedAtDate: now, + balanceConfirmedAt: new Decimal(0), + balanceCreatedAt: new Decimal(0), + }) + }) + + it('test createGmwAccount', () => { + const account = AccountFactory.createGmwAccount(keyPair1, now) + expect(account).toMatchObject({ + derivationIndex: 2147483649, + type: AddressType.COMMUNITY_GMW, + createdAt: now, + balanceCreatedAtDate: now, + balanceConfirmedAt: new Decimal(0), + balanceCreatedAt: new Decimal(0), + }) + }) + + it('test createAufAccount', () => { + const account = AccountFactory.createAufAccount(keyPair1, now) + expect(account).toMatchObject({ + derivationIndex: 2147483650, + type: AddressType.COMMUNITY_AUF, + createdAt: now, + balanceCreatedAtDate: now, + balanceConfirmedAt: new Decimal(0), + balanceCreatedAt: new Decimal(0), + }) + }) + }) + + describe('test repository functions', () => { + beforeAll(async () => { + await con.setupTestDB() + + await Promise.all([ + AccountFactory.createAufAccount(keyPair1, now).save(), + AccountFactory.createGmwAccount(keyPair1, now).save(), + AccountFactory.createAufAccount(keyPair2, now).save(), + AccountFactory.createGmwAccount(keyPair2, now).save(), + AccountFactory.createAufAccount(keyPair3, now).save(), + AccountFactory.createGmwAccount(keyPair3, now).save(), + ]) + const userAccountDraft = new UserAccountDraft() + userAccountDraft.accountType = AccountType.COMMUNITY_HUMAN + userAccountDraft.createdAt = now.toString() + userAccountDraft.user = new UserIdentifier() + userAccountDraft.user.accountNr = 1 + userAccountDraft.user.uuid = userGradidoID + const user = UserFactory.create(userAccountDraft, keyPair1) + const userLogic = new UserLogic(user) + const account = AccountFactory.createAccountFromUserAccountDraft( + userAccountDraft, + userLogic.calculateKeyPair(keyPair1), + ) + account.user = user + // user is set to cascade: ['insert'] will be saved together with account + await account.save() + }) + afterAll(async () => { + await con.teardownTestDB() + }) + it('test findAccountsByPublicKeys', async () => { + const accounts = await AccountRepository.findAccountsByPublicKeys([ + Buffer.from('6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', 'hex'), + Buffer.from('0fa996b73b624592fe326b8500cb1e3f10026112b374d84c87d097f4d489c019', 'hex'), + Buffer.from('0ffa996b73b624592f26b850b0cb1e3f1026112b374d84c87d017f4d489c0197', 'hex'), // invalid + ]) + expect(accounts).toHaveLength(2) + expect(accounts).toMatchObject( + expect.arrayContaining([ + expect.objectContaining({ + derivationIndex: 2147483649, + derive2Pubkey: Buffer.from( + '0fa996b73b624592fe326b8500cb1e3f10026112b374d84c87d097f4d489c019', + 'hex', + ), + type: AddressType.COMMUNITY_GMW, + }), + expect.objectContaining({ + derivationIndex: 2147483650, + derive2Pubkey: Buffer.from( + '6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', + 'hex', + ), + type: AddressType.COMMUNITY_AUF, + }), + ]), + ) + }) + + it('test findAccountByPublicKey', async () => { + expect( + await AccountRepository.findAccountByPublicKey( + Buffer.from('6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', 'hex'), + ), + ).toMatchObject({ + derivationIndex: 2147483650, + derive2Pubkey: Buffer.from( + '6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', + 'hex', + ), + type: AddressType.COMMUNITY_AUF, + }) + }) + + it('test findAccountByUserIdentifier', async () => { + const userIdentifier = new UserIdentifier() + userIdentifier.accountNr = 1 + userIdentifier.uuid = userGradidoID + expect(await AccountRepository.findAccountByUserIdentifier(userIdentifier)).toMatchObject({ + derivationIndex: 1, + derive2Pubkey: Buffer.from( + '2099c004a26e5387c9fbbc9bb0f552a9642d3fd7c710ae5802b775d24ff36f93', + 'hex', + ), + type: AddressType.COMMUNITY_HUMAN, + }) + }) + }) +}) diff --git a/dlt-connector/src/utils/cryptoHelper.ts b/dlt-connector/src/utils/cryptoHelper.ts index 1eb5db36d..467a85e85 100644 --- a/dlt-connector/src/utils/cryptoHelper.ts +++ b/dlt-connector/src/utils/cryptoHelper.ts @@ -1,6 +1,23 @@ import { KeyPair } from '@/data/KeyPair' -import { sign as ed25519Sign } from 'bip32-ed25519' +import { sign as ed25519Sign, generateFromSeed } from 'bip32-ed25519' +import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' +// eslint-disable-next-line camelcase +import { randombytes_buf } from 'sodium-native' export const sign = (message: Buffer, keyPair: KeyPair): Buffer => { return ed25519Sign(message, keyPair.getExtendPrivateKey()) } + +export const generateKeyPair = (mnemonic: string): KeyPair => { + const seedFromMnemonic = mnemonicToSeedSync(mnemonic) + return new KeyPair(generateFromSeed(seedFromMnemonic)) +} + +export const generateMnemonic = (seed?: Buffer | string): string => { + if (seed) { + return entropyToMnemonic(seed) + } + const entropy = Buffer.alloc(256) + randombytes_buf(entropy) + return entropyToMnemonic(entropy) +} diff --git a/dlt-connector/test/TestDB.ts b/dlt-connector/test/TestDB.ts index 457954f7d..75f362c65 100644 --- a/dlt-connector/test/TestDB.ts +++ b/dlt-connector/test/TestDB.ts @@ -6,6 +6,7 @@ import { entities } from '@entity/index' import { CONFIG } from '@/config' import { LogError } from '@/server/LogError' +// TODO: maybe use in memory db like here: https://dkzeb.medium.com/unit-testing-in-ts-jest-with-typeorm-entities-ad5de5f95438 export class TestDB { // eslint-disable-next-line no-use-before-define private static _instance: TestDB From ca95bf4ff1a53c7564b85927476dff8a2c134135 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 8 Dec 2023 13:42:51 +0100 Subject: [PATCH 20/47] fix lint --- dlt-connector/src/data/Account.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/dlt-connector/src/data/Account.test.ts b/dlt-connector/src/data/Account.test.ts index 5a1e00277..62625a66f 100644 --- a/dlt-connector/src/data/Account.test.ts +++ b/dlt-connector/src/data/Account.test.ts @@ -9,8 +9,6 @@ import { AccountType } from '@/graphql/enum/AccountType' import { UserIdentifier } from '@/graphql/input/UserIdentifier' import { AccountRepository } from './Account.repository' import { UserFactory } from './User.factory' -// eslint-disable-next-line n/no-extraneous-import -import { v4 as uuidv4 } from 'uuid' import { UserLogic } from './User.logic' const con = TestDB.instance From 443a7308a11dadcff0ae0386a0e365b1f0ea2d09 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 8 Dec 2023 13:49:59 +0100 Subject: [PATCH 21/47] update filename according to class name change, update imports --- dlt-connector/src/data/proto/3_3/CommunityRoot.ts | 2 +- dlt-connector/src/data/proto/3_3/GradidoCreation.ts | 2 +- dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts | 2 +- dlt-connector/src/data/proto/3_3/GradidoTransfer.ts | 2 +- dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts | 2 +- dlt-connector/src/data/proto/3_3/RegisterAddress.ts | 2 +- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 2 +- .../data/proto/{TransactionBase.ts => AbstractTransaction.ts} | 0 8 files changed, 7 insertions(+), 7 deletions(-) rename dlt-connector/src/data/proto/{TransactionBase.ts => AbstractTransaction.ts} (100%) diff --git a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts index ec69be4f6..442716c3b 100644 --- a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -1,4 +1,4 @@ -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Community } from '@entity/Community' diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts index 4a3ff91f9..31ac08e26 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -5,7 +5,7 @@ import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' diff --git a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index ceedf579d..ebe407d0d 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { GradidoTransfer } from './GradidoTransfer' import { TimestampSeconds } from './TimestampSeconds' -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts index d68b8ccf7..31cb25ae9 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -2,7 +2,7 @@ import { Field, Message } from 'protobufjs' import { TransferAmount } from './TransferAmount' import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' diff --git a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 91d3693b0..52d676ffe 100644 --- a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts +++ b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Field, Message } from 'protobufjs' import { Transaction } from '@entity/Transaction' diff --git a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts index 639b01a54..494d077ed 100644 --- a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -3,7 +3,7 @@ import { Field, Message } from 'protobufjs' import { AddressType } from '@/data/proto/3_3/enum/AddressType' -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 9e7eaeddd..dceb03314 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -13,7 +13,7 @@ import { determineCrossGroupType, determineOtherGroup } from '../transactionBody import { CommunityRoot } from './CommunityRoot' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { TransactionType } from '@/graphql/enum/TransactionType' -import { AbstractTransaction } from '../TransactionBase' +import { AbstractTransaction } from '../AbstractTransaction' import { Transaction } from '@entity/Transaction' import { timestampToDate } from '@/utils/typeConverter' import { LogError } from '@/server/LogError' diff --git a/dlt-connector/src/data/proto/TransactionBase.ts b/dlt-connector/src/data/proto/AbstractTransaction.ts similarity index 100% rename from dlt-connector/src/data/proto/TransactionBase.ts rename to dlt-connector/src/data/proto/AbstractTransaction.ts From b8ee84b7be9b834a53fc0bd09472ce0d517d3568 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Mon, 11 Dec 2023 14:36:10 +0100 Subject: [PATCH 22/47] update community field names in transactions table, fix bug in DataSource --- dlt-connector/src/config/index.ts | 2 +- dlt-connector/src/data/Transaction.builder.ts | 40 +++++++++---------- .../src/graphql/model/TransactionRecipe.ts | 4 +- .../CommunityRootTransaction.role.ts | 2 +- .../transaction/TransactionRecipe.role.ts | 4 +- dlt-connector/src/typeorm/DataSource.ts | 10 +++-- .../Community.ts | 8 ++-- .../Transaction.ts | 20 +++++----- .../0003-refactor_transaction_recipe.ts | 8 ++-- 9 files changed, 50 insertions(+), 48 deletions(-) diff --git a/dlt-connector/src/config/index.ts b/dlt-connector/src/config/index.ts index fc8c780b8..c129af2ea 100644 --- a/dlt-connector/src/config/index.ts +++ b/dlt-connector/src/config/index.ts @@ -4,7 +4,7 @@ dotenv.config() const constants = { LOG4JS_CONFIG: 'log4js-config.json', - DB_VERSION: '0002-refactor_add_community', + DB_VERSION: '0003-refactor_transaction_recipe', // default log level on production should be info LOG_LEVEL: process.env.LOG_LEVEL || 'info', CONFIG_VERSION: { diff --git a/dlt-connector/src/data/Transaction.builder.ts b/dlt-connector/src/data/Transaction.builder.ts index 321dda76b..23820bb4d 100644 --- a/dlt-connector/src/data/Transaction.builder.ts +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -51,8 +51,8 @@ export class TransactionBuilder { return this.transaction } - public getSenderCommunity(): Community { - return this.transaction.senderCommunity + public getCommunity(): Community { + return this.transaction.community } public setSigningAccount(signingAccount: Account): TransactionBuilder { @@ -65,21 +65,21 @@ export class TransactionBuilder { return this } - public setSenderCommunity(senderCommunity: Community): TransactionBuilder { - this.transaction.senderCommunity = senderCommunity + public setCommunity(community: Community): TransactionBuilder { + this.transaction.community = community return this } - public setRecipientCommunity(recipientCommunity?: Community): TransactionBuilder { - if (!this.transaction.senderCommunity) { - throw new LogError('Please set sender community first!') + public setOtherCommunity(otherCommunity?: Community): TransactionBuilder { + if (!this.transaction.community) { + throw new LogError('Please set community first!') } - this.transaction.recipientCommunity = - recipientCommunity && - this.transaction.senderCommunity && - this.transaction.senderCommunity.id !== recipientCommunity.id - ? recipientCommunity + this.transaction.otherCommunity = + otherCommunity && + this.transaction.community && + this.transaction.community.id !== otherCommunity.id + ? otherCommunity : undefined return this } @@ -98,21 +98,19 @@ export class TransactionBuilder { senderUser: UserIdentifier, ): Promise { // get sender community - const senderCommunity = await CommunityRepository.getCommunityForUserIdentifier(senderUser) - if (!senderCommunity) { - throw new LogError("couldn't find sender community for transaction") + const community = await CommunityRepository.getCommunityForUserIdentifier(senderUser) + if (!community) { + throw new LogError("couldn't find community for transaction") } - return this.setSenderCommunity(senderCommunity) + return this.setCommunity(community) } - public async setRecipientCommunityFromRecipientUser( + public async setOtherCommunityFromRecipientUser( recipientUser: UserIdentifier, ): Promise { // get recipient community - const recipientCommunity = await CommunityRepository.getCommunityForUserIdentifier( - recipientUser, - ) - return this.setRecipientCommunity(recipientCommunity) + const otherCommunity = await CommunityRepository.getCommunityForUserIdentifier(recipientUser) + return this.setOtherCommunity(otherCommunity) } public async fromGradidoTransactionSearchForAccounts( diff --git a/dlt-connector/src/graphql/model/TransactionRecipe.ts b/dlt-connector/src/graphql/model/TransactionRecipe.ts index 3b37ba4ea..a4dacd9e9 100644 --- a/dlt-connector/src/graphql/model/TransactionRecipe.ts +++ b/dlt-connector/src/graphql/model/TransactionRecipe.ts @@ -4,11 +4,11 @@ import { Transaction } from '@entity/Transaction' @ObjectType() export class TransactionRecipe { - public constructor({ id, createdAt, type, senderCommunity }: Transaction) { + public constructor({ id, createdAt, type, community }: Transaction) { this.id = id this.createdAt = createdAt.toString() this.type = type - this.topic = senderCommunity.iotaTopic + this.topic = community.iotaTopic } @Field(() => Int) diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts index aa09f89b2..240c86dc4 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts @@ -15,7 +15,7 @@ export class CommunityRootTransactionRole extends TransactionRecipeRole { .fromCommunityDraft(communityDraft, community) .build() // build transaction entity - this.transactionBuilder.fromTransactionBody(transactionBody).setSenderCommunity(community) + this.transactionBuilder.fromTransactionBody(transactionBody).setCommunity(community) const transaction = this.transactionBuilder.getTransaction() // sign this.transactionBuilder.setSignature(sign(transaction.bodyBytes, new KeyPair(community))) diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index caebb4fc4..6b59e5eaa 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -47,12 +47,12 @@ export class TransactionRecipeRole { .setBackendTransactionId(transactionDraft.backendTransactionId) await this.transactionBuilder.setSenderCommunityFromSenderUser(senderUser) if (recipientUser.communityUuid !== senderUser.communityUuid) { - await this.transactionBuilder.setRecipientCommunityFromRecipientUser(recipientUser) + await this.transactionBuilder.setOtherCommunityFromRecipientUser(recipientUser) } const transaction = this.transactionBuilder.getTransaction() // sign this.transactionBuilder.setSignature( - sign(transaction.bodyBytes, new KeyPair(this.transactionBuilder.getSenderCommunity())), + sign(transaction.bodyBytes, new KeyPair(this.transactionBuilder.getCommunity())), ) return this } diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index 62cdbf755..a5db6443d 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -71,12 +71,16 @@ export class Connection { } async checkDBVersion(DB_VERSION: string): Promise { - const dbVersion = await Migration.findOneOrFail({ order: { version: 'DESC' } }) + const dbVersion = await Migration.find({ order: { version: 'DESC' }, take: 1 }) + if (!dbVersion || dbVersion.length < 1) { + throw new LogError('found no db version in migrations, could dlt-database run successfully?') + } + console.log(dbVersion[0].fileName) // return dbVersion ? dbVersion.fileName : null - if (!dbVersion.fileName.includes(DB_VERSION)) { + if (!dbVersion[0].fileName.includes(DB_VERSION)) { throw new LogError( `Wrong database version detected - the backend requires '${DB_VERSION}' but found '${ - dbVersion ?? 'None' + dbVersion[0].fileName ?? 'None' }`, ) } diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts index f403064b4..1233d0832 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts @@ -56,9 +56,9 @@ export class Community extends BaseEntity { @JoinColumn({ name: 'community_id' }) accountCommunities: AccountCommunity[] - @OneToMany(() => Transaction, (recipe) => recipe.senderCommunity) - transactionSender?: Transaction[] + @OneToMany(() => Transaction, (transaction) => transaction.community) + transactions?: Transaction[] - @OneToMany(() => Transaction, (recipe) => recipe.recipientCommunity) - transactionRecipient?: Transaction[] + @OneToMany(() => Transaction, (transaction) => transaction.otherCommunity) + friendCommunitiesTransactions?: Transaction[] } diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index e9d8c6a0e..06c06927b 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -46,21 +46,21 @@ export class Transaction extends BaseEntity { @Column({ name: 'recipient_account_id', type: 'int', unsigned: true, nullable: true }) recipientAccountId?: number - @ManyToOne(() => Community, (community) => community.transactionSender, { + @ManyToOne(() => Community, (community) => community.transactions, { eager: true, }) - @JoinColumn({ name: 'sender_community_id' }) - senderCommunity: Community + @JoinColumn({ name: 'community_id' }) + community: Community - @Column({ name: 'sender_community_id', type: 'int', unsigned: true }) - senderCommunityId: number + @Column({ name: 'community_id', type: 'int', unsigned: true }) + communityId: number - @ManyToOne(() => Community, (community) => community.transactionRecipient) - @JoinColumn({ name: 'recipient_community_id' }) - recipientCommunity?: Community + @ManyToOne(() => Community, (community) => community.friendCommunitiesTransactions) + @JoinColumn({ name: 'other_community_id' }) + otherCommunity?: Community - @Column({ name: 'recipient_community_id', type: 'int', unsigned: true, nullable: true }) - recipientCommunityId?: number + @Column({ name: 'other_community_id', type: 'int', unsigned: true, nullable: true }) + otherCommunityId?: number @Column({ type: 'decimal', diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index cf5657485..fc842d49d 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -34,8 +34,8 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`paring_transaction_id\` bigint unsigned NULL DEFAULT NULL, \`signing_account_id\` int unsigned NULL DEFAULT NULL, \`recipient_account_id\` int unsigned NULL DEFAULT NULL, - \`sender_community_id\` int unsigned NOT NULL, - \`recipient_community_id\` int unsigned NULL DEFAULT NULL, + \`community_id\` int unsigned NOT NULL, + \`other_community_id\` int unsigned NULL DEFAULT NULL, \`amount\` decimal(40, 20) NULL DEFAULT NULL, \`account_balance_created_at\` decimal(40, 20) NOT NULL, \`type\` tinyint NOT NULL, @@ -52,8 +52,8 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis UNIQUE KEY \`signature\` (\`signature\`), FOREIGN KEY (\`signing_account_id\`) REFERENCES accounts(id), FOREIGN KEY (\`recipient_account_id\`) REFERENCES accounts(id), - FOREIGN KEY (\`sender_community_id\`) REFERENCES communities(id), - FOREIGN KEY (\`recipient_community_id\`) REFERENCES communities(id) + FOREIGN KEY (\`community_id\`) REFERENCES communities(id), + FOREIGN KEY (\`other_community_id\`) REFERENCES communities(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `, ) From cb5c5e476a597229a14f69a35049bdd5bbb00a73 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Mon, 11 Dec 2023 14:45:26 +0100 Subject: [PATCH 23/47] remove console.log --- dlt-connector/src/typeorm/DataSource.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index a5db6443d..441cf7eef 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -75,7 +75,6 @@ export class Connection { if (!dbVersion || dbVersion.length < 1) { throw new LogError('found no db version in migrations, could dlt-database run successfully?') } - console.log(dbVersion[0].fileName) // return dbVersion ? dbVersion.fileName : null if (!dbVersion[0].fileName.includes(DB_VERSION)) { throw new LogError( From 00a6e861ef7d10f71e6ad8dd02766638e5fdf14b Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 12 Dec 2023 13:17:02 +0100 Subject: [PATCH 24/47] change not null to null --- dlt-database/migrations/0003-refactor_transaction_recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index fc842d49d..f51f277fd 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -37,7 +37,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`community_id\` int unsigned NOT NULL, \`other_community_id\` int unsigned NULL DEFAULT NULL, \`amount\` decimal(40, 20) NULL DEFAULT NULL, - \`account_balance_created_at\` decimal(40, 20) NOT NULL, + \`account_balance_created_at\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, \`type\` tinyint NOT NULL, \`created_at\` datetime(3) NOT NULL, \`body_bytes\` blob NOT NULL, From 3d245dc3af1cad73eeb49b0e2e7abb37516c3192 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 15 Dec 2023 19:21:52 +0100 Subject: [PATCH 25/47] add error message column for invalid transaction --- .../InvalidTransaction.ts | 13 +++++++++++++ dlt-database/entity/InvalidTransaction.ts | 2 +- .../migrations/0003-refactor_transaction_recipe.ts | 5 +++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts new file mode 100644 index 000000000..e103e253f --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts @@ -0,0 +1,13 @@ +import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm' + +@Entity('invalid_transactions') +export class InvalidTransaction extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) + id: number + + @Column({ name: 'iota_message_id', type: 'binary', length: 32 }) + iotaMessageId: Buffer + + @Column({ name: 'error_message', type: 'varchar', length: 255 }) + errorMessage: string +} diff --git a/dlt-database/entity/InvalidTransaction.ts b/dlt-database/entity/InvalidTransaction.ts index 8042e74b4..166b13adf 100644 --- a/dlt-database/entity/InvalidTransaction.ts +++ b/dlt-database/entity/InvalidTransaction.ts @@ -1 +1 @@ -export { InvalidTransaction } from './0001-init_db/InvalidTransaction' +export { InvalidTransaction } from './0003-refactor_transaction_recipe/InvalidTransaction' diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index f51f277fd..2d3d92a23 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -26,6 +26,10 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at_date\` datetime NULL DEFAULT NULL;`, ) + await queryFn( + `ALTER TABLE \`invalid_transactions\` ADD COLUMN \`error_message\` varchar(255) NOT NULL;`, + ) + await queryFn( `CREATE TABLE \`transactions\` ( \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, @@ -121,6 +125,7 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom ) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at\`;`) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) + await queryFn(`ALTER TABLE \`invalid_transactions\` DROP COLUMN \`error_message\`;`) await queryFn(`DROP TABLE \`transactions\`;`) await queryFn( From c5c073bff412a7d0969e6ed008b4ba75d986e96a Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Sun, 17 Dec 2023 16:31:54 +0100 Subject: [PATCH 26/47] db update --- .../0003-refactor_transaction_recipe/Account.ts | 4 ++-- .../InvalidTransaction.ts | 2 +- .../migrations/0003-refactor_transaction_recipe.ts | 11 +++++------ 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts index a6e8a8b7e..b8beea8ff 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -26,8 +26,8 @@ export class Account extends BaseEntity { @Column({ name: 'user_id', type: 'int', unsigned: true, nullable: true }) userId?: number - @Column({ name: 'derivation_index', type: 'int', unsigned: true, nullable: true }) - derivationIndex?: number + @Column({ name: 'derivation_index', type: 'int', unsigned: true }) + derivationIndex: number @Column({ name: 'derive2_pubkey', type: 'binary', length: 32, unique: true }) derive2Pubkey: Buffer diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts index e103e253f..a34823dbd 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/InvalidTransaction.ts @@ -5,7 +5,7 @@ export class InvalidTransaction extends BaseEntity { @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) id: number - @Column({ name: 'iota_message_id', type: 'binary', length: 32 }) + @Column({ name: 'iota_message_id', type: 'binary', length: 32, unique: true }) iotaMessageId: Buffer @Column({ name: 'error_message', type: 'varchar', length: 255 }) diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index 2d3d92a23..882f2db00 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -13,9 +13,6 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis ; `) - await queryFn( - `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NULL DEFAULT NULL;`, - ) await queryFn( `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_confirmed_at_date\`;`, ) @@ -30,6 +27,9 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis `ALTER TABLE \`invalid_transactions\` ADD COLUMN \`error_message\` varchar(255) NOT NULL;`, ) + await queryFn(`ALTER TABLE \`invalid_transactions\` DROP INDEX \`iota_message_id\`;`) + await queryFn(`ALTER TABLE \`invalid_transactions\` ADD UNIQUE(\`iota_message_id\`);`) + await queryFn( `CREATE TABLE \`transactions\` ( \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, @@ -120,12 +120,11 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom ; `) - await queryFn( - `ALTER TABLE \`accounts\` MODIFY COLUMN \`derivation_index\` int(10) unsigned NOT NULL;`, - ) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at\`;`) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) await queryFn(`ALTER TABLE \`invalid_transactions\` DROP COLUMN \`error_message\`;`) + await queryFn(`ALTER TABLE \`invalid_transactions\` DROP INDEX \`iota_message_id\`;`) + await queryFn(`ALTER TABLE \`invalid_transactions\` ADD INDEX(\`iota_message_id\`); `) await queryFn(`DROP TABLE \`transactions\`;`) await queryFn( From 0567a3ddf0ccadde280cacaf80c761a96b6ba456 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 19 Dec 2023 15:07:53 +0100 Subject: [PATCH 27/47] add lint rule for sorted import like in backend, sort imports, refactor enums, remove KeyManager --- dlt-connector/.eslintrc.js | 48 +++---- dlt-connector/src/data/Account.factory.ts | 17 ++- dlt-connector/src/data/Account.repository.ts | 5 +- dlt-connector/src/data/Account.test.ts | 37 ++++-- .../src/data/Community.repository.ts | 8 +- dlt-connector/src/data/KeyPair.ts | 81 +++++++++--- dlt-connector/src/data/Mnemonic.ts | 25 ++++ dlt-connector/src/data/Transaction.builder.ts | 18 +-- .../src/data/Transaction.repository.ts | 3 +- dlt-connector/src/data/User.factory.ts | 8 +- dlt-connector/src/data/User.logic.ts | 11 +- dlt-connector/src/data/User.repository.ts | 5 +- .../src/data/proto/3_3/CommunityRoot.ts | 11 +- .../data/proto/3_3/ConfirmedTransaction.ts | 4 +- .../data/proto/3_3/GradidoCreation.test.ts | 8 +- .../src/data/proto/3_3/GradidoCreation.ts | 26 ++-- .../data/proto/3_3/GradidoDeferredTransfer.ts | 13 +- .../src/data/proto/3_3/GradidoTransaction.ts | 7 +- .../src/data/proto/3_3/GradidoTransfer.ts | 25 ++-- .../src/data/proto/3_3/GroupFriendsUpdate.ts | 10 +- .../src/data/proto/3_3/RegisterAddress.ts | 8 +- .../src/data/proto/3_3/TransactionBody.ts | 35 ++++-- .../src/data/proto/3_3/enum/AddressType.ts | 15 +-- .../src/data/proto/3_3/enum/CrossGroupType.ts | 19 ++- .../data/proto/3_3/enum/TransactionType.ts | 13 ++ .../src/data/proto/AbstractTransaction.ts | 4 - .../src/data/proto/TransactionBody.builder.ts | 14 ++- .../src/data/proto/transactionBody.logic.ts | 9 +- dlt-connector/src/graphql/enum/AccountType.ts | 7 +- .../src/graphql/enum/InputTransactionType.ts | 14 +-- .../src/graphql/enum/TransactionErrorType.ts | 2 + .../src/graphql/enum/TransactionType.ts | 15 --- .../enum/TransactionValidationLevel.ts | 15 --- .../src/graphql/input/CommunityDraft.ts | 1 + .../src/graphql/input/TransactionDraft.ts | 9 +- .../src/graphql/input/UserAccountDraft.ts | 9 +- dlt-connector/src/graphql/model/Community.ts | 2 +- .../src/graphql/model/TransactionError.ts | 1 + .../src/graphql/model/TransactionRecipe.ts | 17 ++- .../src/graphql/model/TransactionResult.ts | 1 + .../resolver/CommunityResolver.test.ts | 12 +- .../src/graphql/resolver/CommunityResolver.ts | 18 +-- .../resolver/TransactionsResolver.test.ts | 52 ++++---- .../graphql/resolver/TransactionsResolver.ts | 11 +- dlt-connector/src/graphql/schema.ts | 4 +- dlt-connector/src/index.ts | 3 +- .../community/AddCommunity.context.ts | 5 +- .../backendToDb/community/Community.role.ts | 3 +- .../community/HomeCommunity.role.ts | 25 ++-- .../CommunityRootTransaction.role.ts | 11 +- .../CreateTransationRecipe.context.ts | 12 +- .../transaction/TransactionRecipe.role.ts | 8 +- dlt-connector/src/manager/KeyManager.test.ts | 22 ---- dlt-connector/src/manager/KeyManager.ts | 118 ------------------ dlt-connector/src/server/createServer.ts | 10 +- dlt-connector/src/server/logger.ts | 4 +- dlt-connector/src/typeorm/DataSource.ts | 4 +- dlt-connector/src/utils/cryptoHelper.ts | 23 ---- .../src/utils/derivationHelper.test.ts | 1 + dlt-connector/src/utils/typeConverter.test.ts | 1 + dlt-connector/src/utils/typeConverter.ts | 80 ++++++------ dlt-connector/test/ApolloServerMock.ts | 1 + dlt-connector/test/TestDB.ts | 3 +- 63 files changed, 487 insertions(+), 524 deletions(-) create mode 100644 dlt-connector/src/data/Mnemonic.ts create mode 100644 dlt-connector/src/data/proto/3_3/enum/TransactionType.ts delete mode 100644 dlt-connector/src/graphql/enum/TransactionType.ts delete mode 100644 dlt-connector/src/graphql/enum/TransactionValidationLevel.ts delete mode 100644 dlt-connector/src/manager/KeyManager.test.ts delete mode 100644 dlt-connector/src/manager/KeyManager.ts delete mode 100644 dlt-connector/src/utils/cryptoHelper.ts diff --git a/dlt-connector/.eslintrc.js b/dlt-connector/.eslintrc.js index b2bc4047e..fa43a5f1a 100644 --- a/dlt-connector/.eslintrc.js +++ b/dlt-connector/.eslintrc.js @@ -77,30 +77,30 @@ module.exports = { // 'import/no-named-default': 'error', // 'import/no-namespace': 'error', // 'import/no-unassigned-import': 'error', - // 'import/order': [ - // 'error', - // { - // groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object', 'type'], - // 'newlines-between': 'always', - // pathGroups: [ - // { - // pattern: '@?*/**', - // group: 'external', - // position: 'after', - // }, - // { - // pattern: '@/**', - // group: 'external', - // position: 'after', - // }, - // ], - // alphabetize: { - // order: 'asc' /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */, - // caseInsensitive: true /* ignore case. Options: [true, false] */, - // }, - // distinctGroup: true, - // }, - // ], + 'import/order': [ + 'error', + { + groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object', 'type'], + 'newlines-between': 'always', + pathGroups: [ + { + pattern: '@?*/**', + group: 'external', + position: 'after', + }, + { + pattern: '@/**', + group: 'external', + position: 'after', + }, + ], + alphabetize: { + order: 'asc' /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */, + caseInsensitive: true /* ignore case. Options: [true, false] */, + }, + distinctGroup: true, + }, + ], // 'import/prefer-default-export': 'off', // n 'n/handle-callback-err': 'error', diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index 493e394bb..e318cb104 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -1,10 +1,10 @@ -import { KeyManager } from '@/manager/KeyManager' -import { KeyPair } from '@/data/KeyPair' -import { AddressType } from '@/data/proto/3_3/enum/AddressType' -import { hardenDerivationIndex } from '@/utils/derivationHelper' import { Account } from '@entity/Account' import Decimal from 'decimal.js-light' + +import { KeyPair } from '@/data/KeyPair' +import { AddressType } from '@/data/proto/3_3/enum/AddressType' import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' +import { hardenDerivationIndex } from '@/utils/derivationHelper' import { accountTypeToAddressType } from '@/utils/typeConverter' const GMW_ACCOUNT_DERIVATION_INDEX = 1 @@ -15,14 +15,11 @@ export class AccountFactory { createdAt: Date, derivationIndex: number, type: AddressType, - parentKeyPair?: KeyPair, + parentKeyPair: KeyPair, ): Account { const account = Account.create() account.derivationIndex = derivationIndex - account.derive2Pubkey = KeyManager.getInstance().derive( - [derivationIndex], - parentKeyPair, - ).publicKey + account.derive2Pubkey = parentKeyPair.derive([derivationIndex]).publicKey account.type = type.valueOf() account.createdAt = createdAt account.balanceConfirmedAt = new Decimal(0) @@ -33,7 +30,7 @@ export class AccountFactory { public static createAccountFromUserAccountDraft( { createdAt, accountType, user }: UserAccountDraft, - parentKeyPair?: KeyPair, + parentKeyPair: KeyPair, ): Account { return AccountFactory.createAccount( new Date(createdAt), diff --git a/dlt-connector/src/data/Account.repository.ts b/dlt-connector/src/data/Account.repository.ts index ea97080fd..6931e6ea6 100644 --- a/dlt-connector/src/data/Account.repository.ts +++ b/dlt-connector/src/data/Account.repository.ts @@ -1,9 +1,10 @@ -import { UserIdentifier } from '@/graphql/input/UserIdentifier' -import { getDataSource } from '@/typeorm/DataSource' import { Account } from '@entity/Account' import { User } from '@entity/User' import { In } from 'typeorm' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { getDataSource } from '@/typeorm/DataSource' + export const AccountRepository = getDataSource() .getRepository(Account) .extend({ diff --git a/dlt-connector/src/data/Account.test.ts b/dlt-connector/src/data/Account.test.ts index 62625a66f..596b51dc2 100644 --- a/dlt-connector/src/data/Account.test.ts +++ b/dlt-connector/src/data/Account.test.ts @@ -1,13 +1,17 @@ import 'reflect-metadata' -import { TestDB } from '@test/TestDB' -import { AccountFactory } from './Account.factory' -import { AddressType } from './proto/3_3/enum/AddressType' -import { generateKeyPair, generateMnemonic } from '@/utils/cryptoHelper' import { Decimal } from 'decimal.js-light' -import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' + +import { TestDB } from '@test/TestDB' + import { AccountType } from '@/graphql/enum/AccountType' +import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' import { UserIdentifier } from '@/graphql/input/UserIdentifier' + +import { AccountFactory } from './Account.factory' import { AccountRepository } from './Account.repository' +import { KeyPair } from './KeyPair' +import { Mnemonic } from './Mnemonic' +import { AddressType } from './proto/3_3/enum/AddressType' import { UserFactory } from './User.factory' import { UserLogic } from './User.logic' @@ -19,9 +23,9 @@ jest.mock('@typeorm/DataSource', () => ({ describe('data/Account test factory and repository', () => { const now = new Date() - const keyPair1 = generateKeyPair(generateMnemonic('62ef251edc2416f162cd24ab1711982b')) - const keyPair2 = generateKeyPair(generateMnemonic('000a0000000002000000000003000070')) - const keyPair3 = generateKeyPair(generateMnemonic('00ba541a1000020000000000300bda70')) + const keyPair1 = new KeyPair(new Mnemonic('62ef251edc2416f162cd24ab1711982b')) + const keyPair2 = new KeyPair(new Mnemonic('000a0000000002000000000003000070')) + const keyPair3 = new KeyPair(new Mnemonic('00ba541a1000020000000000300bda70')) const userGradidoID = '6be949ab-8198-4acf-ba63-740089081d61' describe('test factory methods', () => { @@ -36,6 +40,10 @@ describe('data/Account test factory and repository', () => { const account = AccountFactory.createAccount(now, 1, AddressType.COMMUNITY_HUMAN, keyPair1) expect(account).toMatchObject({ derivationIndex: 1, + derive2Pubkey: Buffer.from( + 'cb88043ef4833afc01d6ed9b34e1aa48e79dce5ff97c07090c6600ec05f6d994', + 'hex', + ), type: AddressType.COMMUNITY_HUMAN, createdAt: now, balanceCreatedAtDate: now, @@ -53,6 +61,10 @@ describe('data/Account test factory and repository', () => { const account = AccountFactory.createAccountFromUserAccountDraft(userAccountDraft, keyPair1) expect(account).toMatchObject({ derivationIndex: 1, + derive2Pubkey: Buffer.from( + 'cb88043ef4833afc01d6ed9b34e1aa48e79dce5ff97c07090c6600ec05f6d994', + 'hex', + ), type: AddressType.COMMUNITY_HUMAN, createdAt: now, balanceCreatedAtDate: now, @@ -65,6 +77,10 @@ describe('data/Account test factory and repository', () => { const account = AccountFactory.createGmwAccount(keyPair1, now) expect(account).toMatchObject({ derivationIndex: 2147483649, + derive2Pubkey: Buffer.from( + '05f0060357bb73bd290283870fc47a10b3764f02ca26938479ed853f46145366', + 'hex', + ), type: AddressType.COMMUNITY_GMW, createdAt: now, balanceCreatedAtDate: now, @@ -77,6 +93,10 @@ describe('data/Account test factory and repository', () => { const account = AccountFactory.createAufAccount(keyPair1, now) expect(account).toMatchObject({ derivationIndex: 2147483650, + derive2Pubkey: Buffer.from( + '6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', + 'hex', + ), type: AddressType.COMMUNITY_AUF, createdAt: now, balanceCreatedAtDate: now, @@ -89,7 +109,6 @@ describe('data/Account test factory and repository', () => { describe('test repository functions', () => { beforeAll(async () => { await con.setupTestDB() - await Promise.all([ AccountFactory.createAufAccount(keyPair1, now).save(), AccountFactory.createGmwAccount(keyPair1, now).save(), diff --git a/dlt-connector/src/data/Community.repository.ts b/dlt-connector/src/data/Community.repository.ts index 848d7b962..78023b15e 100644 --- a/dlt-connector/src/data/Community.repository.ts +++ b/dlt-connector/src/data/Community.repository.ts @@ -1,14 +1,16 @@ +import { Community } from '@entity/Community' +import { FindOptionsSelect, In, IsNull, Not } from 'typeorm' + import { CommunityArg } from '@/graphql/arg/CommunityArg' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { UserIdentifier } from '@/graphql/input/UserIdentifier' import { TransactionError } from '@/graphql/model/TransactionError' +import { LogError } from '@/server/LogError' import { getDataSource } from '@/typeorm/DataSource' import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' -import { Community } from '@entity/Community' -import { FindOptionsSelect, In, IsNull, Not } from 'typeorm' + import { KeyPair } from './KeyPair' -import { LogError } from '@/server/LogError' export const CommunityRepository = getDataSource() .getRepository(Community) diff --git a/dlt-connector/src/data/KeyPair.ts b/dlt-connector/src/data/KeyPair.ts index 3487c1d95..59e9a5066 100644 --- a/dlt-connector/src/data/KeyPair.ts +++ b/dlt-connector/src/data/KeyPair.ts @@ -1,38 +1,87 @@ -// https://www.npmjs.com/package/bip32-ed25519?activeTab=code -import { toPublic } from 'bip32-ed25519' import { Community } from '@entity/Community' + +// https://www.npmjs.com/package/bip32-ed25519 import { LogError } from '@/server/LogError' +import { toPublic, derivePrivate, sign, verify, generateFromSeed } from 'bip32-ed25519' + +import { Mnemonic } from './Mnemonic' + +/** + * Class Managing Key Pair and also generate, sign and verify signature with it + */ export class KeyPair { + private _publicKey: Buffer + private _chainCode: Buffer + private _privateKey: Buffer + /** - * @param input: Buffer = extended private key, returned from bip32-ed25519 generateFromSeed + * @param input: Mnemonic = Mnemonic or Passphrase which work as seed for generating algorithms + * @param input: Buffer = extended private key, returned from bip32-ed25519 generateFromSeed or from derivePrivate * @param input: Community = community entity with keys loaded from db * */ - public constructor(input: Buffer | Community) { - if (input instanceof Buffer) { - this.privateKey = input.subarray(0, 64) - this.chainCode = input.subarray(64, 96) - this.publicKey = toPublic(input).subarray(0, 32) + public constructor(input: Mnemonic | Buffer | Community) { + if (input instanceof Mnemonic) { + this.loadFromExtendedPrivateKey(generateFromSeed(input.seed)) + } else if (input instanceof Buffer) { + this.loadFromExtendedPrivateKey(input) } else if (input instanceof Community) { if (!input.rootPrivkey || !input.rootChaincode || !input.rootPubkey) { throw new LogError('missing private key or chaincode or public key in commmunity entity') } - this.privateKey = input.rootPrivkey - this.publicKey = input.rootPubkey - this.chainCode = input.rootChaincode + this._privateKey = input.rootPrivkey + this._publicKey = input.rootPubkey + this._chainCode = input.rootChaincode } } + /** + * copy keys to community entity + * @param community + */ + public fillInCommunityKeys(community: Community) { + community.rootPubkey = this._publicKey + community.rootPrivkey = this._privateKey + community.rootChaincode = this._chainCode + } + + private loadFromExtendedPrivateKey(extendedPrivateKey: Buffer) { + if (extendedPrivateKey.length !== 96) { + throw new LogError('invalid extended private key') + } + this._privateKey = extendedPrivateKey.subarray(0, 64) + this._chainCode = extendedPrivateKey.subarray(64, 96) + this._publicKey = toPublic(extendedPrivateKey).subarray(0, 32) + } + public getExtendPrivateKey(): Buffer { - return Buffer.concat([this.privateKey, this.chainCode]) + return Buffer.concat([this._privateKey, this._chainCode]) } public getExtendPublicKey(): Buffer { - return Buffer.concat([this.publicKey, this.chainCode]) + return Buffer.concat([this._publicKey, this._chainCode]) } - publicKey: Buffer - chainCode: Buffer - privateKey: Buffer + public get publicKey(): Buffer { + return this._publicKey + } + + public derive(path: number[]): KeyPair { + const extendedPrivateKey = this.getExtendPrivateKey() + return new KeyPair( + path.reduce( + (extendPrivateKey: Buffer, node: number) => derivePrivate(extendPrivateKey, node), + extendedPrivateKey, + ), + ) + } + + public sign(message: Buffer): Buffer { + return sign(message, this.getExtendPrivateKey()) + } + + public verify(message: Buffer, signature: Buffer): boolean { + return verify(message, signature, this.getExtendPublicKey()) + } } diff --git a/dlt-connector/src/data/Mnemonic.ts b/dlt-connector/src/data/Mnemonic.ts new file mode 100644 index 000000000..8f15c1046 --- /dev/null +++ b/dlt-connector/src/data/Mnemonic.ts @@ -0,0 +1,25 @@ +// https://www.npmjs.com/package/bip39 +import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' +// eslint-disable-next-line camelcase +import { randombytes_buf } from 'sodium-native' + +export class Mnemonic { + private _passphrase = '' + public constructor(seed?: Buffer | string) { + if (seed) { + this._passphrase = entropyToMnemonic(seed) + return + } + const entropy = Buffer.alloc(256) + randombytes_buf(entropy) + this._passphrase = entropyToMnemonic(entropy) + } + + public get passphrase(): string { + return this._passphrase + } + + public get seed(): Buffer { + return mnemonicToSeedSync(this._passphrase) + } +} diff --git a/dlt-connector/src/data/Transaction.builder.ts b/dlt-connector/src/data/Transaction.builder.ts index 23820bb4d..7cbcedac5 100644 --- a/dlt-connector/src/data/Transaction.builder.ts +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -1,13 +1,15 @@ -import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' -import { TransactionBody } from '@/data/proto/3_3/TransactionBody' -import { bodyBytesToTransactionBody, transactionBodyToBodyBytes } from '@/utils/typeConverter' -import { Transaction } from '@entity/Transaction' -import { AccountRepository } from './Account.repository' -import { UserIdentifier } from '@/graphql/input/UserIdentifier' -import { CommunityRepository } from './Community.repository' -import { LogError } from '@/server/LogError' import { Account } from '@entity/Account' import { Community } from '@entity/Community' +import { Transaction } from '@entity/Transaction' + +import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' +import { TransactionBody } from '@/data/proto/3_3/TransactionBody' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { LogError } from '@/server/LogError' +import { bodyBytesToTransactionBody, transactionBodyToBodyBytes } from '@/utils/typeConverter' + +import { AccountRepository } from './Account.repository' +import { CommunityRepository } from './Community.repository' import { TransactionBodyBuilder } from './proto/TransactionBody.builder' export class TransactionBuilder { diff --git a/dlt-connector/src/data/Transaction.repository.ts b/dlt-connector/src/data/Transaction.repository.ts index 8a1eac02e..9c21476ad 100644 --- a/dlt-connector/src/data/Transaction.repository.ts +++ b/dlt-connector/src/data/Transaction.repository.ts @@ -1,7 +1,8 @@ -import { getDataSource } from '@/typeorm/DataSource' import { Transaction } from '@entity/Transaction' import { IsNull } from 'typeorm' +import { getDataSource } from '@/typeorm/DataSource' + // https://www.artima.com/articles/the-dci-architecture-a-new-vision-of-object-oriented-programming export const TransactionRepository = getDataSource() .getRepository(Transaction) diff --git a/dlt-connector/src/data/User.factory.ts b/dlt-connector/src/data/User.factory.ts index 1844cff64..a8c7f0e71 100644 --- a/dlt-connector/src/data/User.factory.ts +++ b/dlt-connector/src/data/User.factory.ts @@ -1,10 +1,12 @@ -import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' import { User } from '@entity/User' -import { UserLogic } from './User.logic' + +import { UserAccountDraft } from '@/graphql/input/UserAccountDraft' + import { KeyPair } from './KeyPair' +import { UserLogic } from './User.logic' export class UserFactory { - static create(userAccountDraft: UserAccountDraft, parentKeys?: KeyPair): User { + static create(userAccountDraft: UserAccountDraft, parentKeys: KeyPair): User { const user = User.create() user.createdAt = new Date(userAccountDraft.createdAt) user.gradidoID = userAccountDraft.user.uuid diff --git a/dlt-connector/src/data/User.logic.ts b/dlt-connector/src/data/User.logic.ts index 58b441561..0a906682d 100644 --- a/dlt-connector/src/data/User.logic.ts +++ b/dlt-connector/src/data/User.logic.ts @@ -1,9 +1,10 @@ import { User } from '@entity/User' -import { KeyPair } from './KeyPair' + import { LogError } from '@/server/LogError' -import { uuid4ToBuffer } from '@/utils/typeConverter' import { hardenDerivationIndex } from '@/utils/derivationHelper' -import { KeyManager } from '@/manager/KeyManager' +import { uuid4ToBuffer } from '@/utils/typeConverter' + +import { KeyPair } from './KeyPair' export class UserLogic { // eslint-disable-next-line no-useless-constructor @@ -15,7 +16,7 @@ export class UserLogic { * @returns */ - calculateKeyPair = (parentKeys?: KeyPair): KeyPair => { + calculateKeyPair = (parentKeys: KeyPair): KeyPair => { if (!this.user.gradidoID) { throw new LogError('missing GradidoID for user.', { id: this.user.id }) } @@ -27,7 +28,7 @@ export class UserLogic { parts[i] = hardenDerivationIndex(wholeHex.subarray(i * 4, (i + 1) * 4).readUInt32BE()) } // parts: [2206563009, 2629978174, 2324817329, 2405141782] - const keyPair = KeyManager.getInstance().derive(parts, parentKeys) + const keyPair = parentKeys.derive(parts) if (this.user.derive1Pubkey && this.user.derive1Pubkey.compare(keyPair.publicKey) !== 0) { throw new LogError( 'The freshly derived public key does not correspond to the stored public key', diff --git a/dlt-connector/src/data/User.repository.ts b/dlt-connector/src/data/User.repository.ts index abd64ac46..6e5a66203 100644 --- a/dlt-connector/src/data/User.repository.ts +++ b/dlt-connector/src/data/User.repository.ts @@ -1,8 +1,9 @@ -import { UserIdentifier } from '@/graphql/input/UserIdentifier' -import { getDataSource } from '@/typeorm/DataSource' import { Account } from '@entity/Account' import { User } from '@entity/User' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { getDataSource } from '@/typeorm/DataSource' + export const UserRepository = getDataSource() .getRepository(User) .extend({ diff --git a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts index 442716c3b..c03460741 100644 --- a/dlt-connector/src/data/proto/3_3/CommunityRoot.ts +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -1,8 +1,8 @@ -import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' -import { Field, Message } from 'protobufjs' import { Community } from '@entity/Community' import { Transaction } from '@entity/Transaction' +import { Field, Message } from 'protobufjs' + +import { AbstractTransaction } from '../AbstractTransaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -30,11 +30,6 @@ export class CommunityRoot extends Message implements AbstractTra @Field.d(3, 'bytes') public aufPubkey: Buffer - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public validate(_level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars public fillTransactionRecipe(recipe: Transaction): void {} } diff --git a/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts index 9c6491128..d59b991e8 100644 --- a/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts +++ b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts @@ -1,7 +1,9 @@ import { Field, Message } from 'protobufjs' + +import { base64ToBuffer } from '@/utils/typeConverter' + import { GradidoTransaction } from './GradidoTransaction' import { TimestampSeconds } from './TimestampSeconds' -import { base64ToBuffer } from '@/utils/typeConverter' /* id will be set by Node server diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts index 8b3fd1b3f..06011838c 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts @@ -1,9 +1,11 @@ import 'reflect-metadata' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { GradidoCreation } from './GradidoCreation' -import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@enum/TransactionErrorType' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionError } from '@/graphql/model/TransactionError' + +import { GradidoCreation } from './GradidoCreation' + describe('proto/3.3/GradidoCreation', () => { it('test with missing targetDate', () => { const transactionDraft = new TransactionDraft() diff --git a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts index 31ac08e26..0fa08eff5 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoCreation.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -1,15 +1,16 @@ +import { Account } from '@entity/Account' +import { Transaction } from '@entity/Transaction' +import { Decimal } from 'decimal.js-light' import { Field, Message } from 'protobufjs' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionError } from '@/graphql/model/TransactionError' + +import { AbstractTransaction } from '../AbstractTransaction' + 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' -import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' -import { Transaction } from '@entity/Transaction' -import Decimal from 'decimal.js-light' -import { Account } from '@entity/Account' // need signature from group admin or // percent of group users another than the receiver @@ -36,17 +37,16 @@ export class GradidoCreation extends Message implements Abstrac } } + // recipient: TransferAmount contain + // - recipient public key + // - amount + // - communityId // only set if not the same as recipient community @Field.d(1, TransferAmount) public recipient: TransferAmount @Field.d(3, 'TimestampSeconds') public targetDate: TimestampSeconds - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public validate(level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - public fillTransactionRecipe(recipe: Transaction): void { recipe.amount = new Decimal(this.recipient.amount ?? 0) } diff --git a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index ebe407d0d..f48719b16 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -1,11 +1,11 @@ +import { Transaction } from '@entity/Transaction' +import Decimal from 'decimal.js-light' import { Field, Message } from 'protobufjs' +import { AbstractTransaction } from '../AbstractTransaction' + import { GradidoTransfer } from './GradidoTransfer' import { TimestampSeconds } from './TimestampSeconds' -import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' -import { Transaction } from '@entity/Transaction' -import Decimal from 'decimal.js-light' // transaction type for chargeable transactions // for transaction for people which haven't a account already @@ -36,11 +36,6 @@ export class GradidoDeferredTransfer // split for n recipient // max gradido per recipient? or per transaction with cool down? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public validate(level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - public fillTransactionRecipe(recipe: Transaction): void { recipe.amount = new Decimal(this.transfer.sender.amount ?? 0) } diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts b/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts index d4eea4836..4aaa3e25c 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts @@ -1,10 +1,11 @@ import { Field, Message } from 'protobufjs' -import { SignatureMap } from './SignatureMap' -import { TransactionBody } from './TransactionBody' -import { SignaturePair } from './SignaturePair' import { LogError } from '@/server/LogError' +import { SignatureMap } from './SignatureMap' +import { SignaturePair } from './SignaturePair' +import { TransactionBody } from './TransactionBody' + // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define export class GradidoTransaction extends Message { diff --git a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts index 31cb25ae9..7e9da40bd 100644 --- a/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -1,12 +1,13 @@ -import { Field, Message } from 'protobufjs' - -import { TransferAmount } from './TransferAmount' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' +import { Account } from '@entity/Account' import { Transaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' -import { Account } from '@entity/Account' +import { Field, Message } from 'protobufjs' + +import { TransactionDraft } from '@/graphql/input/TransactionDraft' + +import { AbstractTransaction } from '../AbstractTransaction' + +import { TransferAmount } from './TransferAmount' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -31,17 +32,17 @@ export class GradidoTransfer extends Message implements Abstrac } } + // sender: TransferAmount contain + // - sender public key + // - amount + // - communityId // only set if not the same as sender and recipient community @Field.d(1, TransferAmount) public sender: TransferAmount + // the recipient public key @Field.d(2, 'bytes') public recipient: Buffer - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public validate(level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - public fillTransactionRecipe(recipe: Transaction): void { recipe.amount = new Decimal(this.sender?.amount ?? 0) } diff --git a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 52d676ffe..b64e80a73 100644 --- a/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts +++ b/dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' -import { Field, Message } from 'protobufjs' import { Transaction } from '@entity/Transaction' +import { Field, Message } from 'protobufjs' + +import { AbstractTransaction } from '../AbstractTransaction' // connect group together // only CrossGroupType CROSS (in TransactionBody) @@ -17,10 +17,6 @@ export class GroupFriendsUpdate extends Message implements A @Field.d(1, 'bool') public colorFusion: boolean - public validate(level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - public fillTransactionRecipe(recipe: Transaction): void { throw new Error('Method not implemented.') } diff --git a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts index 494d077ed..87f09afbd 100644 --- a/dlt-connector/src/data/proto/3_3/RegisterAddress.ts +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -1,11 +1,11 @@ /* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/no-unused-vars */ +import { Transaction } from '@entity/Transaction' import { Field, Message } from 'protobufjs' import { AddressType } from '@/data/proto/3_3/enum/AddressType' + import { AbstractTransaction } from '../AbstractTransaction' -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' -import { Transaction } from '@entity/Transaction' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -25,9 +25,5 @@ export class RegisterAddress extends Message implements Abstrac @Field.d(5, 'uint32') public derivationIndex?: number - public validate(level: TransactionValidationLevel): boolean { - throw new Error('Method not implemented.') - } - public fillTransactionRecipe(_recipe: Transaction): void {} } diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index dceb03314..70199c03c 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -1,23 +1,24 @@ +import { Transaction } from '@entity/Transaction' import { Field, Message, OneOf } from 'protobufjs' -import { CrossGroupType } from './enum/CrossGroupType' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { LogError } from '@/server/LogError' +import { timestampToDate } from '@/utils/typeConverter' -import { Timestamp } from './Timestamp' -import { GradidoTransfer } from './GradidoTransfer' +import { AbstractTransaction } from '../AbstractTransaction' +import { determineCrossGroupType, determineOtherGroup } from '../transactionBody.logic' + +import { CommunityRoot } from './CommunityRoot' +import { PROTO_TRANSACTION_BODY_VERSION_NUMBER } from './const' +import { CrossGroupType } from './enum/CrossGroupType' +import { TransactionType } from './enum/TransactionType' import { GradidoCreation } from './GradidoCreation' import { GradidoDeferredTransfer } from './GradidoDeferredTransfer' +import { GradidoTransfer } from './GradidoTransfer' import { GroupFriendsUpdate } from './GroupFriendsUpdate' import { RegisterAddress } from './RegisterAddress' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { determineCrossGroupType, determineOtherGroup } from '../transactionBody.logic' -import { CommunityRoot } from './CommunityRoot' -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { TransactionType } from '@/graphql/enum/TransactionType' -import { AbstractTransaction } from '../AbstractTransaction' -import { Transaction } from '@entity/Transaction' -import { timestampToDate } from '@/utils/typeConverter' -import { LogError } from '@/server/LogError' -import { PROTO_TRANSACTION_BODY_VERSION_NUMBER } from './const' +import { Timestamp } from './Timestamp' // https://www.npmjs.com/package/@apollo/protobufjs // eslint-disable-next-line no-use-before-define @@ -95,6 +96,14 @@ export class TransactionBody extends Message { else if (this.communityRoot) return TransactionType.COMMUNITY_ROOT } + // The `TransactionBody` class utilizes Protobuf's `OneOf` field structure which, according to Protobuf documentation + // (https://protobuf.dev/programming-guides/proto3/#oneof), allows only one field within the group to be set at a time. + // Therefore, accessing the `getTransactionDetails()` method returns the first initialized value among the defined fields, + // each of which should be of type AbstractTransaction. It's important to note that due to the nature of Protobuf's `OneOf`, + // only one type from the defined options can be set within the object obtained from Protobuf. + // + // If multiple fields are set in a single object, the method `getTransactionDetails()` will return the first defined value + // based on the order of checks. Developers should handle this behavior according to the expected Protobuf structure. public getTransactionDetails(): AbstractTransaction | undefined { if (this.transfer) return this.transfer if (this.creation) return this.creation diff --git a/dlt-connector/src/data/proto/3_3/enum/AddressType.ts b/dlt-connector/src/data/proto/3_3/enum/AddressType.ts index 49fcf0c4e..eace1e022 100644 --- a/dlt-connector/src/data/proto/3_3/enum/AddressType.ts +++ b/dlt-connector/src/data/proto/3_3/enum/AddressType.ts @@ -1,3 +1,8 @@ +/** + * Enum for protobuf + * used from RegisterAddress to determine account type + * master implementation: https://github.com/gradido/gradido_protocol/blob/master/proto/gradido/register_address.proto + */ export enum AddressType { NONE = 0, // if no address was found COMMUNITY_HUMAN = 1, // creation account for human @@ -7,13 +12,3 @@ export enum AddressType { SUBACCOUNT = 5, // no creations allowed CRYPTO_ACCOUNT = 6, // user control his keys, no creations } - -export function getAddressTypeEnumValue(typeString: string): AddressType | undefined { - // Iterate through all enum values - for (const key in AddressType) { - if (AddressType[key] === typeString) { - return AddressType[key] as unknown as AddressType - } - } - return undefined // If the string is not found -} diff --git a/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts b/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts index 13e968509..fee592e57 100644 --- a/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts +++ b/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts @@ -1,7 +1,22 @@ +/** + * Enum for protobuf + * Determine Cross Group type of Transactions + * LOCAL: no cross group transactions, sender and recipient community are the same, only one transaction + * INBOUND: cross group transaction, Inbound part. On recipient community chain. Recipient side by Transfer Transactions + * OUTBOUND: cross group transaction, Outbound part. On sender community chain. Sender side by Transfer Transactions + * CROSS: for cross group transaction which haven't a direction like group friend update + * master implementation: https://github.com/gradido/gradido_protocol/blob/master/proto/gradido/transaction_body.proto + * + * Transaction Handling differ from database focused backend + * In Backend for each transfer transaction there are always two entries in db, + * on for sender user and one for recipient user despite storing basically the same data two times + * In Blockchain Implementation there only two transactions on cross group transactions, one for + * the sender community chain, one for the recipient community chain + * if the transaction stay in the community there is only one transaction + */ export enum CrossGroupType { LOCAL = 0, INBOUND = 1, OUTBOUND = 2, - // for cross group transaction which haven't a direction like group friend update - // CROSS = 3, + CROSS = 3, } diff --git a/dlt-connector/src/data/proto/3_3/enum/TransactionType.ts b/dlt-connector/src/data/proto/3_3/enum/TransactionType.ts new file mode 100644 index 000000000..c50f33bec --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/enum/TransactionType.ts @@ -0,0 +1,13 @@ +/** + * based on TransactionBody data oneOf + * https://github.com/gradido/gradido_protocol/blob/master/proto/gradido/transaction_body.proto + * for storing type in db as number + */ +export enum TransactionType { + GRADIDO_TRANSFER = 1, + GRADIDO_CREATION = 2, + GROUP_FRIENDS_UPDATE = 3, + REGISTER_ADDRESS = 4, + GRADIDO_DEFERRED_TRANSFER = 5, + COMMUNITY_ROOT = 6, +} diff --git a/dlt-connector/src/data/proto/AbstractTransaction.ts b/dlt-connector/src/data/proto/AbstractTransaction.ts index 82c50dcb0..ac089b096 100644 --- a/dlt-connector/src/data/proto/AbstractTransaction.ts +++ b/dlt-connector/src/data/proto/AbstractTransaction.ts @@ -1,9 +1,5 @@ -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' import { Transaction } from '@entity/Transaction' export abstract class AbstractTransaction { - // validate if transaction is valid, maybe expensive because depending on level several transactions will be fetched from db - public abstract validate(level: TransactionValidationLevel): boolean - public abstract fillTransactionRecipe(recipe: Transaction): void } diff --git a/dlt-connector/src/data/proto/TransactionBody.builder.ts b/dlt-connector/src/data/proto/TransactionBody.builder.ts index b0e0a9f79..cf9479015 100644 --- a/dlt-connector/src/data/proto/TransactionBody.builder.ts +++ b/dlt-connector/src/data/proto/TransactionBody.builder.ts @@ -1,13 +1,15 @@ -import { TransactionBody } from './3_3/TransactionBody' import { Account } from '@entity/Account' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { Community } from '@entity/Community' + import { InputTransactionType } from '@/graphql/enum/InputTransactionType' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { LogError } from '@/server/LogError' + +import { CommunityRoot } from './3_3/CommunityRoot' import { GradidoCreation } from './3_3/GradidoCreation' import { GradidoTransfer } from './3_3/GradidoTransfer' -import { Community } from '@entity/Community' -import { CommunityRoot } from './3_3/CommunityRoot' -import { LogError } from '@/server/LogError' +import { TransactionBody } from './3_3/TransactionBody' export class TransactionBodyBuilder { private signingAccount?: Account diff --git a/dlt-connector/src/data/proto/transactionBody.logic.ts b/dlt-connector/src/data/proto/transactionBody.logic.ts index 872172aac..99dbc2ed6 100644 --- a/dlt-connector/src/data/proto/transactionBody.logic.ts +++ b/dlt-connector/src/data/proto/transactionBody.logic.ts @@ -1,8 +1,9 @@ -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { CrossGroupType } from './3_3/enum/CrossGroupType' import { InputTransactionType } from '@/graphql/enum/InputTransactionType' -import { TransactionError } from '@/graphql/model/TransactionError' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionError } from '@/graphql/model/TransactionError' + +import { CrossGroupType } from './3_3/enum/CrossGroupType' export const determineCrossGroupType = ({ senderUser, @@ -50,5 +51,7 @@ export const determineOtherGroup = ( ) } return senderUser.communityUuid + case CrossGroupType.CROSS: + throw new TransactionError(TransactionErrorType.NOT_IMPLEMENTED_YET, 'not implemented yet') } } diff --git a/dlt-connector/src/graphql/enum/AccountType.ts b/dlt-connector/src/graphql/enum/AccountType.ts index a6946275b..810c89044 100644 --- a/dlt-connector/src/graphql/enum/AccountType.ts +++ b/dlt-connector/src/graphql/enum/AccountType.ts @@ -1,7 +1,12 @@ import { registerEnumType } from 'type-graphql' +/** + * enum for graphql + * describe input account type in UserAccountDraft + * should have the same entries like enum AddressType from proto/enum folder + */ export enum AccountType { - NONE = 'none', // if no address was found + NONE = 'NONE', // if no address was found COMMUNITY_HUMAN = 'COMMUNITY_HUMAN', // creation account for human COMMUNITY_GMW = 'COMMUNITY_GMW', // community public budget account COMMUNITY_AUF = 'COMMUNITY_AUF', // community compensation and environment founds account diff --git a/dlt-connector/src/graphql/enum/InputTransactionType.ts b/dlt-connector/src/graphql/enum/InputTransactionType.ts index f35a26658..41eeac6cb 100755 --- a/dlt-connector/src/graphql/enum/InputTransactionType.ts +++ b/dlt-connector/src/graphql/enum/InputTransactionType.ts @@ -1,6 +1,7 @@ -import { LogError } from '@/server/LogError' import { registerEnumType } from 'type-graphql' +// enum for graphql but with int because it is the same in backend +// for transaction type from backend export enum InputTransactionType { CREATION = 1, SEND = 2, @@ -11,14 +12,3 @@ registerEnumType(InputTransactionType, { name: 'InputTransactionType', // this one is mandatory description: 'Type of the transaction', // this one is optional }) - -// from ChatGPT -export function getTransactionTypeString(id: InputTransactionType): string { - const key = Object.keys(InputTransactionType).find( - (key) => InputTransactionType[key as keyof typeof InputTransactionType] === id, - ) - if (key === undefined) { - throw new LogError('invalid transaction type id: ' + id.toString()) - } - return key -} diff --git a/dlt-connector/src/graphql/enum/TransactionErrorType.ts b/dlt-connector/src/graphql/enum/TransactionErrorType.ts index 8238eae08..1b01bc0da 100644 --- a/dlt-connector/src/graphql/enum/TransactionErrorType.ts +++ b/dlt-connector/src/graphql/enum/TransactionErrorType.ts @@ -1,5 +1,7 @@ import { registerEnumType } from 'type-graphql' +// enum for graphql +// error groups for resolver answers export enum TransactionErrorType { NOT_IMPLEMENTED_YET = 'Not Implemented yet', MISSING_PARAMETER = 'Missing parameter', diff --git a/dlt-connector/src/graphql/enum/TransactionType.ts b/dlt-connector/src/graphql/enum/TransactionType.ts deleted file mode 100644 index 3647b9ca8..000000000 --- a/dlt-connector/src/graphql/enum/TransactionType.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { registerEnumType } from 'type-graphql' - -export enum TransactionType { - GRADIDO_TRANSFER = 1, - GRADIDO_CREATION = 2, - GROUP_FRIENDS_UPDATE = 3, - REGISTER_ADDRESS = 4, - GRADIDO_DEFERRED_TRANSFER = 5, - COMMUNITY_ROOT = 6, -} - -registerEnumType(TransactionType, { - name: 'TransactionType', // this one is mandatory - description: 'Type of the transaction', // this one is optional -}) diff --git a/dlt-connector/src/graphql/enum/TransactionValidationLevel.ts b/dlt-connector/src/graphql/enum/TransactionValidationLevel.ts deleted file mode 100644 index 9462dd8a8..000000000 --- a/dlt-connector/src/graphql/enum/TransactionValidationLevel.ts +++ /dev/null @@ -1,15 +0,0 @@ -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', -}) diff --git a/dlt-connector/src/graphql/input/CommunityDraft.ts b/dlt-connector/src/graphql/input/CommunityDraft.ts index f028ea06c..665e10b75 100644 --- a/dlt-connector/src/graphql/input/CommunityDraft.ts +++ b/dlt-connector/src/graphql/input/CommunityDraft.ts @@ -2,6 +2,7 @@ import { IsBoolean, IsUUID } from 'class-validator' import { Field, InputType } from 'type-graphql' + import { isValidDateString } from '@validator/DateString' @InputType() diff --git a/dlt-connector/src/graphql/input/TransactionDraft.ts b/dlt-connector/src/graphql/input/TransactionDraft.ts index 3cd497eec..7c43e9554 100755 --- a/dlt-connector/src/graphql/input/TransactionDraft.ts +++ b/dlt-connector/src/graphql/input/TransactionDraft.ts @@ -1,12 +1,13 @@ // https://www.npmjs.com/package/@apollo/protobufjs - +import { IsEnum, IsObject, IsPositive, ValidateNested } from 'class-validator' import { Decimal } from 'decimal.js-light' -import { InputTransactionType } from '@enum/InputTransactionType' import { InputType, Field, Int } from 'type-graphql' -import { UserIdentifier } from './UserIdentifier' + +import { InputTransactionType } from '@enum/InputTransactionType' import { isValidDateString } from '@validator/DateString' import { IsPositiveDecimal } from '@validator/Decimal' -import { IsEnum, IsObject, IsPositive, ValidateNested } from 'class-validator' + +import { UserIdentifier } from './UserIdentifier' @InputType() export class TransactionDraft { diff --git a/dlt-connector/src/graphql/input/UserAccountDraft.ts b/dlt-connector/src/graphql/input/UserAccountDraft.ts index bae9c0694..9ae544e32 100644 --- a/dlt-connector/src/graphql/input/UserAccountDraft.ts +++ b/dlt-connector/src/graphql/input/UserAccountDraft.ts @@ -1,11 +1,14 @@ // https://www.npmjs.com/package/@apollo/protobufjs -import { InputType, Field } from 'type-graphql' -import { UserIdentifier } from './UserIdentifier' -import { isValidDateString } from '@validator/DateString' import { IsEnum, IsObject, ValidateNested } from 'class-validator' +import { InputType, Field } from 'type-graphql' + +import { isValidDateString } from '@validator/DateString' + import { AccountType } from '@/graphql/enum/AccountType' +import { UserIdentifier } from './UserIdentifier' + @InputType() export class UserAccountDraft { @Field(() => UserIdentifier) diff --git a/dlt-connector/src/graphql/model/Community.ts b/dlt-connector/src/graphql/model/Community.ts index 214984f15..7a69288dc 100644 --- a/dlt-connector/src/graphql/model/Community.ts +++ b/dlt-connector/src/graphql/model/Community.ts @@ -1,5 +1,5 @@ -import { ObjectType, Field, Int } from 'type-graphql' import { Community as CommunityEntity } from '@entity/Community' +import { ObjectType, Field, Int } from 'type-graphql' @ObjectType() export class Community { diff --git a/dlt-connector/src/graphql/model/TransactionError.ts b/dlt-connector/src/graphql/model/TransactionError.ts index 891ad2a89..eee54e19c 100644 --- a/dlt-connector/src/graphql/model/TransactionError.ts +++ b/dlt-connector/src/graphql/model/TransactionError.ts @@ -1,4 +1,5 @@ import { ObjectType, Field } from 'type-graphql' + import { TransactionErrorType } from '../enum/TransactionErrorType' @ObjectType() diff --git a/dlt-connector/src/graphql/model/TransactionRecipe.ts b/dlt-connector/src/graphql/model/TransactionRecipe.ts index a4dacd9e9..263ccce4a 100644 --- a/dlt-connector/src/graphql/model/TransactionRecipe.ts +++ b/dlt-connector/src/graphql/model/TransactionRecipe.ts @@ -1,13 +1,20 @@ -import { Field, Int, ObjectType } from 'type-graphql' -import { TransactionType } from '@enum/TransactionType' import { Transaction } from '@entity/Transaction' +import { Field, Int, ObjectType } from 'type-graphql' + +import { TransactionType } from '@/data/proto/3_3/enum/TransactionType' +import { LogError } from '@/server/LogError' +import { getEnumValue } from '@/utils/typeConverter' @ObjectType() export class TransactionRecipe { public constructor({ id, createdAt, type, community }: Transaction) { + const transactionType = getEnumValue(TransactionType, type) + if (!transactionType) { + throw new LogError('invalid transaction, type is missing') + } this.id = id this.createdAt = createdAt.toString() - this.type = type + this.type = transactionType.toString() this.topic = community.iotaTopic } @@ -17,8 +24,8 @@ export class TransactionRecipe { @Field(() => String) createdAt: string - @Field(() => TransactionType) - type: TransactionType + @Field(() => String) + type: string @Field(() => String) topic: string diff --git a/dlt-connector/src/graphql/model/TransactionResult.ts b/dlt-connector/src/graphql/model/TransactionResult.ts index bc443ad1f..370c9827d 100644 --- a/dlt-connector/src/graphql/model/TransactionResult.ts +++ b/dlt-connector/src/graphql/model/TransactionResult.ts @@ -1,4 +1,5 @@ import { ObjectType, Field } from 'type-graphql' + import { TransactionError } from './TransactionError' import { TransactionRecipe } from './TransactionRecipe' diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts index 2c402c537..0fa61cc48 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts @@ -1,10 +1,14 @@ import 'reflect-metadata' -import { ApolloServer } from '@apollo/server' -// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories -import { TestDB } from '@test/TestDB' -import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' + +import { ApolloServer } from '@apollo/server' + +// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories +// eslint-disable-next-line import/order +import { TestDB } from '@test/TestDB' import { TransactionResult } from '@model/TransactionResult' +import { createApolloTestServer } from '@test/ApolloServerMock' + import { CONFIG } from '@/config' CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.ts index 9b6d8f3f2..d4bbeb28e 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.ts @@ -1,17 +1,17 @@ import { Resolver, Query, Arg, Mutation, Args } from 'type-graphql' -import { CommunityDraft } from '@input/CommunityDraft' - -import { TransactionResult } from '@model/TransactionResult' -import { TransactionError } from '@model/TransactionError' -import { TransactionErrorType } from '@enum/TransactionErrorType' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' -import { Community } from '@model/Community' import { CommunityArg } from '@arg/CommunityArg' -import { LogError } from '@/server/LogError' -import { logger } from '@/server/logger' +import { TransactionErrorType } from '@enum/TransactionErrorType' +import { CommunityDraft } from '@input/CommunityDraft' +import { Community } from '@model/Community' +import { TransactionError } from '@model/TransactionError' +import { TransactionResult } from '@model/TransactionResult' + import { CommunityRepository } from '@/data/Community.repository' import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' +import { LogError } from '@/server/LogError' +import { logger } from '@/server/logger' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' @Resolver() export class CommunityResolver { diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index 71044805c..b5d5ee126 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -1,22 +1,28 @@ import 'reflect-metadata' -import { ApolloServer } from '@apollo/server' -// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories -import { TestDB } from '@test/TestDB' -import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' -import { TransactionResult } from '@model/TransactionResult' -import { AccountFactory } from '@/data/Account.factory' -import { CONFIG } from '@/config' -import { UserFactory } from '@/data/User.factory' -import { UserAccountDraft } from '../input/UserAccountDraft' -import { UserLogic } from '@/data/User.logic' -import { AccountType } from '@enum/AccountType' -import { UserIdentifier } from '../input/UserIdentifier' -import { CommunityDraft } from '../input/CommunityDraft' -import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' -import { InputTransactionType, getTransactionTypeString } from '../enum/InputTransactionType' -CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' +import { ApolloServer } from '@apollo/server' + +// must be imported before createApolloTestServer so that TestDB was created before createApolloTestServer imports repositories +// eslint-disable-next-line import/order +import { TestDB } from '@test/TestDB' +import { AccountType } from '@enum/AccountType' +import { TransactionResult } from '@model/TransactionResult' +import { createApolloTestServer } from '@test/ApolloServerMock' + +import { CONFIG } from '@/config' +import { AccountFactory } from '@/data/Account.factory' +import { KeyPair } from '@/data/KeyPair' +import { Mnemonic } from '@/data/Mnemonic' +import { UserFactory } from '@/data/User.factory' +import { UserLogic } from '@/data/User.logic' +import { AddCommunityContext } from '@/interactions/backendToDb/community/AddCommunity.context' +import { getEnumValue } from '@/utils/typeConverter' + +import { InputTransactionType } from '../enum/InputTransactionType' +import { CommunityDraft } from '../input/CommunityDraft' +import { UserAccountDraft } from '../input/UserAccountDraft' +import { UserIdentifier } from '../input/UserIdentifier' let apolloTestServer: ApolloServer @@ -32,7 +38,9 @@ jest.mock('@typeorm/DataSource', () => ({ getDataSource: jest.fn(() => TestDB.instance.dbConnect), })) +CONFIG.IOTA_HOME_COMMUNITY_SEED = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899' const communityUUID = '3d813cbb-37fb-42ba-91df-831e1593ac29' +const communityKeyPair = new KeyPair(new Mnemonic(CONFIG.IOTA_HOME_COMMUNITY_SEED)) const createUserStoreAccount = async (uuid: string): Promise => { const userAccountDraft = new UserAccountDraft() @@ -41,11 +49,11 @@ const createUserStoreAccount = async (uuid: string): Promise => userAccountDraft.user = new UserIdentifier() userAccountDraft.user.uuid = uuid userAccountDraft.user.communityUuid = communityUUID - const user = UserFactory.create(userAccountDraft) + const user = UserFactory.create(userAccountDraft, communityKeyPair) const userLogic = new UserLogic(user) const account = AccountFactory.createAccountFromUserAccountDraft( userAccountDraft, - userLogic.calculateKeyPair(), + userLogic.calculateKeyPair(communityKeyPair), ) account.user = user // user is set to cascade: ['insert'] will be saved together with account @@ -82,7 +90,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: getTransactionTypeString(InputTransactionType.SEND), + type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -130,7 +138,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: getTransactionTypeString(InputTransactionType.SEND), + type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: 'no number', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, @@ -156,7 +164,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: getTransactionTypeString(InputTransactionType.SEND), + type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: '10', createdAt: 'not valid', backendTransactionId: 1, @@ -192,7 +200,7 @@ describe('Transaction Resolver Test', () => { input: { senderUser, recipientUser, - type: getTransactionTypeString(InputTransactionType.CREATION), + type: getEnumValue(InputTransactionType, InputTransactionType.CREATION), amount: '10', createdAt: '2012-04-17T17:12:00Z', backendTransactionId: 1, diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts index eb1cb769b..4f3f3efe2 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -1,11 +1,14 @@ import { Resolver, Arg, Mutation } from 'type-graphql' + import { TransactionDraft } from '@input/TransactionDraft' -import { TransactionResult } from '../model/TransactionResult' -import { TransactionError } from '../model/TransactionError' -import { CreateTransactionRecipeContext } from '@/interactions/backendToDb/transaction/CreateTransationRecipe.context' -import { TransactionRecipe } from '../model/TransactionRecipe' + import { TransactionRepository } from '@/data/Transaction.repository' +import { CreateTransactionRecipeContext } from '@/interactions/backendToDb/transaction/CreateTransationRecipe.context' + import { TransactionErrorType } from '../enum/TransactionErrorType' +import { TransactionError } from '../model/TransactionError' +import { TransactionRecipe } from '../model/TransactionRecipe' +import { TransactionResult } from '../model/TransactionResult' @Resolver() export class TransactionResolver { diff --git a/dlt-connector/src/graphql/schema.ts b/dlt-connector/src/graphql/schema.ts index ac3119d1a..19a6d5566 100755 --- a/dlt-connector/src/graphql/schema.ts +++ b/dlt-connector/src/graphql/schema.ts @@ -2,9 +2,9 @@ import { Decimal } from 'decimal.js-light' import { GraphQLSchema } from 'graphql' import { buildSchema } from 'type-graphql' -import { DecimalScalar } from './scalar/Decimal' -import { TransactionResolver } from './resolver/TransactionsResolver' import { CommunityResolver } from './resolver/CommunityResolver' +import { TransactionResolver } from './resolver/TransactionsResolver' +import { DecimalScalar } from './scalar/Decimal' export const schema = async (): Promise => { return buildSchema({ diff --git a/dlt-connector/src/index.ts b/dlt-connector/src/index.ts index 7e1ea1adc..c72978b35 100644 --- a/dlt-connector/src/index.ts +++ b/dlt-connector/src/index.ts @@ -1,14 +1,13 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { CONFIG } from '@/config' + import createServer from './server/createServer' -import { KeyManager } from './manager/KeyManager' async function main() { // eslint-disable-next-line no-console console.log(`DLT_CONNECTOR_PORT=${CONFIG.DLT_CONNECTOR_PORT}`) const { app } = await createServer() - await KeyManager.getInstance().init() app.listen(CONFIG.DLT_CONNECTOR_PORT, () => { // eslint-disable-next-line no-console console.log(`Server is running at http://localhost:${CONFIG.DLT_CONNECTOR_PORT}`) diff --git a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts index ff46de4d3..bc8f90c32 100644 --- a/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -1,8 +1,9 @@ import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' + +import { CommunityRole } from './Community.role' import { ForeignCommunityRole } from './ForeignCommunity.role' import { HomeCommunityRole } from './HomeCommunity.role' -import { iotaTopicFromCommunityUUID } from '@/utils/typeConverter' -import { CommunityRole } from './Community.role' /** * @DCI-Context diff --git a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts index f08dc25a0..30d91bfed 100644 --- a/dlt-connector/src/interactions/backendToDb/community/Community.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts @@ -1,8 +1,9 @@ +import { Community } from '@entity/Community' + import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { TransactionError } from '@/graphql/model/TransactionError' import { logger } from '@/server/logger' -import { Community } from '@entity/Community' export abstract class CommunityRole { protected self: Community diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index 57155d8ff..0b134b97c 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -1,27 +1,28 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { Community } from '@entity/Community' -import { CommunityRole } from './Community.role' import { Transaction } from '@entity/Transaction' -import { KeyManager } from '@/manager/KeyManager' + +import { CONFIG } from '@/config' import { AccountFactory } from '@/data/Account.factory' -import { CreateTransactionRecipeContext } from '../transaction/CreateTransationRecipe.context' -import { logger } from '@/server/logger' -import { TransactionError } from '@/graphql/model/TransactionError' +import { KeyPair } from '@/data/KeyPair' +import { Mnemonic } from '@/data/Mnemonic' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionError } from '@/graphql/model/TransactionError' +import { logger } from '@/server/logger' import { getDataSource } from '@/typeorm/DataSource' +import { CreateTransactionRecipeContext } from '../transaction/CreateTransationRecipe.context' + +import { CommunityRole } from './Community.role' + export class HomeCommunityRole extends CommunityRole { private transactionRecipe: Transaction public async create(communityDraft: CommunityDraft, topic: string): Promise { super.create(communityDraft, topic) // generate key pair for signing transactions and deriving all keys for community - const keyPair = KeyManager.generateKeyPair() - this.self.rootPubkey = keyPair.publicKey - this.self.rootPrivkey = keyPair.privateKey - this.self.rootChaincode = keyPair.chainCode - // we should only have one home community per server - KeyManager.getInstance().setHomeCommunityKeyPair(keyPair) + const keyPair = new KeyPair(new Mnemonic(CONFIG.IOTA_HOME_COMMUNITY_SEED ?? undefined)) + keyPair.fillInCommunityKeys(this.self) // create auf account and gmw account this.self.aufAccount = AccountFactory.createAufAccount(keyPair, this.self.createdAt) diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts index 240c86dc4..75b885f2f 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts @@ -1,9 +1,10 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' -import { TransactionRecipeRole } from './TransactionRecipe.role' import { Community } from '@entity/Community' -import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' + import { KeyPair } from '@/data/KeyPair' -import { sign } from '@/utils/cryptoHelper' +import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' + +import { TransactionRecipeRole } from './TransactionRecipe.role' export class CommunityRootTransactionRole extends TransactionRecipeRole { public createFromCommunityRoot( @@ -18,7 +19,7 @@ export class CommunityRootTransactionRole extends TransactionRecipeRole { this.transactionBuilder.fromTransactionBody(transactionBody).setCommunity(community) const transaction = this.transactionBuilder.getTransaction() // sign - this.transactionBuilder.setSignature(sign(transaction.bodyBytes, new KeyPair(community))) + this.transactionBuilder.setSignature(new KeyPair(community).sign(transaction.bodyBytes)) return this } } diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts index a5da13dcd..078ec8e5c 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -1,11 +1,13 @@ -import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { Community } from '@entity/Community' -import { TransactionRecipeRole } from './TransactionRecipe.role' -import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { Transaction } from '@entity/Transaction' -import { TransactionError } from '@/graphql/model/TransactionError' + import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { TransactionError } from '@/graphql/model/TransactionError' + +import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' +import { TransactionRecipeRole } from './TransactionRecipe.role' /** * @DCI-Context diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 6b59e5eaa..362d114ef 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -1,12 +1,12 @@ +import { Transaction } from '@entity/Transaction' + import { KeyPair } from '@/data/KeyPair' +import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' import { TransactionBuilder } from '@/data/Transaction.builder' import { UserRepository } from '@/data/User.repository' -import { TransactionBodyBuilder } from '@/data/proto/TransactionBody.builder' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' -import { sign } from '@/utils/cryptoHelper' -import { Transaction } from '@entity/Transaction' export class TransactionRecipeRole { protected transactionBuilder: TransactionBuilder @@ -52,7 +52,7 @@ export class TransactionRecipeRole { const transaction = this.transactionBuilder.getTransaction() // sign this.transactionBuilder.setSignature( - sign(transaction.bodyBytes, new KeyPair(this.transactionBuilder.getCommunity())), + new KeyPair(this.transactionBuilder.getCommunity()).sign(transaction.bodyBytes), ) return this } diff --git a/dlt-connector/src/manager/KeyManager.test.ts b/dlt-connector/src/manager/KeyManager.test.ts deleted file mode 100644 index 7f3d26932..000000000 --- a/dlt-connector/src/manager/KeyManager.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* eslint-disable camelcase */ -import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' -import { generateFromSeed, toPublic } from 'bip32-ed25519' - -describe('controller/KeyManager', () => { - describe('test crypto lib', () => { - it('key length', () => { - const mnemonic = entropyToMnemonic( - 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899', - ) - expect(mnemonic).toEqual( - 'primary taxi danger target useless ancient match hammer fever crisp timber crew produce toy jeans that abandon math mimic master filter design carbon carbon', - ) - const seed = mnemonicToSeedSync(mnemonic) - // private key 64 Bytes + 32 Byte ChainCode - const extendPrivkey = generateFromSeed(seed) - expect(extendPrivkey).toHaveLength(96) - // public key 32 Bytes + 32 Bytes ChainCode - expect(toPublic(extendPrivkey)).toHaveLength(64) - }) - }) -}) diff --git a/dlt-connector/src/manager/KeyManager.ts b/dlt-connector/src/manager/KeyManager.ts deleted file mode 100644 index 2e8b615aa..000000000 --- a/dlt-connector/src/manager/KeyManager.ts +++ /dev/null @@ -1,118 +0,0 @@ -// eslint-disable-next-line camelcase -import { randombytes_buf } from 'sodium-native' -import { CONFIG } from '../config' -import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' -// https://www.npmjs.com/package/bip32-ed25519?activeTab=code -import { generateFromSeed, derivePrivate, sign as ed25519Sign } from 'bip32-ed25519' -import { logger } from '@/server/logger' -import { LogError } from '@/server/LogError' -import { KeyPair } from '@/data/KeyPair' -import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' -import { CommunityRepository } from '@/data/Community.repository' -import { SignaturePair } from '@/data/proto/3_3/SignaturePair' - -// Source: https://refactoring.guru/design-patterns/singleton/typescript/example -// and ../federation/client/FederationClientFactory.ts -/** - * A Singleton class defines the `getInstance` method that lets clients access - * the unique singleton instance. - */ -// eslint-disable-next-line @typescript-eslint/no-extraneous-class -export class KeyManager { - // eslint-disable-next-line no-use-before-define - private static instance: KeyManager - private homeCommunityRootKeys: KeyPair | null = null - - /** - * The Singleton's constructor should always be private to prevent direct - * construction calls with the `new` operator. - */ - // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function - private constructor() {} - - /** - * The static method that controls the access to the singleton instance. - * - * This implementation let you subclass the Singleton class while keeping - * just one instance of each subclass around. - */ - public static getInstance(): KeyManager { - if (!KeyManager.instance) { - KeyManager.instance = new KeyManager() - } - return KeyManager.instance - } - - public async init(): Promise { - try { - this.homeCommunityRootKeys = await CommunityRepository.loadHomeCommunityKeyPair() - return true - } catch (error) { - logger.error('error by init key manager', error) - return false - } - } - - public static generateKeyPair(): KeyPair { - const mnemonic = KeyManager.generateMnemonic(CONFIG.IOTA_HOME_COMMUNITY_SEED ?? undefined) - // logger.info('passphrase for key pair: ' + mnemonic) - const seed = mnemonicToSeedSync(mnemonic) - return new KeyPair(generateFromSeed(seed)) - } - - public setHomeCommunityKeyPair(keyPair: KeyPair) { - this.homeCommunityRootKeys = keyPair - } - - public sign(transaction: GradidoTransaction, keys?: KeyPair[]) { - let localKeys: KeyPair[] = [] - - if (!keys && this.homeCommunityRootKeys) { - localKeys.push(this.homeCommunityRootKeys) - } else if (keys) { - localKeys = keys - } - if (!localKeys.length) { - throw new LogError('no key pair for signing') - } - localKeys.forEach((keyPair: KeyPair) => { - const signature = ed25519Sign(transaction.bodyBytes, keyPair.getExtendPrivateKey()) - const sigPair = new SignaturePair({ pubKey: keyPair.publicKey, signature }) - logger.debug('sign transaction', { - signature: signature.toString('hex'), - publicKey: keyPair.publicKey.toString('hex'), - bodyBytes: transaction.bodyBytes.toString('hex'), - }) - transaction.sigMap.sigPair.push(sigPair) - }) - } - - public getHomeCommunityPublicKey(): Buffer | undefined { - if (!this.homeCommunityRootKeys) return undefined - return this.homeCommunityRootKeys.publicKey - } - - public derive(path: number[], parentKeys?: KeyPair): KeyPair { - const extendedPrivateKey = parentKeys - ? parentKeys.getExtendPrivateKey() - : this.homeCommunityRootKeys?.getExtendPrivateKey() - if (!extendedPrivateKey) { - throw new LogError('missing parent or root key pair') - } - return new KeyPair( - path.reduce( - (extendPrivateKey: Buffer, node: number) => derivePrivate(extendPrivateKey, node), - extendedPrivateKey, - ), - ) - } - - static generateMnemonic(seed?: Buffer | string): string { - if (seed) { - return entropyToMnemonic(seed) - } - const entropy = Buffer.alloc(256) - randombytes_buf(entropy) - return entropyToMnemonic(entropy) - } -} diff --git a/dlt-connector/src/server/createServer.ts b/dlt-connector/src/server/createServer.ts index f3a3b1de7..e02cc3073 100755 --- a/dlt-connector/src/server/createServer.ts +++ b/dlt-connector/src/server/createServer.ts @@ -2,16 +2,16 @@ import 'reflect-metadata' import { ApolloServer } from '@apollo/server' import { expressMiddleware } from '@apollo/server/express4' +import bodyParser from 'body-parser' +import cors from 'cors' import express, { Express } from 'express' - // graphql +import { Logger } from 'log4js' + import { schema } from '@/graphql/schema' +import { Connection } from '@/typeorm/DataSource' import { logger as dltLogger } from './logger' -import { Logger } from 'log4js' -import cors from 'cors' -import bodyParser from 'body-parser' -import { Connection } from '@/typeorm/DataSource' type ServerDef = { apollo: ApolloServer; app: Express } diff --git a/dlt-connector/src/server/logger.ts b/dlt-connector/src/server/logger.ts index 89757f656..bec2ec578 100644 --- a/dlt-connector/src/server/logger.ts +++ b/dlt-connector/src/server/logger.ts @@ -1,7 +1,9 @@ +import { readFileSync } from 'fs' + import log4js from 'log4js' + import { CONFIG } from '@/config' -import { readFileSync } from 'fs' const options = JSON.parse(readFileSync(CONFIG.LOG4JS_CONFIG, 'utf-8')) log4js.configure(options) diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index 441cf7eef..18be65300 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -2,11 +2,11 @@ // We cannot use our connection here, but must use the external typeorm installation import { DataSource as DBDataSource, FileLogger } from '@dbTools/typeorm' import { entities } from '@entity/index' +import { Migration } from '@entity/Migration' import { CONFIG } from '@/config' -import { logger } from '@/server/logger' -import { Migration } from '@entity/Migration' import { LogError } from '@/server/LogError' +import { logger } from '@/server/logger' // eslint-disable-next-line @typescript-eslint/no-extraneous-class export class Connection { diff --git a/dlt-connector/src/utils/cryptoHelper.ts b/dlt-connector/src/utils/cryptoHelper.ts deleted file mode 100644 index 467a85e85..000000000 --- a/dlt-connector/src/utils/cryptoHelper.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { KeyPair } from '@/data/KeyPair' -import { sign as ed25519Sign, generateFromSeed } from 'bip32-ed25519' -import { entropyToMnemonic, mnemonicToSeedSync } from 'bip39' -// eslint-disable-next-line camelcase -import { randombytes_buf } from 'sodium-native' - -export const sign = (message: Buffer, keyPair: KeyPair): Buffer => { - return ed25519Sign(message, keyPair.getExtendPrivateKey()) -} - -export const generateKeyPair = (mnemonic: string): KeyPair => { - const seedFromMnemonic = mnemonicToSeedSync(mnemonic) - return new KeyPair(generateFromSeed(seedFromMnemonic)) -} - -export const generateMnemonic = (seed?: Buffer | string): string => { - if (seed) { - return entropyToMnemonic(seed) - } - const entropy = Buffer.alloc(256) - randombytes_buf(entropy) - return entropyToMnemonic(entropy) -} diff --git a/dlt-connector/src/utils/derivationHelper.test.ts b/dlt-connector/src/utils/derivationHelper.test.ts index 0ad381aa8..f14b99cdf 100644 --- a/dlt-connector/src/utils/derivationHelper.test.ts +++ b/dlt-connector/src/utils/derivationHelper.test.ts @@ -1,5 +1,6 @@ import 'reflect-metadata' import { Timestamp } from '../data/proto/3_3/Timestamp' + import { hardenDerivationIndex, HARDENED_KEY_BITMASK } from './derivationHelper' import { timestampToDate } from './typeConverter' diff --git a/dlt-connector/src/utils/typeConverter.test.ts b/dlt-connector/src/utils/typeConverter.test.ts index 03863d0f2..d9b1c2356 100644 --- a/dlt-connector/src/utils/typeConverter.test.ts +++ b/dlt-connector/src/utils/typeConverter.test.ts @@ -1,5 +1,6 @@ import 'reflect-metadata' import { Timestamp } from '@/data/proto/3_3/Timestamp' + import { timestampToDate } from './typeConverter' describe('utils/typeConverter', () => { diff --git a/dlt-connector/src/utils/typeConverter.ts b/dlt-connector/src/utils/typeConverter.ts index ecf090c45..1fc46ee4b 100644 --- a/dlt-connector/src/utils/typeConverter.ts +++ b/dlt-connector/src/utils/typeConverter.ts @@ -1,14 +1,14 @@ import { crypto_generichash as cryptoHash } from 'sodium-native' +import { AddressType } from '@/data/proto/3_3/enum/AddressType' import { Timestamp } from '@/data/proto/3_3/Timestamp' import { TimestampSeconds } from '@/data/proto/3_3/TimestampSeconds' import { TransactionBody } from '@/data/proto/3_3/TransactionBody' -import { logger } from '@/server/logger' -import { TransactionError } from '@/graphql/model/TransactionError' -import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { AccountType } from '@/graphql/enum/AccountType' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionError } from '@/graphql/model/TransactionError' import { LogError } from '@/server/LogError' -import { AddressType } from '@/data/proto/3_3/enum/AddressType' +import { logger } from '@/server/logger' export const uuid4ToBuffer = (uuid: string): Buffer => { // Remove dashes from the UUIDv4 string @@ -64,44 +64,44 @@ export const transactionBodyToBodyBytes = (transactionBody: TransactionBody): Bu } } -export const accountTypeToAddressType = (accountType: AccountType): AddressType => { - switch (accountType) { - case AccountType.NONE: - return AddressType.NONE - case AccountType.COMMUNITY_HUMAN: - return AddressType.COMMUNITY_HUMAN - case AccountType.COMMUNITY_GMW: - return AddressType.COMMUNITY_GMW - case AccountType.COMMUNITY_AUF: - return AddressType.COMMUNITY_AUF - case AccountType.COMMUNITY_PROJECT: - return AddressType.COMMUNITY_PROJECT - case AccountType.SUBACCOUNT: - return AddressType.SUBACCOUNT - case AccountType.CRYPTO_ACCOUNT: - return AddressType.CRYPTO_ACCOUNT - default: - throw new LogError(`Unsupported AccountType: ${accountType}`) +export function getEnumValue>( + enumType: T, + value: number | string, +): T[keyof T] | undefined { + if (typeof value === 'number' && typeof enumType === 'object') { + return enumType[value as keyof T] as T[keyof T] + } else if (typeof value === 'string') { + for (const key in enumType) { + if (enumType[key as keyof T] === value) { + return enumType[key as keyof T] as T[keyof T] + } + } } + return undefined } -export const addressTypeToAccountType = (addressType: AddressType): AccountType => { - switch (addressType) { - case AddressType.NONE: - return AccountType.NONE - case AddressType.COMMUNITY_HUMAN: - return AccountType.COMMUNITY_HUMAN - case AddressType.COMMUNITY_GMW: - return AccountType.COMMUNITY_GMW - case AddressType.COMMUNITY_AUF: - return AccountType.COMMUNITY_AUF - case AddressType.COMMUNITY_PROJECT: - return AccountType.COMMUNITY_PROJECT - case AddressType.SUBACCOUNT: - return AccountType.SUBACCOUNT - case AddressType.CRYPTO_ACCOUNT: - return AccountType.CRYPTO_ACCOUNT - default: - throw new LogError(`Unsupported AddressType: ${addressType}`) +export const accountTypeToAddressType = (type: AccountType): AddressType => { + const typeString: string = AccountType[type] + const addressType: AddressType = AddressType[typeString as keyof typeof AddressType] + + if (!addressType) { + throw new LogError("couldn't find corresponding AddressType for AccountType", { + accountType: type, + addressTypes: Object.keys(AddressType), + }) } + return addressType +} + +export const addressTypeToAccountType = (type: AddressType): AccountType => { + const typeString: string = AddressType[type] + const accountType: AccountType = AccountType[typeString as keyof typeof AccountType] + + if (!accountType) { + throw new LogError("couldn't find corresponding AccountType for AddressType", { + addressTypes: type, + accountType: Object.keys(AccountType), + }) + } + return accountType } diff --git a/dlt-connector/test/ApolloServerMock.ts b/dlt-connector/test/ApolloServerMock.ts index 6e0585862..c13df2407 100644 --- a/dlt-connector/test/ApolloServerMock.ts +++ b/dlt-connector/test/ApolloServerMock.ts @@ -1,5 +1,6 @@ import { ApolloServer } from '@apollo/server' import { addMocksToSchema } from '@graphql-tools/mock' + import { schema } from '@/graphql/schema' let apolloTestServer: ApolloServer diff --git a/dlt-connector/test/TestDB.ts b/dlt-connector/test/TestDB.ts index 75f362c65..63ce78500 100644 --- a/dlt-connector/test/TestDB.ts +++ b/dlt-connector/test/TestDB.ts @@ -1,7 +1,6 @@ import { DataSource, FileLogger } from '@dbTools/typeorm' -import { createDatabase } from 'typeorm-extension' - import { entities } from '@entity/index' +import { createDatabase } from 'typeorm-extension' import { CONFIG } from '@/config' import { LogError } from '@/server/LogError' From ca6d68834478a6637dd603fffe33bd8de0360190 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 19 Dec 2023 16:30:04 +0100 Subject: [PATCH 28/47] add comments to explain local imports --- dlt-database/entity/0001-init_db/Account.ts | 2 ++ dlt-database/entity/0001-init_db/Community.ts | 1 + dlt-database/entity/0001-init_db/ConfirmedTransaction.ts | 2 ++ dlt-database/entity/0001-init_db/TransactionRecipe.ts | 3 +++ 4 files changed, 8 insertions(+) diff --git a/dlt-database/entity/0001-init_db/Account.ts b/dlt-database/entity/0001-init_db/Account.ts index 4a7801c0e..7ceaf09cc 100644 --- a/dlt-database/entity/0001-init_db/Account.ts +++ b/dlt-database/entity/0001-init_db/Account.ts @@ -8,7 +8,9 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from './TransactionRecipe' +// ConfirmedTransaction was removed in newer migrations, so only the version from this folder can be linked import { ConfirmedTransaction } from './ConfirmedTransaction' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Decimal } from 'decimal.js-light' diff --git a/dlt-database/entity/0001-init_db/Community.ts b/dlt-database/entity/0001-init_db/Community.ts index 52f8c1155..943914878 100644 --- a/dlt-database/entity/0001-init_db/Community.ts +++ b/dlt-database/entity/0001-init_db/Community.ts @@ -8,6 +8,7 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from './TransactionRecipe' import { AccountCommunity } from '../AccountCommunity' diff --git a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts index b195e17c2..408a58a69 100644 --- a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts +++ b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts @@ -10,7 +10,9 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +// the relation in future account don't match which this any longer, so we can only link with the local account here import { Account } from './Account' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from './TransactionRecipe' @Entity('confirmed_transactions') diff --git a/dlt-database/entity/0001-init_db/TransactionRecipe.ts b/dlt-database/entity/0001-init_db/TransactionRecipe.ts index 1222cfbdd..b2acbba75 100644 --- a/dlt-database/entity/0001-init_db/TransactionRecipe.ts +++ b/dlt-database/entity/0001-init_db/TransactionRecipe.ts @@ -10,8 +10,11 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +// the relation in future account don't match which this any longer, so we can only link with the local account here import { Account } from './Account' +// the relation in future community don't match which this any longer, so we can only link with the local account here import { Community } from './Community' +// ConfirmedTransaction was removed in newer migrations, so only the version from this folder can be linked import { ConfirmedTransaction } from './ConfirmedTransaction' @Entity('transaction_recipes') From 712e6f61cb61c604fbe8df8ff5931e0310ecd6a7 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 19 Dec 2023 19:42:12 +0100 Subject: [PATCH 29/47] more comments for removed tables --- dlt-database/entity/0002-refactor_add_community/Account.ts | 2 ++ dlt-database/entity/0002-refactor_add_community/Community.ts | 1 + .../entity/0002-refactor_add_community/ConfirmedTransaction.ts | 1 + 3 files changed, 4 insertions(+) diff --git a/dlt-database/entity/0002-refactor_add_community/Account.ts b/dlt-database/entity/0002-refactor_add_community/Account.ts index 644b1b9a8..821b75e73 100644 --- a/dlt-database/entity/0002-refactor_add_community/Account.ts +++ b/dlt-database/entity/0002-refactor_add_community/Account.ts @@ -8,7 +8,9 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' +// ConfirmedTransaction was removed in newer migrations, so only the version from this folder can be linked import { ConfirmedTransaction } from './ConfirmedTransaction' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Decimal } from 'decimal.js-light' diff --git a/dlt-database/entity/0002-refactor_add_community/Community.ts b/dlt-database/entity/0002-refactor_add_community/Community.ts index 2961d5af3..7136efa2e 100644 --- a/dlt-database/entity/0002-refactor_add_community/Community.ts +++ b/dlt-database/entity/0002-refactor_add_community/Community.ts @@ -8,6 +8,7 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' import { AccountCommunity } from '../AccountCommunity' diff --git a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts index 33ab13b52..e973f9571 100644 --- a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts +++ b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts @@ -11,6 +11,7 @@ import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Account } from './Account' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' @Entity('confirmed_transactions') From 5c11f2e85d263ced1fa8906e3d5ca8e56e6c7857 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Tue, 19 Dec 2023 19:57:27 +0100 Subject: [PATCH 30/47] update name for balances --- dlt-connector/src/data/Account.factory.ts | 6 ++--- dlt-connector/src/data/Account.test.ts | 24 +++++++++---------- .../Account.ts | 16 ++++++------- .../Transaction.ts | 8 +++---- .../0003-refactor_transaction_recipe.ts | 20 ++++++++-------- 5 files changed, 37 insertions(+), 37 deletions(-) diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts index e318cb104..a8c1f162d 100644 --- a/dlt-connector/src/data/Account.factory.ts +++ b/dlt-connector/src/data/Account.factory.ts @@ -22,9 +22,9 @@ export class AccountFactory { account.derive2Pubkey = parentKeyPair.derive([derivationIndex]).publicKey account.type = type.valueOf() account.createdAt = createdAt - account.balanceConfirmedAt = new Decimal(0) - account.balanceCreatedAt = new Decimal(0) - account.balanceCreatedAtDate = createdAt + account.balanceOnConfirmation = new Decimal(0) + account.balanceOnCreation = new Decimal(0) + account.balanceCreatedAt = createdAt return account } diff --git a/dlt-connector/src/data/Account.test.ts b/dlt-connector/src/data/Account.test.ts index 596b51dc2..f28065cce 100644 --- a/dlt-connector/src/data/Account.test.ts +++ b/dlt-connector/src/data/Account.test.ts @@ -46,9 +46,9 @@ describe('data/Account test factory and repository', () => { ), type: AddressType.COMMUNITY_HUMAN, createdAt: now, - balanceCreatedAtDate: now, - balanceConfirmedAt: new Decimal(0), - balanceCreatedAt: new Decimal(0), + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), }) }) @@ -67,9 +67,9 @@ describe('data/Account test factory and repository', () => { ), type: AddressType.COMMUNITY_HUMAN, createdAt: now, - balanceCreatedAtDate: now, - balanceConfirmedAt: new Decimal(0), - balanceCreatedAt: new Decimal(0), + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), }) }) @@ -83,9 +83,9 @@ describe('data/Account test factory and repository', () => { ), type: AddressType.COMMUNITY_GMW, createdAt: now, - balanceCreatedAtDate: now, - balanceConfirmedAt: new Decimal(0), - balanceCreatedAt: new Decimal(0), + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), }) }) @@ -99,9 +99,9 @@ describe('data/Account test factory and repository', () => { ), type: AddressType.COMMUNITY_AUF, createdAt: now, - balanceCreatedAtDate: now, - balanceConfirmedAt: new Decimal(0), - balanceCreatedAt: new Decimal(0), + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), }) }) }) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts index b8beea8ff..1c01094f1 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -43,39 +43,39 @@ export class Account extends BaseEntity { confirmedAt?: Date @Column({ - name: 'balance_confirmed_at', + name: 'balance_on_confirmation', type: 'decimal', precision: 40, scale: 20, default: 0, transformer: DecimalTransformer, }) - balanceConfirmedAt: Decimal + balanceOnConfirmation: Decimal // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ - name: 'balance_confirmed_at_date', + name: 'balance_confirmed_at', type: 'datetime', nullable: true, }) - balanceConfirmedAtDate: Date + balanceConfirmedAt: Date @Column({ - name: 'balance_created_at', + name: 'balance_on_creation', type: 'decimal', precision: 40, scale: 20, default: 0, transformer: DecimalTransformer, }) - balanceCreatedAt: Decimal + balanceOnCreation: Decimal @Column({ - name: 'balance_created_at_date', + name: 'balance_created_at', type: 'datetime', precision: 3, }) - balanceCreatedAtDate: Date + balanceCreatedAt: Date @OneToMany(() => AccountCommunity, (accountCommunity) => accountCommunity.account) @JoinColumn({ name: 'account_id' }) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index 06c06927b..3c4e7959c 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -73,14 +73,14 @@ export class Transaction extends BaseEntity { // account balance for sender based on creation date @Column({ - name: 'account_balance_created_at', + name: 'account_balance_on_creation', type: 'decimal', precision: 40, scale: 20, nullable: true, transformer: DecimalTransformer, }) - accountBalanceCreatedAt?: Decimal + accountBalanceOnCreation?: Decimal @Column({ type: 'tinyint' }) type: number @@ -105,14 +105,14 @@ export class Transaction extends BaseEntity { // account balance for sender based on confirmation date (iota milestone) @Column({ - name: 'account_balance_confirmed_at', + name: 'account_balance_on_confirmation', type: 'decimal', precision: 40, scale: 20, nullable: true, transformer: DecimalTransformer, }) - accountBalanceConfirmedAt?: Decimal + accountBalanceOnConfirmation?: Decimal @Column({ name: 'iota_milestone', type: 'bigint', nullable: true }) iotaMilestone?: number diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index 882f2db00..cea8c3cd3 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -8,19 +8,19 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis await queryFn(` ALTER TABLE \`accounts\` - RENAME COLUMN \`balance\` TO \`balance_confirmed_at\`, - RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at_date\` + RENAME COLUMN \`balance\` TO \`balance_on_confirmation\`, + RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at\` ; `) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_confirmed_at_date\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_on_creation\` decimal(40,20) NOT NULL DEFAULT 0 AFTER \`balance_confirmed_at\`;`, ) await queryFn( - `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at_date\` datetime(3) NOT NULL AFTER \`balance_created_at\`;`, + `ALTER TABLE \`accounts\` ADD COLUMN \`balance_created_at\` datetime(3) NOT NULL AFTER \`balance_on_creation\`;`, ) await queryFn( - `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at_date\` datetime NULL DEFAULT NULL;`, + `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at\` datetime NULL DEFAULT NULL;`, ) await queryFn( @@ -41,7 +41,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`community_id\` int unsigned NOT NULL, \`other_community_id\` int unsigned NULL DEFAULT NULL, \`amount\` decimal(40, 20) NULL DEFAULT NULL, - \`account_balance_created_at\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, + \`account_balance_on_creation\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, \`type\` tinyint NOT NULL, \`created_at\` datetime(3) NOT NULL, \`body_bytes\` blob NOT NULL, @@ -49,7 +49,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`protocol_version\` varchar(255) NOT NULL DEFAULT '1', \`nr\` bigint NULL DEFAULT NULL, \`running_hash\` varbinary(48) NULL DEFAULT NULL, - \`account_balance_confirmed_at\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, + \`account_balance_on_confirmation\` decimal(40, 20) NULL DEFAULT 0.00000000000000000000, \`iota_milestone\` bigint NULL DEFAULT NULL, \`confirmed_at\` datetime NULL DEFAULT NULL, PRIMARY KEY (\`id\`), @@ -115,13 +115,13 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom ) await queryFn(` ALTER TABLE \`accounts\` - RENAME COLUMN \`balance_confirmed_at\` TO \`balance\`, - RENAME COLUMN \`balance_confirmed_at_date\` TO \`balance_date\` + RENAME COLUMN \`balance_on_confirmation\` TO \`balance\`, + RENAME COLUMN \`balance_confirmed_at\` TO \`balance_date\` ; `) + await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_on_creation\`;`) await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at\`;`) - await queryFn(`ALTER TABLE \`accounts\` DROP COLUMN \`balance_created_at_date\`;`) await queryFn(`ALTER TABLE \`invalid_transactions\` DROP COLUMN \`error_message\`;`) await queryFn(`ALTER TABLE \`invalid_transactions\` DROP INDEX \`iota_message_id\`;`) await queryFn(`ALTER TABLE \`invalid_transactions\` ADD INDEX(\`iota_message_id\`); `) From bcaae7002c0d683d97825169070fc21180f8a027 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 22 Dec 2023 12:52:10 +0100 Subject: [PATCH 31/47] update DltConnectorClient to set user correct --- backend/src/apis/DltConnectorClient.ts | 174 ++++++++++++++++++++++--- 1 file changed, 153 insertions(+), 21 deletions(-) diff --git a/backend/src/apis/DltConnectorClient.ts b/backend/src/apis/DltConnectorClient.ts index f01a55d6c..c558da77a 100644 --- a/backend/src/apis/DltConnectorClient.ts +++ b/backend/src/apis/DltConnectorClient.ts @@ -1,4 +1,5 @@ import { Transaction as DbTransaction } from '@entity/Transaction' +import { User as DbUser } from '@entity/User' import { gql, GraphQLClient } from 'graphql-request' import { CONFIG } from '@/config' @@ -14,6 +15,52 @@ const sendTransaction = gql` } ` +enum TransactionType { + GRADIDO_TRANSFER = 1, + GRADIDO_CREATION = 2, + GROUP_FRIENDS_UPDATE = 3, + REGISTER_ADDRESS = 4, + GRADIDO_DEFERRED_TRANSFER = 5, + COMMUNITY_ROOT = 6, +} + +enum TransactionErrorType { + NOT_IMPLEMENTED_YET = 'Not Implemented yet', + MISSING_PARAMETER = 'Missing parameter', + ALREADY_EXIST = 'Already exist', + DB_ERROR = 'DB Error', + PROTO_DECODE_ERROR = 'Proto Decode Error', + PROTO_ENCODE_ERROR = 'Proto Encode Error', + INVALID_SIGNATURE = 'Invalid Signature', + LOGIC_ERROR = 'Logic Error', + NOT_FOUND = 'Not found', +} + +interface TransactionError { + type: TransactionErrorType + message: string + name: string +} + +interface TransactionRecipe { + id: number + createdAt: string + type: TransactionType + topic: string +} + +interface TransactionResult { + error?: TransactionError + recipe?: TransactionRecipe + succeed: boolean +} + +interface UserIdentifier { + uuid: string + communityUuid: string + accountNr?: number +} + // from ChatGPT function getTransactionTypeString(id: TransactionTypeId): string { const key = Object.keys(TransactionTypeId).find( @@ -74,36 +121,121 @@ export class DltConnectorClient { return DltConnectorClient.instance } + protected async getCorrectUserUUID( + transaction: DbTransaction, + type: 'sender' | 'recipient', + ): Promise { + const confirmingUserId = transaction.contribution?.confirmedBy + let confirmingUser: DbUser | undefined + logger.info('confirming user id', confirmingUserId) + if (confirmingUserId) { + confirmingUser = await DbUser.findOneOrFail({ where: { id: confirmingUserId } }) + } + switch (transaction.typeId) { + case TransactionTypeId.CREATION: + if (!confirmingUserId || !confirmingUser) { + throw new LogError( + "couldn't find id of confirming moderator for contribution transaction!", + ) + } + if (type === 'sender') { + return (await DbUser.findOneOrFail({ where: { id: confirmingUserId } })).gradidoID + } else if (type === 'recipient') { + return transaction.userGradidoID + } + break + case TransactionTypeId.SEND: + if (type === 'sender') { + return transaction.userGradidoID + } else if (type === 'recipient') { + if (!transaction.linkedUserGradidoID) { + throw new LogError('missing linked user gradido id') + } + return transaction.linkedUserGradidoID + } + break + case TransactionTypeId.RECEIVE: + if (type === 'sender') { + if (!transaction.linkedUserGradidoID) { + throw new LogError('missing linked user gradido id') + } + return transaction.linkedUserGradidoID + } else if (type === 'recipient') { + return transaction.userGradidoID + } + } + throw new LogError('unhandled case') + } + + protected async getCorrectUserIdentifier( + transaction: DbTransaction, + senderCommunityUuid: string, + recipientCommunityUuid: string, + type: 'sender' | 'recipient', + ): Promise { + // sender and receiver user on creation transaction + // sender user on send transaction (SEND and RECEIVE) + if (type === 'sender' || transaction.typeId === TransactionTypeId.CREATION) { + return { + uuid: await this.getCorrectUserUUID(transaction, type), + communityUuid: senderCommunityUuid, + } + } + // recipient user on SEND and RECEIVE transactions + return { + uuid: await this.getCorrectUserUUID(transaction, type), + communityUuid: recipientCommunityUuid ?? senderCommunityUuid, + } + } + /** * transmit transaction via dlt-connector to iota * and update dltTransactionId of transaction in db with iota message id */ public async transmitTransaction( transaction: DbTransaction, - senderCommunityUuid?: string, - recipientCommunityUuid?: string, - ): Promise { + senderCommunityUuid: string, + recipientCommunityUuid: string, + ): Promise { const typeString = getTransactionTypeString(transaction.typeId) - const amountString = transaction.amount.toString() + // no negative values in dlt connector, gradido concept don't use negative values so the code don't use it too + const amountString = transaction.amount.abs().toString() + const params = { + input: { + senderUser: await this.getCorrectUserIdentifier( + transaction, + senderCommunityUuid, + recipientCommunityUuid, + 'sender', + ), + recipientUser: await this.getCorrectUserIdentifier( + transaction, + senderCommunityUuid, + recipientCommunityUuid, + 'recipient', + ), + amount: amountString, + type: typeString, + createdAt: transaction.balanceDate.toISOString(), + backendTransactionId: transaction.id, + targetDate: transaction.creationDate?.toISOString(), + }, + } try { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const { data } = await this.client.rawRequest(sendTransaction, { - input: { - senderUser: { - uuid: transaction.userGradidoID, - communityUuid: senderCommunityUuid, - }, - recipientUser: { - uuid: transaction.linkedUserGradidoID, - communityUuid: recipientCommunityUuid, - }, - amount: amountString, - type: typeString, - createdAt: transaction.balanceDate.toString(), + // TODO: add account nr for user after they have also more than one account in backend + logger.debug('transmit transaction to dlt connector', params) + const { + data: { + sendTransaction: { error, succeed }, }, - }) - // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access - return data.sendTransaction.dltTransactionIdHex + } = await this.client.rawRequest<{ sendTransaction: TransactionResult }>( + sendTransaction, + params, + ) + if (error) { + throw new Error(error.message) + } + return succeed } catch (e) { throw new LogError('Error send sending transaction to dlt-connector: ', e) } From ba13144ad3ebad781dc4999372e4c3beaf908bb5 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 22 Dec 2023 15:19:21 +0100 Subject: [PATCH 32/47] add backendTransaction table, update dltConnectorClient code and test --- backend/log.txt | 2533 +++++++++++++++++ backend/src/apis/DltConnectorClient.test.ts | 36 +- backend/src/apis/DltConnectorClient.ts | 20 +- .../sendTransactionsToDltConnector.test.ts | 43 +- .../util/sendTransactionsToDltConnector.ts | 21 +- .../src/data/BackendTransaction.factory.ts | 13 + .../src/data/BackendTransaction.repository.ts | 7 + dlt-connector/src/data/Transaction.builder.ts | 11 +- .../src/data/Transaction.repository.ts | 21 +- .../graphql/resolver/TransactionsResolver.ts | 34 +- .../transaction/TransactionRecipe.role.ts | 4 +- .../BackendTransaction.ts | 45 + .../Transaction.ts | 11 +- dlt-database/entity/BackendTransaction.ts | 1 + dlt-database/entity/index.ts | 2 + .../0003-refactor_transaction_recipe.ts | 18 +- 16 files changed, 2717 insertions(+), 103 deletions(-) create mode 100644 backend/log.txt create mode 100644 dlt-connector/src/data/BackendTransaction.factory.ts create mode 100644 dlt-connector/src/data/BackendTransaction.repository.ts create mode 100644 dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts create mode 100644 dlt-database/entity/BackendTransaction.ts diff --git a/backend/log.txt b/backend/log.txt new file mode 100644 index 000000000..b496d4791 --- /dev/null +++ b/backend/log.txt @@ -0,0 +1,2533 @@ + FAIL  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionResolver.test.tssrc/graphql/resolver/ContributionResolver.test.ts]8;; (9.447 s) + ContributionResolver + createContribution + unauthenticated + ✓ returns an error (8 ms) + authenticated with valid user + input not valid + ✓ throws error when memo length smaller than 5 chars (7 ms) + ✓ throws error when memo length greater than 255 chars (5 ms) + ✓ throws error when creationDate not-valid (4 ms) + ✓ throws error when creationDate 3 month behind (13 ms) + ✓ logs the error "No information for available creations for the given date" again (1 ms) + valid input + ✓ creates contribution + ✓ stores the CONTRIBUTION_CREATE event in the database (4 ms) + updateContribution + unauthenticated + ✓ returns an error (2 ms) + authenticated + Memo length smaller than 5 chars + ✓ throws error (5 ms) + Memo length greater than 255 chars + ✓ throws error (6 ms) + wrong contribution id + ✓ throws an error (8 ms) + ✓ logs the error "Contribution not found" + wrong user tries to update the contribution + ✓ throws an error (10 ms) + ✓ logs the error "Can not update contribution of another user" (1 ms) + admin tries to update a user contribution + ✕ throws an error (24 ms) + ✕ logs the error "An admin is not allowed to update an user contribution" (1 ms) + contribution has wrong status + ✓ throws an error (9 ms) + ✓ logs the error "Contribution can not be updated due to status" (1 ms) + update too much so that the limit is exceeded + ✓ throws an error (10 ms) + ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) + update creation to a date that is older than 3 months + ✓ throws an error (6 ms) + ✓ logs the error "Month of contribution can not be changed" (1 ms) + valid input + ✓ updates contribution (19 ms) + ✓ stores the CONTRIBUTION_UPDATE event in the database (97 ms) + denyContribution + unauthenticated + ✓ returns an error (2 ms) + authenticated without admin rights + ✓ returns an error (6 ms) + authenticated with admin rights + wrong contribution id + ✓ throws an error (6 ms) + ✓ logs the error "Contribution not found" (1 ms) + deny contribution that is already confirmed + ✓ throws an error (218 ms) + ✓ logs the error "Contribution not found" + deny contribution that is already deleted + ✓ throws an error (216 ms) + ✓ logs the error "Contribution not found" (1 ms) + deny contribution that is already denied + ✓ throws an error (211 ms) + ✓ logs the error "Contribution not found" (1 ms) + valid input + ✓ deny contribution (103 ms) + ✓ stores the ADMIN_CONTRIBUTION_DENY event in the database (2 ms) + ✓ calls sendContributionDeniedEmail + deleteContribution + unauthenticated + ✓ returns an error (1 ms) + authenticated + wrong contribution id + ✓ returns an error (7 ms) + ✓ logs the error "Contribution not found" (1 ms) + other user sends a deleteContribution + ✓ returns an error (5 ms) + ✓ logs the error "Can not delete contribution of another user" (1 ms) + User deletes own contribution + ✓ deletes successfully (20 ms) + ✓ stores the CONTRIBUTION_DELETE event in the database (2 ms) + User deletes already confirmed contribution + ✓ throws an error (199 ms) + ✓ logs the error "A confirmed contribution can not be deleted" (1 ms) + listContributions + unauthenticated + ✓ returns an error (2 ms) + authenticated + no status filter + ✕ returns creations (15 ms) + with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] + ✕ returns only unconfirmed creations (9 ms) + listAllContribution + unauthenticated + ✓ returns an error (1 ms) + authenticated + ✓ throws an error with "NOT_VALID" in statusFilter (6 ms) + ✓ throws an error with a null in statusFilter (2 ms) + ✓ throws an error with null and "NOT_VALID" in statusFilter (2 ms) + ✓ returns all contributions without statusFilter (8 ms) + ✓ returns all contributions for statusFilter = null (8 ms) + ✓ returns all contributions for statusFilter = [] (7 ms) + ✓ returns all CONFIRMED contributions (6 ms) + ✓ returns all PENDING contributions (6 ms) + ✓ returns all IN_PROGRESS Creation (6 ms) + ✓ returns all DENIED Creation (6 ms) + ✓ does not return any DELETED Creation (6 ms) + ✓ returns all CONFIRMED and PENDING Creation (7 ms) + contributions + unauthenticated + adminCreateContribution + ✓ returns an error (2 ms) + adminUpdateContribution + ✓ returns an error (1 ms) + adminDeleteContribution + ✓ returns an error (1 ms) + confirmContribution + ✓ returns an error (1 ms) + authenticated + without admin rights + adminCreateContribution + ✓ returns an error (7 ms) + adminUpdateContribution + ✓ returns an error (4 ms) + adminDeleteContribution + ✓ returns an error (3 ms) + confirmContribution + ✓ returns an error (3 ms) + with admin rights + adminCreateContribution + user to create for does not exist + ✓ throws an error (7 ms) + ✓ logs the error "Could not find user" (1 ms) + user to create for is deleted + ✓ throws an error (6 ms) + ✓ logs the error "Cannot create contribution since the user was deleted" (1 ms) + user to create for has email not confirmed + ✓ throws an error (7 ms) + ✓ logs the error "Cannot create contribution since the users email is not activated" (1 ms) + valid user to create for + date of creation is not a date string + ✓ throws an error (4 ms) + date of creation is four months ago + ✓ throws an error (7 ms) + ✓ logs the error "No information for available creations for the given date" + date of creation is in the future + ✓ throws an error (7 ms) + ✓ logs the error "No information for available creations for the given date" + amount of creation is too high + ✓ throws an error (7 ms) + ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) + creation is valid + ✓ returns an array of the open creations for the last three months (18 ms) + ✓ stores the ADMIN_CONTRIBUTION_CREATE event in the database (5 ms) + user tries to update admin contribution + ✓ logs and throws "Cannot update contribution of moderator" error (8 ms) + second creation surpasses the available amount + ✓ returns an array of the open creations for the last three months (9 ms) + ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) + adminUpdateContribution + creation does not exist + ✓ throws an error (5 ms) + ✓ logs the error "Contribution not found" + creation update is not valid + ✓ throws an error (8 ms) + ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) + creation update is successful changing month + ○ skipped returns update creation object + ○ skipped stores the ADMIN_CONTRIBUTION_UPDATE event in the database + creation update is successful without changing month + ✓ returns update creation object (16 ms) + ✓ stores the ADMIN_CONTRIBUTION_UPDATE event in the database (3 ms) + adminDeleteContribution + creation id does not exist + ✓ throws an error (8 ms) + ✓ logs the error "Contribution not found" + admin deletes own user contribution + ✓ throws an error (5 ms) + creation id does exist + ✓ returns true (25 ms) + ✓ stores the ADMIN_CONTRIBUTION_DELETE event in the database (4 ms) + ✓ calls sendContributionDeletedEmail + creation already confirmed + ✓ throws an error (350 ms) + confirmContribution + creation does not exits + ✓ throws an error (5 ms) + ✓ logs the error "Contribution not found" (1 ms) + confirm own creation + ✓ thows an error (5 ms) + ✓ logs the error "Moderator can not confirm own contribution" (1 ms) + confirm creation for other user + ✓ returns true (21 ms) + ✓ stores the ADMIN_CONTRIBUTION_CONFIRM event in the database (4 ms) + ✓ creates a transaction (3 ms) + ✓ calls sendContributionConfirmedEmail + ✓ stores the EMAIL_CONFIRMATION event in the database (4 ms) + ✓ logs the error "Contribution already confirmed" (1 ms) + confirm same contribution again + ✓ throws an error (6 ms) + confirm two creations one after the other quickly + ✓ throws no error for the second confirmation (43 ms) + adminListContributions + unauthenticated + ✓ returns an error (2 ms) + authenticated as user + ✓ returns an error (4 ms) + authenticated as admin + ✓ throw error for invalid ContributionStatus in statusFilter array (1 ms) + ✕ returns 18 creations in total (20 ms) + ✓ returns two pending creations with page size set to 2 (9 ms) + with user query + ✕ returns only contributions of the queried user (10 ms) + ✕ returns only contributions of the queried user without hashtags (10 ms) + ✓ returns only contributions with #firefighter (7 ms) + ✓ returns no contributions with #firefighter and no hashtag (6 ms) + ✓ returns only contributions of the queried user email (8 ms) + + ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › throws an error + + expect(received).toEqual(expected) // deep equality + + Expected: [[GraphQLError: An admin is not allowed to update an user contribution]] + Received: undefined + +   509 | }, +   510 | }) + > 511 | expect(errorObjects).toEqual([ +   | ^ +   512 | new GraphQLError('An admin is not allowed to update an user contribution'), +   513 | ]) +   514 | }) + + at src/graphql/resolver/ContributionResolver.test.ts:511:32 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › logs the error "An admin is not allowed to update an user contribution" + + expect(jest.fn()).toBeCalledWith(...expected) + + Expected: "An admin is not allowed to update an user contribution" + + Number of calls: 0 + +   515 | +   516 | it('logs the error "An admin is not allowed to update an user contribution"', () => { + > 517 | expect(logger.error).toBeCalledWith( +   | ^ +   518 | 'An admin is not allowed to update an user contribution', +   519 | ) +   520 | }) + + at Object. (src/graphql/resolver/ContributionResolver.test.ts:517:32) + + ● ContributionResolver › listContributions › authenticated › no status filter › returns creations + + expect(received).toMatchObject(expected) + + - Expected - 16 + + Received + 64 + +  Object { +  "contributionCount": 6, + - "contributionList": ArrayContaining [ + - ObjectContaining { + + "contributionList": Array [ + + Object { +  "amount": "100", + - "id": 25, + - "memo": "Test contribution to confirm", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, + + "id": 27, + + "memo": "Test contribution to delete", +  "messagesCount": 0, + - }, + - ObjectContaining { + - "amount": "10", + - "id": 23, + - "memo": "Test PENDING contribution update", + - "messagesCount": 1, + + "status": "DELETED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "id": 26, +  "memo": "Test contribution to deny", +  "messagesCount": 0, + + "status": "DENIED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + - "id": 27, + - "memo": "Test contribution to delete", + + "confirmedAt": "2023-11-06T08:36:49.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 25, + + "memo": "Test contribution to confirm", +  "messagesCount": 0, + + "status": "CONFIRMED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 24, +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, + + "status": "IN_PROGRESS", +  }, + - ObjectContaining { + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 23, + + "memo": "Test PENDING contribution update", + + "messagesCount": 2, + + "status": "PENDING", + + }, + + Object { +  "amount": "1000", + + "confirmedAt": "2023-11-06T08:36:46.000Z", + + "confirmedBy": 283, + + "contributionDate": "2022-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 22, +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, + + "status": "CONFIRMED", +  }, +  ], +  } + +   1103 | }, +   1104 | }) + > 1105 | expect(contributionListResult).toMatchObject({ +   | ^ +   1106 | contributionCount: 6, +   1107 | contributionList: expect.arrayContaining([ +   1108 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:1105:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › listContributions › authenticated › with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] › returns only unconfirmed creations + + expect(received).toMatchObject(expected) + + - Expected - 19 + + Received + 44 + +  Object { +  "contributionCount": 4, + - "contributionList": ArrayContaining [ + - ObjectNotContaining { + - "status": "CONFIRMED", + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, + + "id": 27, + + "memo": "Test contribution to delete", + + "messagesCount": 0, + + "status": "DELETED", +  }, + - ObjectContaining { + - "amount": "10", + - "id": 23, + - "memo": "Test PENDING contribution update", + - "messagesCount": 1, + - "status": "PENDING", + - }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "id": 26, +  "memo": "Test contribution to deny", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + - "id": 27, + - "memo": "Test contribution to delete", + - "messagesCount": 0, + - "status": "DELETED", + - }, + - ObjectContaining { + - "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 24, +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, +  "status": "IN_PROGRESS", + + }, + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 23, + + "memo": "Test PENDING contribution update", + + "messagesCount": 2, + + "status": "PENDING", +  }, +  ], +  } + +   1161 | }, +   1162 | }) + > 1163 | expect(contributionListResult).toMatchObject({ +   | ^ +   1164 | contributionCount: 4, +   1165 | contributionList: expect.arrayContaining([ +   1166 | expect.not.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:1163:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › returns 18 creations in total + + expect(received).toMatchObject(expected) + + - Expected - 57 + + Received + 165 + + @@ -1,165 +1,273 @@ +  Object { +  "contributionCount": 18, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<100>, + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:51.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 39, +  "lastName": "Lustig", +  "memo": "#firefighters", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<50>, + + Object { + + "amount": "50", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 38, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<50>, + + Object { + + "amount": "50", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 37, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<450>, + + Object { + + "amount": "450", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 36, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<400>, + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": "2023-11-06T08:36:50.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bob", + - "id": Any, + + "id": 34, +  "lastName": "der Baumeister", +  "memo": "Confirmed Contribution", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 32, +  "lastName": "Bloxberg", +  "memo": "Aktives Grundeinkommen", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "firstName": "Räuber", + - "id": Any, + + "id": 30, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Räuber", + - "id": Any, + + "id": 29, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": "2023-11-06T08:36:48.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Räuber", + - "id": Any, + + "id": 28, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 27, +  "lastName": "Bloxberg", +  "memo": "Test contribution to delete", +  "messagesCount": 0, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "firstName": "Bibi", + - "id": Any, + + "id": 26, +  "lastName": "Bloxberg", +  "memo": "Test contribution to deny", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": "2023-11-06T08:36:49.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 25, +  "lastName": "Bloxberg", +  "memo": "Test contribution to confirm", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 24, +  "lastName": "Bloxberg", +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, +  "status": "IN_PROGRESS", +  }, + - ObjectContaining { + - "amount": decimalEqual<10>, + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 23, +  "lastName": "Bloxberg", +  "memo": "Test PENDING contribution update", + - "messagesCount": 2, + + "messagesCount": 3, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<1000>, + + Object { + + "amount": "1000", + + "confirmedAt": "2023-11-06T08:36:46.000Z", + + "confirmedBy": 283, + + "contributionDate": "2022-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 22, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + +   2827 | // console.log('17 contributions: %s', JSON.stringify(contributionListObject, null, 2)) +   2828 | expect(contributionListObject.contributionList).toHaveLength(18) + > 2829 | expect(contributionListObject).toMatchObject({ +   | ^ +   2830 | contributionCount: 18, +   2831 | contributionList: expect.arrayContaining([ +   2832 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:2829:40 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user + + expect(received).toMatchObject(expected) + + - Expected - 14 + + Received + 38 + +  Object { +  "contributionCount": 4, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<100>, + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:51.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 39, +  "lastName": "Lustig", +  "memo": "#firefighters", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<400>, + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, +  ], +  } + +   3057 | }) +   3058 | expect(contributionListObject.contributionList).toHaveLength(4) + > 3059 | expect(contributionListObject).toMatchObject({ +   | ^ +   3060 | contributionCount: 4, +   3061 | contributionList: expect.arrayContaining([ +   3062 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:3059:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user without hashtags + + expect(received).toMatchObject(expected) + + - Expected - 11 + + Received + 29 + +  Object { +  "contributionCount": 3, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<400>, + + "contributionList": Array [ + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, +  ], +  } + +   3111 | }) +   3112 | expect(contributionListObject.contributionList).toHaveLength(3) + > 3113 | expect(contributionListObject).toMatchObject({ +   | ^ +   3114 | contributionCount: 3, +   3115 | contributionList: expect.arrayContaining([ +   3116 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:3113:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/UserResolver.test.tssrc/graphql/resolver/UserResolver.test.ts]8;; (12.687 s) + UserResolver + createUser + ✓ returns success (2 ms) + valid input data + ✓ stores the USER_REGISTER event in the database (5 ms) + filling all tables + ✓ saves the user in users table (1 ms) + ✓ creates an email contact + account activation email + ✓ sends an account activation email (1 ms) + ✓ stores the EMAIL_CONFIRMATION event in the database (2 ms) + user already exists + ✓ logs an info (1 ms) + ✓ sends an account multi registration email (1 ms) + ✓ results with partly faked user with random "id" + ✓ stores the EMAIL_ACCOUNT_MULTIREGISTRATION event in the database (7 ms) + unknown language + ✓ sets "de" as default language (63 ms) + no publisher id + ✓ sets publisher id to 0 (55 ms) + redeem codes + contribution link + ✓ sets the contribution link id (4 ms) + ✓ stores the USER_ACTIVATE_ACCOUNT event in the database (2 ms) + ✓ stores the USER_REGISTER_REDEEM event in the database (3 ms) + transaction link + ✓ sets the referrer id to bob baumeister id (3 ms) + ✓ stores the USER_REGISTER_REDEEM event in the database (2 ms) + setPassword + valid optin code and valid password + ✓ sets email checked to true (1 ms) + ✓ updates the password (76 ms) + ✓ calls the klicktipp API + ✓ returns true (1 ms) + no valid password + ✓ throws an error (21 ms) + ✓ logs the error thrown (1 ms) + no valid optin code + ✓ throws an error (2 ms) + ✓ logs the error found + login + no users in database + ✓ throws an error (6 ms) + ✓ logs the error found (1 ms) + user is in database and correct login data + ✓ returns the user object (1 ms) + ✓ sets the token in the header (1 ms) + ✓ stores the USER_LOGIN event in the database (4 ms) + user is in database and wrong password + ✓ returns an error (1 ms) + ✓ logs the error thrown (1 ms) + user is in database but deleted + ✓ returns an error (1 ms) + ✓ logs the error thrown + user is in database but email not confirmed + ✓ returns an error (1 ms) + ✓ logs the error thrown + user is in database but password is not set + ○ skipped returns an error + ○ skipped logs the error thrown + logout + unauthenticated + ✓ throws an error (4 ms) + authenticated + ✓ returns true (10 ms) + ✓ stores the USER_LOGOUT event in the database (6 ms) + verifyLogin + unauthenticated + ✓ throws an error (1 ms) + user exists but is not logged in + ✓ throws an error (1 ms) + authenticated + ✓ returns user object (5 ms) + ✓ stores the USER_LOGIN event in the database (4 ms) + forgotPassword + user is not in DB + duration not expired + ✓ returns true (3 ms) + user exists in DB + duration not expired + ✓ throws an error (7 ms) + duration reset to 0 + ✓ returns true (36 ms) + ✓ sends reset password email (1 ms) + ✓ stores the EMAIL_FORGOT_PASSWORD event in the database (5 ms) + request reset password again + ✓ thows an error (6 ms) + ✓ logs the error found + queryOptIn + wrong optin code + ✓ throws an error (8 ms) + correct optin code + ✓ returns true (2 ms) + updateUserInfos + unauthenticated + ✓ throws an error (2 ms) + authenticated + ✓ returns true (13 ms) + first-name, last-name and language + ✓ updates the fields in DB (14 ms) + ✓ stores the USER_INFO_UPDATE event in the database (7 ms) + alias + valid alias + ✓ updates the user in DB (17 ms) + language is not valid + ✓ throws an error (5 ms) + ✓ logs the error found + password + wrong old password + ✓ throws an error (81 ms) + ✓ logs the error found + invalid new password + ✓ throws an error (5 ms) + ✓ logs the error found (1 ms) + correct old and new password + ✓ returns true (166 ms) + ✓ can login with new password (89 ms) + ✓ cannot login with old password (82 ms) + ✓ logs the error thrown (1 ms) + searchAdminUsers + unauthenticated + ✓ throws an error (3 ms) + authenticated + ✓ finds peter@lustig.de (8 ms) + password encryption type + user just registered + ✓ has password type gradido id (79 ms) + user has encryption type email + ✓ changes to gradidoID on login (259 ms) + ✓ can login after password change (93 ms) + set user role + unauthenticated + ✓ returns an error (2 ms) + authenticated + with user rights + ✓ returns an error (4 ms) + with moderator rights + ✓ returns an error (4 ms) + with admin rights + ✓ returns user with new moderator-role (18 ms) + user to get a new role does not exist + ✓ throws an error (8 ms) + ✓ logs the error thrown (1 ms) + change role with success + user gets new role + to admin + ✓ returns admin-rolename (17 ms) + ✓ stores the ADMIN_USER_ROLE_SET event in the database (5 ms) + to moderator + ✓ returns date string (18 ms) + ✓ stores the ADMIN_USER_ROLE_SET event in the database (2 ms) + to usual user + ✓ returns null (16 ms) + change role with error + his own role + ✓ throws an error (7 ms) + ✓ logs the error thrown + to not allowed role + ✓ throws an error (4 ms) + user has already role to be set + to admin + ✓ throws an error (26 ms) + ✓ logs the error thrown (1 ms) + to moderator + ✓ throws an error (25 ms) + ✓ logs the error thrown (1 ms) + to usual user + ✓ throws an error (23 ms) + ✓ logs the error thrown + delete user + unauthenticated + ✓ returns an error (2 ms) + authenticated + without admin rights + ✓ returns an error (4 ms) + with admin rights + user to be deleted does not exist + ✓ throws an error (6 ms) + ✓ logs the error thrown + delete self + ✓ throws an error (7 ms) + ✓ logs the error thrown + delete with success + ✓ returns date string (19 ms) + ✓ stores the ADMIN_USER_DELETE event in the database (8 ms) + delete deleted user + ✓ throws an error (6 ms) + ✓ logs the error thrown + sendActivationEmail + unauthenticated + ✓ returns an error (2 ms) + authenticated + without admin rights + ✓ returns an error (3 ms) + with admin rights + user does not exist + ✓ throws an error (6 ms) + ✓ logs the error thrown + user is deleted + ✓ throws an error (155 ms) + ✓ logs the error thrown + sendActivationEmail with success + ✓ returns true (36 ms) + ✓ sends an account activation email (4 ms) + ✓ stores the EMAIL_ADMIN_CONFIRMATION event in the database (7 ms) + unDelete user + unauthenticated + ✓ returns an error (2 ms) + authenticated + without admin rights + ✓ returns an error (4 ms) + with admin rights + user to be undelete does not exist + ✓ throws an error (5 ms) + ✓ logs the error thrown + user to undelete is not deleted + ✓ throws an error (6 ms) + ✓ logs the error thrown + undelete deleted user + ✓ returns null (14 ms) + ✓ stores the ADMIN_USER_UNDELETE event in the database (8 ms) + search users + unauthenticated + ✓ returns an error (4 ms) + authenticated + without admin rights + ✓ returns an error (4 ms) + with admin rights + without any filters + ✓ finds all users (18 ms) + all filters are null + ✓ finds all users (14 ms) + filter by unchecked email + ✓ finds only users with unchecked email (10 ms) + filter by deleted users + ✓ finds only users with deleted account (9 ms) + filter by deleted account and unchecked email + ✓ finds no users (6 ms) + user + unauthenticated + ✓ throws and logs "401 Unauthorized" error (2 ms) + authenticated + identifier is no gradido ID, no email and no alias + ✓ throws and logs "Unknown identifier type" error (8 ms) + identifier is not found + ✓ throws and logs "No user found to given identifier" error (8 ms) + identifier is found via email, but not matching community + ✓ returns user (6 ms) + identifier is found via email + ✓ returns user (9 ms) + identifier is found via gradidoID + ✓ returns user (7 ms) + identifier is found via alias + ✓ returns user (7 ms) + check username + reserved alias + ✓ returns false (2 ms) + valid alias + ✓ returns true (3 ms) + printTimeDuration + ✓ works with 10 minutes (1 ms) + ✓ works with 1440 minutes (1 ms) + ✓ works with 1410 minutes + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/TransactionLinkResolver.test.tssrc/graphql/resolver/TransactionLinkResolver.test.ts]8;; (5.288 s) + TransactionLinkResolver + createTransactionLink + unauthenticated + ✓ throws an error (9 ms) + authenticated + ✓ throws error when amount is zero (6 ms) + ✓ throws error when amount is negative (4 ms) + ✓ throws error when memo text is too short (5 ms) + ✓ throws error when memo text is too long (7 ms) + ✓ throws error when user has not enough GDD (13 ms) + ✓ logs the error "User has not enough GDD" + redeemTransactionLink + unauthenticated + ✓ throws an error (1 ms) + authenticated + contributionLink + input not valid + ✓ throws error when link does not exists (14 ms) + ✓ logs the error "No contribution link found to given code" (1 ms) + ✓ throws error when link is not valid yet (31 ms) + ✓ logs the error "Contribution link is not valid yet" (1 ms) + ✓ throws error when contributionLink cycle is invalid (26 ms) + ✓ logs the error "Contribution link has unknown cycle" + ✓ throws error when link is no longer valid (24 ms) + ✓ logs the error "Contribution link is no longer valid" (1 ms) + redeem daily Contribution Link + ✓ has a daily contribution link in the database (3 ms) + user has pending contribution of 1000 GDD + ✓ does not allow the user to redeem the contribution link (11 ms) + ✓ logs the error "Creation from contribution link was not successful" (1 ms) + user has no pending contributions that would not allow to redeem the link + ✓ allows the user to redeem the contribution link (24 ms) + ✓ stores the CONTRIBUTION_LINK_REDEEM event in the database (10 ms) + ✓ does not allow the user to redeem the contribution link a second time on the same day (8 ms) + ✓ logs the error "Creation from contribution link was not successful" + after one day + ✓ allows the user to redeem the contribution link again (25 ms) + ✓ does not allow the user to redeem the contribution link a second time on the same day (15 ms) + ✓ logs the error "Creation from contribution link was not successful" + transaction link + link does not exits + ✓ throws and logs the error (6 ms) + link exists + ✓ stores the TRANSACTION_LINK_CREATE event in the database (5 ms) + own link + ✓ throws and logs an error (13 ms) + ✓ delete own link (16 ms) + ✓ stores the TRANSACTION_LINK_DELETE event in the database (9 ms) + other link + ✓ successfully redeems link (99 ms) + ✓ stores the TRANSACTION_LINK_REDEEM event in the database (16 ms) + listTransactionLinksAdmin + unauthenticated + ✓ returns an error (5 ms) + authenticated + without admin rights + ✓ returns an error (4 ms) + with admin rights + ✓ throws error when user does not exists (6 ms) + ✓ logs the error "Could not find requested User" + without any filters + ✓ finds 6 open transaction links and no deleted or redeemed (14 ms) + all filters are null + ✓ finds 6 open transaction links and no deleted or redeemed (7 ms) + filter with deleted + ✓ finds 6 open transaction links, 1 deleted, and no redeemed (7 ms) + filter by expired + ✓ finds 5 open transaction links, 1 expired, and no redeemed (10 ms) + filter by redeemed + ○ skipped finds 6 open transaction links, 1 deleted, and no redeemed + transactionLinkCode + ✓ returns a string of length 24 + ✓ returns a string that ends with the hex value of date + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionMessageResolver.test.tssrc/graphql/resolver/ContributionMessageResolver.test.ts]8;; + ContributionMessageResolver + adminCreateContributionMessage + unauthenticated + ✓ returns an error (12 ms) + authenticated + input not valid + ✓ throws error when contribution does not exist (11 ms) + ✓ logs the error "ContributionMessage was not sent successfully: Error: Contribution not found" (1 ms) + ✓ throws error when contribution.userId equals user.id (116 ms) + ✓ logs the error "ContributionMessage was not sent successfully: Error: Admin can not answer on his own contribution" (1 ms) + contribution message type MODERATOR + ✓ creates ContributionMessage (17 ms) + ✓ does not call sendAddedContributionMessageEmail (1 ms) + ✓ does not change contribution status (2 ms) + valid input + ✓ creates ContributionMessage (52 ms) + ✓ calls sendAddedContributionMessageEmail (1 ms) + ✓ changes contribution status (4 ms) + ✓ stores the ADMIN_CONTRIBUTION_MESSAGE_CREATE event in the database (3 ms) + createContributionMessage + unauthenticated + ✓ returns an error (2 ms) + authenticated + input not valid + ✓ throws error when contribution does not exist (11 ms) + ✓ logs the error "ContributionMessage was not sent successfully: Error: Contribution not found" + ✓ throws error when other user tries to send createContributionMessage (99 ms) + ✓ logs the error "ContributionMessage was not sent successfully: Error: Can not send message to contribution of another user" (1 ms) + valid input + ✓ creates ContributionMessage (15 ms) + ✓ stores the CONTRIBUTION_MESSAGE_CREATE event in the database (2 ms) + listContributionMessages + unauthenticated + ✓ returns an error (2 ms) + authenticated + ✓ returns a list of contributionmessages without type MODERATOR (11 ms) + adminListContributionMessages + unauthenticated + ✓ returns an error (2 ms) + authenticated as user + ✓ returns an error (5 ms) + authenticated as admin + ✓ returns a list of contributionmessages with type MODERATOR (11 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/TransactionResolver.test.tssrc/graphql/resolver/TransactionResolver.test.ts]8;; + send coins + unknown recipient + ✓ throws an error (106 ms) + ✓ logs the error thrown (1 ms) + deleted recipient + ✓ throws an error (94 ms) + ✓ logs the error thrown (1 ms) + recipient account not activated + ✓ throws an error (92 ms) + ✓ logs the error thrown (1 ms) + errors in the transaction itself + sender and recipient are the same + ✓ throws an error (27 ms) + ✓ logs the error thrown (1 ms) + memo text is too short + ✓ throws an error (4 ms) + memo text is too long + ✓ throws an error (6 ms) + user has not enough GDD + ✓ throws an error (14 ms) + ✓ logs the error thrown + user has some GDD + trying to send negative amount + ✓ throws an error (4 ms) + good transaction + ✓ sends the coins (37 ms) + ✓ stores the TRANSACTION_SEND event in the database (35 ms) + ✓ stores the TRANSACTION_RECEIVE event in the database (6 ms) + sendTransactionsToDltConnector + ✓ has wait till sendTransactionsToDltConnector created all dlt-transactions (1 ms) + send coins via gradido ID + ✓ sends the coins (45 ms) + send coins via alias + ✓ sends the coins (38 ms) + peter's transactions + ✓ has all expected transactions (173 ms) + X-Com send coins via gradido ID + ✓ sends the coins (52 ms) + more transactions to test semaphore + ✓ sends the coins four times in a row (251 ms) + transactionList + unauthenticated + ✓ throws an error (9 ms) + authenticated + no transactions + ✓ has no transactions and balance 0 (82 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/creations.test.tssrc/graphql/resolver/util/creations.test.ts]8;; + util/creation + getUserCreations + ✓ has the correct data setup (4 ms) + call getUserCreation now + ✓ returns the expected open contributions (4 ms) + run forward in time one hour before next month + ✓ has the clock set correctly (1 ms) + call getUserCreation with UTC + ✓ returns the expected open contributions (2 ms) + call getUserCreation with JST (GMT+0900) + ✓ returns the expected open contributions (2 ms) + call getUserCreation with PST (GMT-0800) + ✓ returns the expected open contributions (2 ms) + run two hours forward to be in the next month in UTC + ✓ has the clock set correctly + call getUserCreation with UTC + ✓ returns the expected open contributions (2 ms) + call getUserCreation with JST (GMT+0900) + ✓ returns the expected open contributions (2 ms) + call getUserCreation with PST (GMT-0800) + ✓ returns the expected open contributions (3 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionLinkResolver.test.tssrc/graphql/resolver/ContributionLinkResolver.test.ts]8;; + Contribution Links + unauthenticated + createContributionLink + ✓ returns an error (11 ms) + listContributionLinks + ✓ returns an error (2 ms) + updateContributionLink + ✓ returns an error (3 ms) + deleteContributionLink + ✓ returns an error (2 ms) + authenticated + without admin rights + createContributionLink + ✓ returns an error (6 ms) + listContributionLinks + ✓ returns an empty object (7 ms) + updateContributionLink + ✓ returns an error (7 ms) + deleteContributionLink + ✓ returns an error (4 ms) + with admin rights + createContributionLink + ✓ returns a contribution link object (18 ms) + ✓ has a contribution link stored in db (4 ms) + ✓ stores the ADMIN_CONTRIBUTION_LINK_CREATE event in the database (5 ms) + ✓ returns an error if missing startDate (8 ms) + ✓ logs the error "A Start-Date must be set" (1 ms) + ✓ returns an error if missing endDate (4 ms) + ✓ logs the error "An End-Date must be set" (1 ms) + ✓ returns an error if endDate is before startDate (4 ms) + ✓ logs the error "The value of validFrom must before or equals the validTo" + ✓ returns an error if name is shorter than 5 characters (4 ms) + ✓ returns an error if name is longer than 100 characters (7 ms) + ✓ returns an error if memo is shorter than 5 characters (4 ms) + ✓ returns an error if memo is longer than 255 characters (4 ms) + ✓ returns an error if amount is not positive (4 ms) + listContributionLinks + one link in DB + ✓ returns the link and count 1 (6 ms) + updateContributionLink + ✓ logs the error "Contribution Link not found" + no valid id + ✓ returns an error (8 ms) + valid id + ✓ returns updated contribution link object (15 ms) + ✓ updated the DB record (2 ms) + ✓ stores the ADMIN_CONTRIBUTION_LINK_UPDATE event in the database (2 ms) + deleteContributionLink + no valid id + ✓ returns an error (5 ms) + ✓ logs the error "Contribution Link not found" + valid id + ✓ returns true (18 ms) + ✓ stores the ADMIN_CONTRIBUTION_LINK_DELETE event in the database (5 ms) + ✓ does not list this contribution link anymore (8 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/KlicktippResolver.test.tssrc/graphql/resolver/KlicktippResolver.test.ts]8;; + KlicktippResolver + subscribeNewsletter + unauthenticated + ✓ returns an error (9 ms) + authenticated + ✓ calls API (11 ms) + ✓ stores the NEWSLETTER_SUBSCRIBE event in the database (5 ms) + unsubscribeNewsletter + unauthenticated + ✓ returns an error (2 ms) + authenticated + ✓ calls API (11 ms) + ✓ stores the NEWSLETTER_UNSUBSCRIBE event in the database (5 ms) + +(node:16141) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit +(Use `node --trace-warnings ...` to show where the warning was created) + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/util/klicktipp.test.tssrc/util/klicktipp.test.ts]8;; + klicktipp + exportEventDataToKlickTipp + ✓ calls the KlicktippController (13 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/semaphore.test.tssrc/graphql/resolver/semaphore.test.ts]8;; + semaphore + ✓ creates a lot of transactions without errors (772 ms) + redeem transaction link twice + ✓ does throw error on second redeem call (107 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/validateAlias.test.tssrc/graphql/resolver/util/validateAlias.test.ts]8;; + validate alias + alias too short + ✓ throws and logs an error (1 ms) + alias too long + ✓ throws and logs an error (1 ms) + alias contains invalid characters + ✓ throws and logs an error + alias is a reserved word + ✓ throws and logs an error (1 ms) + alias is a reserved word with uppercase characters + ✓ throws and logs an error (1 ms) + hyphens and underscore + alias starts with underscore + ✓ throws and logs an error (3 ms) + alias contains two following hyphens + ✓ throws and logs an error (1 ms) + test against existing alias in database + alias exists in database + ✓ throws and logs an error (3 ms) + alias exists in database with in lower-case + ✓ throws and logs an error (3 ms) + valid alias + ✓ resolves to true (2 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/CommunityResolver.test.tssrc/graphql/resolver/CommunityResolver.test.ts]8;; + CommunityResolver + getCommunities + with empty list + ✓ returns no community entry (13 ms) + only home-communities entries + ✓ returns 3 home-community entries (50 ms) + plus foreign-communities entries + ✓ returns 3 home community and 3 foreign community entries (17 ms) + communities + with empty list + ✓ returns no community entry (33 ms) + with one home-community entry + ✓ returns 1 home-community entry (29 ms) + returns 2 filtered communities even with 3 existing entries + ✓ returns 2 community entries (43 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.tssrc/graphql/resolver/util/sendTransactionsToDltConnector.test.ts]8;; + create and send Transactions to DltConnector + with 3 creations but inactive dlt-connector + ✓ found 3 dlt-transactions (102 ms) + with 3 creations and active dlt-connector + ✓ found 3 dlt-transactions (104 ms) + with 3 verified creations, 1 sendCoins and active dlt-connector + ✓ found 3 dlt-transactions (114 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/EmailOptinCodes.test.tssrc/graphql/resolver/EmailOptinCodes.test.ts]8;; + EmailOptinCodes + queryOptIn + ✓ has a valid optin code (4 ms) + run time forward until code must be expired + ✓ throws an error (23 ms) + ✓ does not allow to set password (11 ms) + forgotPassword + ✓ throws an error (11 ms) + run time forward until code can be resent + ✓ cann send email again (17 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/federation/validateCommunities.test.tssrc/federation/validateCommunities.test.ts]8;; + validate Communities + start validation logic without loop + ✓ logs zero communities found (13 ms) + with one Community of api 1_0 but missing pubKey response + ✓ logs one community found (25 ms) + ✓ logs requestGetPublicKey missing response data (12 ms) + with one Community of api 1_0 and not matching pubKey + ✓ logs one community found (22 ms) + ✓ logs requestGetPublicKey for community api 1_0 (14 ms) + ✓ logs not matching publicKeys (14 ms) + with one Community of api 1_0 and matching pubKey + ✓ logs one community found (36 ms) + ✓ logs requestGetPublicKey for community api 1_0 (24 ms) + ✓ logs community pubKey verified (65 ms) + with two Communities of api 1_0 and 1_1 + ✓ logs two communities found (18 ms) + ✓ logs requestGetPublicKey for community api 1_0 (19 ms) + ✓ logs requestGetPublicKey for community api 1_1 (21 ms) + with three Communities of api 1_0, 1_1 and 2_0 + ✓ logs three community found (26 ms) + ✓ logs requestGetPublicKey for community api 1_0 (28 ms) + ✓ logs requestGetPublicKey for community api 1_1 (17 ms) + ✓ logs unsupported api for community with api 2_0 (19 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/apis/DltConnectorClient.test.tssrc/apis/DltConnectorClient.test.ts]8;; + undefined DltConnectorClient + ✓ invalid url (2 ms) + ✓ DLT_CONNECTOR is false (1 ms) + transmitTransaction + ✓ invalid transaction type (2 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/emails/sendEmailVariants.test.tssrc/emails/sendEmailVariants.test.ts]8;; + sendEmailVariants + sendAddedContributionMessageEmail + calls "sendEmailTranslated" + ✓ with expected parameters (2 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot (1 ms) + sendAccountActivationEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot (1 ms) + sendAccountMultiRegistrationEmail + calls "sendEmailTranslated" + ✓ with expected parameters + result + ✓ is the expected object + ✓ has the correct html as snapshot (1 ms) + sendContributionConfirmedEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object + ✓ has the correct html as snapshot + sendContributionDeniedEmail + calls "sendEmailTranslated" + ✓ with expected parameters + result + ✓ has expected result (1 ms) + ✓ has the correct html as snapshot (1 ms) + sendContributionDeletedEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot + sendResetPasswordEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot + sendTransactionLinkRedeemedEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot + sendTransactionReceivedEmail + calls "sendEmailTranslated" + ✓ with expected parameters (1 ms) + result + ✓ is the expected object (1 ms) + ✓ has the correct html as snapshot + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/test/helpers.test.tstest/helpers.test.ts]8;; + contributionDateFormatter + ✓ formats the date correctly (2 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/emails/sendEmailTranslated.test.tssrc/emails/sendEmailTranslated.test.ts]8;; + sendEmailTranslated + config email is false + ✓ logs warning (2 ms) + ✓ returns false + config email is true + ✓ calls the transporter (104 ms) + ○ skipped calls "i18n.setLocale" with "en" + ○ skipped calls "i18n.__" for translation + call of "sendEmailTranslated" + ✓ has expected result (50 ms) + with email EMAIL_TEST_MODUS true + ✓ call of "sendEmailTranslated" with faked "to" (39 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/server/LogError.test.tssrc/server/LogError.test.ts]8;; + LogError + ✓ logs an Error when created (2 ms) + ✓ logs an Error including additional data when created (1 ms) + ✓ does not contain additional data in Error object when thrown (3 ms) + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/util/decay.test.tssrc/util/decay.test.ts]8;; + utils/decay + ✓ has base 0.99999997802044727 + ✓ returns input amount when from and to is the same (1 ms) + decayFormula + ✓ has base 0.99999997802044727 (1 ms) + ✓ has correct backward calculation + ○ skipped has correct forward calculation + + PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/config/index.test.tssrc/config/index.test.ts]8;; + config/index + decay start block + ✓ has the correct date set (2 ms) + +Running coverage on untested files...Browserslist: caniuse-lite is outdated. Please run: + npx browserslist@latest --update-db + Why you should do it regularly: https://github.com/browserslist/browserslist#browsers-data-updating +Summary of all failing tests + FAIL  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionResolver.test.tssrc/graphql/resolver/ContributionResolver.test.ts]8;; (9.447 s) + ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › throws an error + + expect(received).toEqual(expected) // deep equality + + Expected: [[GraphQLError: An admin is not allowed to update an user contribution]] + Received: undefined + +   509 | }, +   510 | }) + > 511 | expect(errorObjects).toEqual([ +   | ^ +   512 | new GraphQLError('An admin is not allowed to update an user contribution'), +   513 | ]) +   514 | }) + + at src/graphql/resolver/ContributionResolver.test.ts:511:32 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › logs the error "An admin is not allowed to update an user contribution" + + expect(jest.fn()).toBeCalledWith(...expected) + + Expected: "An admin is not allowed to update an user contribution" + + Number of calls: 0 + +   515 | +   516 | it('logs the error "An admin is not allowed to update an user contribution"', () => { + > 517 | expect(logger.error).toBeCalledWith( +   | ^ +   518 | 'An admin is not allowed to update an user contribution', +   519 | ) +   520 | }) + + at Object. (src/graphql/resolver/ContributionResolver.test.ts:517:32) + + ● ContributionResolver › listContributions › authenticated › no status filter › returns creations + + expect(received).toMatchObject(expected) + + - Expected - 16 + + Received + 64 + +  Object { +  "contributionCount": 6, + - "contributionList": ArrayContaining [ + - ObjectContaining { + + "contributionList": Array [ + + Object { +  "amount": "100", + - "id": 25, + - "memo": "Test contribution to confirm", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, + + "id": 27, + + "memo": "Test contribution to delete", +  "messagesCount": 0, + - }, + - ObjectContaining { + - "amount": "10", + - "id": 23, + - "memo": "Test PENDING contribution update", + - "messagesCount": 1, + + "status": "DELETED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "id": 26, +  "memo": "Test contribution to deny", +  "messagesCount": 0, + + "status": "DENIED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + - "id": 27, + - "memo": "Test contribution to delete", + + "confirmedAt": "2023-11-06T08:36:49.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 25, + + "memo": "Test contribution to confirm", +  "messagesCount": 0, + + "status": "CONFIRMED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 24, +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, + + "status": "IN_PROGRESS", +  }, + - ObjectContaining { + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 23, + + "memo": "Test PENDING contribution update", + + "messagesCount": 2, + + "status": "PENDING", + + }, + + Object { +  "amount": "1000", + + "confirmedAt": "2023-11-06T08:36:46.000Z", + + "confirmedBy": 283, + + "contributionDate": "2022-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 22, +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, + + "status": "CONFIRMED", +  }, +  ], +  } + +   1103 | }, +   1104 | }) + > 1105 | expect(contributionListResult).toMatchObject({ +   | ^ +   1106 | contributionCount: 6, +   1107 | contributionList: expect.arrayContaining([ +   1108 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:1105:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › listContributions › authenticated › with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] › returns only unconfirmed creations + + expect(received).toMatchObject(expected) + + - Expected - 19 + + Received + 44 + +  Object { +  "contributionCount": 4, + - "contributionList": ArrayContaining [ + - ObjectNotContaining { + - "status": "CONFIRMED", + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, + + "id": 27, + + "memo": "Test contribution to delete", + + "messagesCount": 0, + + "status": "DELETED", +  }, + - ObjectContaining { + - "amount": "10", + - "id": 23, + - "memo": "Test PENDING contribution update", + - "messagesCount": 1, + - "status": "PENDING", + - }, + - ObjectContaining { + + Object { +  "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "id": 26, +  "memo": "Test contribution to deny", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + + Object { +  "amount": "100", + - "id": 27, + - "memo": "Test contribution to delete", + - "messagesCount": 0, + - "status": "DELETED", + - }, + - ObjectContaining { + - "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, +  "id": 24, +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, +  "status": "IN_PROGRESS", + + }, + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deletedAt": null, + + "deniedAt": null, + + "deniedBy": null, + + "id": 23, + + "memo": "Test PENDING contribution update", + + "messagesCount": 2, + + "status": "PENDING", +  }, +  ], +  } + +   1161 | }, +   1162 | }) + > 1163 | expect(contributionListResult).toMatchObject({ +   | ^ +   1164 | contributionCount: 4, +   1165 | contributionList: expect.arrayContaining([ +   1166 | expect.not.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:1163:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › returns 18 creations in total + + expect(received).toMatchObject(expected) + + - Expected - 57 + + Received + 165 + + @@ -1,165 +1,273 @@ +  Object { +  "contributionCount": 18, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<100>, + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:51.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 39, +  "lastName": "Lustig", +  "memo": "#firefighters", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<50>, + + Object { + + "amount": "50", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 38, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<50>, + + Object { + + "amount": "50", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 37, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<450>, + + Object { + + "amount": "450", + + "confirmedAt": "2023-11-06T08:36:51.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-09-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 36, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<400>, + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": "2023-11-06T08:36:50.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bob", + - "id": Any, + + "id": 34, +  "lastName": "der Baumeister", +  "memo": "Confirmed Contribution", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 32, +  "lastName": "Bloxberg", +  "memo": "Aktives Grundeinkommen", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "firstName": "Räuber", + - "id": Any, + + "id": 30, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Räuber", + - "id": Any, + + "id": 29, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<166>, + + Object { + + "amount": "166", + + "confirmedAt": "2023-11-06T08:36:48.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:48.000Z", + + "createdAt": "2023-11-06T08:36:48.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Räuber", + - "id": Any, + + "id": 28, +  "lastName": "Hotzenplotz", +  "memo": "Whatever contribution", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 27, +  "lastName": "Bloxberg", +  "memo": "Test contribution to delete", +  "messagesCount": 0, +  "status": "DELETED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": "2023-11-06T08:36:48.000Z", + + "deniedBy": 283, +  "firstName": "Bibi", + - "id": Any, + + "id": 26, +  "lastName": "Bloxberg", +  "memo": "Test contribution to deny", +  "messagesCount": 0, +  "status": "DENIED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": "2023-11-06T08:36:49.000Z", + + "confirmedBy": 283, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 25, +  "lastName": "Bloxberg", +  "memo": "Test contribution to confirm", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:46.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 24, +  "lastName": "Bloxberg", +  "memo": "Test IN_PROGRESS contribution", +  "messagesCount": 1, +  "status": "IN_PROGRESS", +  }, + - ObjectContaining { + - "amount": decimalEqual<10>, + + Object { + + "amount": "10", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:47.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 23, +  "lastName": "Bloxberg", +  "memo": "Test PENDING contribution update", + - "messagesCount": 2, + + "messagesCount": 3, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<1000>, + + Object { + + "amount": "1000", + + "confirmedAt": "2023-11-06T08:36:46.000Z", + + "confirmedBy": 283, + + "contributionDate": "2022-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:46.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Bibi", + - "id": Any, + + "id": 22, +  "lastName": "Bloxberg", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "CONFIRMED", +  }, + +   2827 | // console.log('17 contributions: %s', JSON.stringify(contributionListObject, null, 2)) +   2828 | expect(contributionListObject.contributionList).toHaveLength(18) + > 2829 | expect(contributionListObject).toMatchObject({ +   | ^ +   2830 | contributionCount: 18, +   2831 | contributionList: expect.arrayContaining([ +   2832 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:2829:40 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user + + expect(received).toMatchObject(expected) + + - Expected - 14 + + Received + 38 + +  Object { +  "contributionCount": 4, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<100>, + + "contributionList": Array [ + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T08:36:51.000Z", + + "createdAt": "2023-11-06T08:36:51.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 39, +  "lastName": "Lustig", +  "memo": "#firefighters", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<400>, + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, +  ], +  } + +   3057 | }) +   3058 | expect(contributionListObject.contributionList).toHaveLength(4) + > 3059 | expect(contributionListObject).toMatchObject({ +   | ^ +   3060 | contributionCount: 4, +   3061 | contributionList: expect.arrayContaining([ +   3062 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:3059:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user without hashtags + + expect(received).toMatchObject(expected) + + - Expected - 11 + + Received + 29 + +  Object { +  "contributionCount": 3, + - "contributionList": ArrayContaining [ + - ObjectContaining { + - "amount": decimalEqual<400>, + + "contributionList": Array [ + + Object { + + "amount": "400", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 35, +  "lastName": "Lustig", +  "memo": "Herzlich Willkommen bei Gradido!", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<100>, + + Object { + + "amount": "100", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-11-06T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:50.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 33, +  "lastName": "Lustig", +  "memo": "Test env contribution", +  "messagesCount": 0, +  "status": "PENDING", +  }, + - ObjectContaining { + - "amount": decimalEqual<200>, + + Object { + + "amount": "200", + + "confirmedAt": null, + + "confirmedBy": null, + + "contributionDate": "2023-10-01T00:00:00.000Z", + + "createdAt": "2023-11-06T08:36:49.000Z", + + "deniedAt": null, + + "deniedBy": null, +  "firstName": "Peter", + - "id": Any, + + "id": 31, +  "lastName": "Lustig", +  "memo": "Das war leider zu Viel!", + - "messagesCount": 0, + + "messagesCount": 1, +  "status": "DELETED", +  }, +  ], +  } + +   3111 | }) +   3112 | expect(contributionListObject.contributionList).toHaveLength(3) + > 3113 | expect(contributionListObject).toMatchObject({ +   | ^ +   3114 | contributionCount: 3, +   3115 | contributionList: expect.arrayContaining([ +   3116 | expect.objectContaining({ + + at src/graphql/resolver/ContributionResolver.test.ts:3113:42 + at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) + + +Test Suites: 1 failed, 21 passed, 22 total +Tests: 7 failed, 8 skipped, 482 passed, 497 total +Snapshots: 9 passed, 9 total +Time: 59.16 s +Ran all test suites. +error Command failed with exit code 1. diff --git a/backend/src/apis/DltConnectorClient.test.ts b/backend/src/apis/DltConnectorClient.test.ts index 56fa3d13f..421b957e9 100644 --- a/backend/src/apis/DltConnectorClient.test.ts +++ b/backend/src/apis/DltConnectorClient.test.ts @@ -25,8 +25,6 @@ let testEnv: { jest.mock('graphql-request', () => { const originalModule = jest.requireActual('graphql-request') - let testCursor = 0 - return { __esModule: true, ...originalModule, @@ -38,30 +36,11 @@ jest.mock('graphql-request', () => { // why not using mockResolvedValueOnce or mockReturnValueOnce? // I have tried, but it didn't work and return every time the first value request: jest.fn().mockImplementation(() => { - testCursor++ - if (testCursor === 4) { - return Promise.resolve( - // invalid, is 33 Bytes long as binary - { - transmitTransaction: { - dltTransactionIdHex: - '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc516212A', - }, - }, - ) - } else if (testCursor === 5) { - throw Error('Connection error') - } else { - return Promise.resolve( - // valid, is 32 Bytes long as binary - { - transmitTransaction: { - dltTransactionIdHex: - '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', - }, - }, - ) - } + return Promise.resolve({ + transmitTransaction: { + succeed: true, + }, + }) }), } }), @@ -134,7 +113,10 @@ describe('transmitTransaction', () => { const localTransaction = new DbTransaction() localTransaction.typeId = 12 try { - await DltConnectorClient.getInstance()?.transmitTransaction(localTransaction) + await DltConnectorClient.getInstance()?.transmitTransaction( + localTransaction, + 'senderCommunityUUID', + ) } catch (e) { expect(e).toMatchObject( new LogError('invalid transaction type id: ' + localTransaction.typeId.toString()), diff --git a/backend/src/apis/DltConnectorClient.ts b/backend/src/apis/DltConnectorClient.ts index c558da77a..14f95fbe7 100644 --- a/backend/src/apis/DltConnectorClient.ts +++ b/backend/src/apis/DltConnectorClient.ts @@ -6,6 +6,7 @@ import { CONFIG } from '@/config' import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' import { LogError } from '@/server/LogError' import { backendLogger as logger } from '@/server/logger' +import { Contribution } from '@entity/Contribution' const sendTransaction = gql` mutation ($input: TransactionInput!) { @@ -125,15 +126,14 @@ export class DltConnectorClient { transaction: DbTransaction, type: 'sender' | 'recipient', ): Promise { - const confirmingUserId = transaction.contribution?.confirmedBy - let confirmingUser: DbUser | undefined + let confirmingUserId: number | undefined logger.info('confirming user id', confirmingUserId) - if (confirmingUserId) { - confirmingUser = await DbUser.findOneOrFail({ where: { id: confirmingUserId } }) - } switch (transaction.typeId) { case TransactionTypeId.CREATION: - if (!confirmingUserId || !confirmingUser) { + confirmingUserId = ( + await Contribution.findOneOrFail({ where: { transactionId: transaction.id } }) + ).confirmedBy + if (!confirmingUserId) { throw new LogError( "couldn't find id of confirming moderator for contribution transaction!", ) @@ -170,8 +170,8 @@ export class DltConnectorClient { protected async getCorrectUserIdentifier( transaction: DbTransaction, senderCommunityUuid: string, - recipientCommunityUuid: string, type: 'sender' | 'recipient', + recipientCommunityUuid?: string, ): Promise { // sender and receiver user on creation transaction // sender user on send transaction (SEND and RECEIVE) @@ -195,7 +195,7 @@ export class DltConnectorClient { public async transmitTransaction( transaction: DbTransaction, senderCommunityUuid: string, - recipientCommunityUuid: string, + recipientCommunityUuid?: string, ): Promise { const typeString = getTransactionTypeString(transaction.typeId) // no negative values in dlt connector, gradido concept don't use negative values so the code don't use it too @@ -205,14 +205,14 @@ export class DltConnectorClient { senderUser: await this.getCorrectUserIdentifier( transaction, senderCommunityUuid, - recipientCommunityUuid, 'sender', + recipientCommunityUuid, ), recipientUser: await this.getCorrectUserIdentifier( transaction, senderCommunityUuid, - recipientCommunityUuid, 'recipient', + recipientCommunityUuid, ), amount: amountString, type: typeString, diff --git a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts index d9a2da569..05a5b44cf 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts @@ -24,6 +24,15 @@ import { CONFIG } from '@/config' import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' import { sendTransactionsToDltConnector } from './sendTransactionsToDltConnector' +import { Contribution } from '@entity/Contribution' +import { User } from '@entity/User' +import { userFactory } from '@/seeds/factory/user' +import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' +import { creations } from '@/seeds/creation' +import { creationFactory } from '@/seeds/factory/creation' +import { peterLustig } from '@/seeds/users/peter-lustig' +import { raeuberHotzenplotz } from '@/seeds/users/raeuber-hotzenplotz' +import { bobBaumeister } from '@/seeds/users/bob-baumeister' /* // Mock the GraphQLClient @@ -423,9 +432,17 @@ describe('create and send Transactions to DltConnector', () => { describe('with 3 creations and active dlt-connector', () => { it('found 3 dlt-transactions', async () => { - txCREATION1 = await createTxCREATION1(false) - txCREATION2 = await createTxCREATION2(false) - txCREATION3 = await createTxCREATION3(false) + await userFactory(testEnv, bibiBloxberg) + await userFactory(testEnv, peterLustig) + await userFactory(testEnv, raeuberHotzenplotz) + await userFactory(testEnv, bobBaumeister) + let count = 0 + for (const creation of creations) { + await creationFactory(testEnv, creation) + count++ + // we need only 3 for testing + if (count >= 3) break + } await createHomeCommunity() CONFIG.DLT_CONNECTOR = true @@ -435,10 +452,7 @@ describe('create and send Transactions to DltConnector', () => { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return { data: { - sendTransaction: { - dltTransactionIdHex: - '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', - }, + sendTransaction: { succeed: true }, }, } as Response }) @@ -464,7 +478,7 @@ describe('create and send Transactions to DltConnector', () => { expect.objectContaining({ id: expect.any(Number), transactionId: transactions[0].id, - messageId: '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', + messageId: 'sended', verified: false, createdAt: expect.any(Date), verifiedAt: null, @@ -472,7 +486,7 @@ describe('create and send Transactions to DltConnector', () => { expect.objectContaining({ id: expect.any(Number), transactionId: transactions[1].id, - messageId: '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', + messageId: 'sended', verified: false, createdAt: expect.any(Date), verifiedAt: null, @@ -480,7 +494,7 @@ describe('create and send Transactions to DltConnector', () => { expect.objectContaining({ id: expect.any(Number), transactionId: transactions[2].id, - messageId: '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', + messageId: 'sended', verified: false, createdAt: expect.any(Date), verifiedAt: null, @@ -514,10 +528,7 @@ describe('create and send Transactions to DltConnector', () => { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return { data: { - sendTransaction: { - dltTransactionIdHex: - '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', - }, + sendTransaction: { succeed: true }, }, } as Response }) @@ -569,7 +580,7 @@ describe('create and send Transactions to DltConnector', () => { expect.objectContaining({ id: expect.any(Number), transactionId: txSEND1to2.id, - messageId: '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', + messageId: 'sended', verified: false, createdAt: expect.any(Date), verifiedAt: null, @@ -577,7 +588,7 @@ describe('create and send Transactions to DltConnector', () => { expect.objectContaining({ id: expect.any(Number), transactionId: txRECEIVE2From1.id, - messageId: '723e3fab62c5d3e2f62fd72ba4e622bcd53eff35262e3f3526327fe41bc51621', + messageId: 'sended', verified: false, createdAt: expect.any(Date), verifiedAt: null, diff --git a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts index 98e1ffbe3..9c6d50725 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts @@ -23,7 +23,6 @@ export async function sendTransactionsToDltConnector(): Promise { 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({ @@ -37,27 +36,23 @@ export async function sendTransactionsToDltConnector(): Promise { continue } try { - const messageId = await dltConnector.transmitTransaction( + const result = await dltConnector.transmitTransaction( dltTx.transaction, senderCommunityUuid, - recipientCommunityUuid, ) - const dltMessageId = Buffer.from(messageId, 'hex') - if (dltMessageId.length !== 32) { - logger.error( - 'Error dlt message id is invalid: %s, should by 32 Bytes long in binary after converting from hex', - dltMessageId, - ) - return + // message id isn't known at this point of time, because transaction will not direct sended to iota, + // it will first go to db and then sended, if no transaction is in db before + if (result) { + dltTx.messageId = 'sended' + await DltTransaction.save(dltTx) + logger.info('store messageId=%s in dltTx=%d', dltTx.messageId, dltTx.id) } - dltTx.messageId = dltMessageId.toString('hex') - await DltTransaction.save(dltTx) - logger.info('store messageId=%s in dltTx=%d', dltTx.messageId, dltTx.id) } catch (e) { logger.error( `error while sending to dlt-connector or writing messageId of dltTx=${dltTx.id}`, e, ) + console.log('error', e) } } } else { diff --git a/dlt-connector/src/data/BackendTransaction.factory.ts b/dlt-connector/src/data/BackendTransaction.factory.ts new file mode 100644 index 000000000..365da0693 --- /dev/null +++ b/dlt-connector/src/data/BackendTransaction.factory.ts @@ -0,0 +1,13 @@ +import { BackendTransaction } from '@entity/BackendTransaction' + +import { TransactionDraft } from '@/graphql/input/TransactionDraft' + +export class BackendTransactionFactory { + public static createFromTransactionDraft(transactionDraft: TransactionDraft): BackendTransaction { + const backendTransaction = BackendTransaction.create() + backendTransaction.backendTransactionId = transactionDraft.backendTransactionId + backendTransaction.typeId = transactionDraft.type + backendTransaction.createdAt = new Date(transactionDraft.createdAt) + return backendTransaction + } +} diff --git a/dlt-connector/src/data/BackendTransaction.repository.ts b/dlt-connector/src/data/BackendTransaction.repository.ts new file mode 100644 index 000000000..b4e566659 --- /dev/null +++ b/dlt-connector/src/data/BackendTransaction.repository.ts @@ -0,0 +1,7 @@ +import { BackendTransaction } from '@entity/BackendTransaction' + +import { getDataSource } from '@/typeorm/DataSource' + +export const BackendTransactionRepository = getDataSource() + .getRepository(BackendTransaction) + .extend({}) diff --git a/dlt-connector/src/data/Transaction.builder.ts b/dlt-connector/src/data/Transaction.builder.ts index 7cbcedac5..115391e91 100644 --- a/dlt-connector/src/data/Transaction.builder.ts +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -4,11 +4,13 @@ import { Transaction } from '@entity/Transaction' import { GradidoTransaction } from '@/data/proto/3_3/GradidoTransaction' import { TransactionBody } from '@/data/proto/3_3/TransactionBody' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { UserIdentifier } from '@/graphql/input/UserIdentifier' import { LogError } from '@/server/LogError' import { bodyBytesToTransactionBody, transactionBodyToBodyBytes } from '@/utils/typeConverter' import { AccountRepository } from './Account.repository' +import { BackendTransactionFactory } from './BackendTransaction.factory' import { CommunityRepository } from './Community.repository' import { TransactionBodyBuilder } from './proto/TransactionBody.builder' @@ -91,8 +93,13 @@ export class TransactionBuilder { return this } - public setBackendTransactionId(backendTransactionId: number): TransactionBuilder { - this.transaction.backendTransactionId = backendTransactionId + public addBackendTransaction(transactionDraft: TransactionDraft): TransactionBuilder { + if (!this.transaction.backendTransactions) { + this.transaction.backendTransactions = [] + } + this.transaction.backendTransactions.push( + BackendTransactionFactory.createFromTransactionDraft(transactionDraft), + ) return this } diff --git a/dlt-connector/src/data/Transaction.repository.ts b/dlt-connector/src/data/Transaction.repository.ts index 9c21476ad..6ba622c9c 100644 --- a/dlt-connector/src/data/Transaction.repository.ts +++ b/dlt-connector/src/data/Transaction.repository.ts @@ -20,30 +20,21 @@ export const TransactionRepository = getDataSource() relations: { signingAccount: true }, }) }, - async findExistingTransactionAndMissingMessageIds(messageIDsHex: string[]): Promise<{ - existingTransactions: Transaction[] - missingMessageIdsHex: string[] - }> { - const existingTransactions = await this.createQueryBuilder('Transaction') + findExistingTransactionAndMissingMessageIds(messageIDsHex: string[]): Promise { + return this.createQueryBuilder('Transaction') .where('HEX(Transaction.iota_message_id) IN (:...messageIDs)', { messageIDs: messageIDsHex, }) + .leftJoinAndSelect('Transaction.community', 'Community') + .leftJoinAndSelect('Transaction.otherCommunity', 'OtherCommunity') .leftJoinAndSelect('Transaction.recipientAccount', 'RecipientAccount') + .leftJoinAndSelect('Transaction.backendTransactions', 'BackendTransactions') .leftJoinAndSelect('RecipientAccount.user', 'RecipientUser') .leftJoinAndSelect('Transaction.signingAccount', 'SigningAccount') .leftJoinAndSelect('SigningAccount.user', 'SigningUser') .getMany() - - const foundMessageIds = existingTransactions - .map((recipe) => recipe.iotaMessageId?.toString('hex')) - .filter((messageId) => !!messageId) - // find message ids for which we don't already have a transaction recipe - const missingMessageIdsHex = messageIDsHex.filter( - (id: string) => !foundMessageIds.includes(id), - ) - return { existingTransactions, missingMessageIdsHex } }, - async removeConfirmedTransaction(transactions: Transaction[]): Promise { + removeConfirmedTransaction(transactions: Transaction[]): Transaction[] { return transactions.filter( (transaction: Transaction) => transaction.runningHash === undefined || transaction.runningHash.length === 0, diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts index 4f3f3efe2..10b55573e 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -4,8 +4,8 @@ import { TransactionDraft } from '@input/TransactionDraft' import { TransactionRepository } from '@/data/Transaction.repository' import { CreateTransactionRecipeContext } from '@/interactions/backendToDb/transaction/CreateTransationRecipe.context' +import { LogError } from '@/server/LogError' -import { TransactionErrorType } from '../enum/TransactionErrorType' import { TransactionError } from '../model/TransactionError' import { TransactionRecipe } from '../model/TransactionRecipe' import { TransactionResult } from '../model/TransactionResult' @@ -21,22 +21,28 @@ export class TransactionResolver { try { await createTransactionRecipeContext.run() const transactionRecipe = createTransactionRecipeContext.getTransactionRecipe() - await transactionRecipe.save() + // check if a transaction with this signature already exist + const existingRecipe = await TransactionRepository.findBySignature( + transactionRecipe.signature, + ) + if (existingRecipe) { + // transaction recipe with this signature already exist, we need only to store the backendTransaction + if (transactionRecipe.backendTransactions.length !== 1) { + throw new LogError('unexpected backend transaction count', { + count: transactionRecipe.backendTransactions.length, + transactionId: transactionRecipe.id, + }) + } + const backendTransaction = transactionRecipe.backendTransactions[0] + backendTransaction.transactionId = transactionRecipe.id + await backendTransaction.save() + } else { + // we can store the transaction and with that automatic the backend transaction + await transactionRecipe.save() + } return new TransactionResult(new TransactionRecipe(transactionRecipe)) // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { - if (error.code === 'ER_DUP_ENTRY') { - const existingRecipe = await TransactionRepository.findBySignature( - createTransactionRecipeContext.getTransactionRecipe().signature, - ) - if (!existingRecipe) { - throw new TransactionError( - TransactionErrorType.LOGIC_ERROR, - "recipe cannot be added because signature exist but couldn't load this existing receipt", - ) - } - return new TransactionResult(new TransactionRecipe(existingRecipe)) - } if (error instanceof TransactionError) { return new TransactionResult(error) } else { diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 362d114ef..7f77a5e82 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -40,11 +40,11 @@ export class TransactionRecipeRole { .setSigningAccount(signingAccount) .setRecipientAccount(recipientAccount) .fromTransactionDraft(transactionDraft) - // build transaction entity + // build transaction entity this.transactionBuilder .fromTransactionBodyBuilder(transactionBodyBuilder) - .setBackendTransactionId(transactionDraft.backendTransactionId) + .addBackendTransaction(transactionDraft) await this.transactionBuilder.setSenderCommunityFromSenderUser(senderUser) if (recipientUser.communityUuid !== senderUser.communityUuid) { await this.transactionBuilder.setOtherCommunityFromRecipientUser(recipientUser) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts new file mode 100644 index 000000000..12b9c83cf --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts @@ -0,0 +1,45 @@ +import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne, JoinColumn } from 'typeorm' +import { Decimal } from 'decimal.js-light' + +import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +import { Transaction } from '../Transaction' + +@Entity('backend_transactions') +export class BackendTransaction extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) + id: number + + @Column({ name: 'backend_transaction_id', type: 'bigint', unsigned: true, nullable: true }) + backendTransactionId?: number + + @ManyToOne(() => Transaction, (transaction) => transaction.backendTransactions) + @JoinColumn({ name: 'transaction_id' }) + transaction?: Transaction + + @Column({ name: 'transaction_id', type: 'bigint', unsigned: true, nullable: true }) + transactionId?: number + + @Column({ name: 'type_id', unsigned: true, nullable: false }) + typeId: number + + // account balance based on creation date + @Column({ + name: 'balance', + type: 'decimal', + precision: 40, + scale: 20, + nullable: true, + transformer: DecimalTransformer, + }) + balance?: Decimal + + @Column({ name: 'created_at', type: 'datetime', precision: 3 }) + createdAt: Date + + // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here + @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) + confirmedAt?: Date + + @Column({ name: 'verifiedOnBackend', type: 'tinyint', default: false }) + verifiedOnBackend: boolean +} diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts index 3c4e7959c..922bf81cd 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -6,12 +6,14 @@ import { OneToOne, JoinColumn, BaseEntity, + OneToMany, } from 'typeorm' import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' import { Account } from '../Account' import { Community } from '../Community' +import { BackendTransaction } from '../BackendTransaction' @Entity('transactions') export class Transaction extends BaseEntity { @@ -21,9 +23,6 @@ export class Transaction extends BaseEntity { @Column({ name: 'iota_message_id', type: 'binary', length: 32, nullable: true }) iotaMessageId?: Buffer - @Column({ name: 'backend_transaction_id', type: 'bigint', unsigned: true, nullable: true }) - backendTransactionId?: number - @OneToOne(() => Transaction) // eslint-disable-next-line no-use-before-define paringTransaction?: Transaction @@ -120,4 +119,10 @@ export class Transaction extends BaseEntity { // use timestamp from iota milestone which is only in seconds precision, so no need to use 3 Bytes extra here @Column({ name: 'confirmed_at', type: 'datetime', nullable: true }) confirmedAt?: Date + + @OneToMany(() => BackendTransaction, (backendTransaction) => backendTransaction.transaction, { + cascade: ['insert', 'update'], + }) + @JoinColumn({ name: 'transaction_id' }) + backendTransactions: BackendTransaction[] } diff --git a/dlt-database/entity/BackendTransaction.ts b/dlt-database/entity/BackendTransaction.ts new file mode 100644 index 000000000..6ec68427d --- /dev/null +++ b/dlt-database/entity/BackendTransaction.ts @@ -0,0 +1 @@ +export { BackendTransaction } from './0003-refactor_transaction_recipe/BackendTransaction' diff --git a/dlt-database/entity/index.ts b/dlt-database/entity/index.ts index ba7ea2663..b1215263d 100644 --- a/dlt-database/entity/index.ts +++ b/dlt-database/entity/index.ts @@ -1,5 +1,6 @@ import { Account } from './Account' import { AccountCommunity } from './AccountCommunity' +import { BackendTransaction } from './BackendTransaction' import { Community } from './Community' import { InvalidTransaction } from './InvalidTransaction' import { Migration } from './Migration' @@ -9,6 +10,7 @@ import { User } from './User' export const entities = [ AccountCommunity, Account, + BackendTransaction, Community, InvalidTransaction, Migration, diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index cea8c3cd3..a3e8265e7 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -34,7 +34,6 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis `CREATE TABLE \`transactions\` ( \`id\` bigint unsigned NOT NULL AUTO_INCREMENT, \`iota_message_id\` varbinary(32) NULL DEFAULT NULL, - \`backend_transaction_id\` bigint unsigned NULL DEFAULT NULL, \`paring_transaction_id\` bigint unsigned NULL DEFAULT NULL, \`signing_account_id\` int unsigned NULL DEFAULT NULL, \`recipient_account_id\` int unsigned NULL DEFAULT NULL, @@ -62,6 +61,22 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis `, ) + await queryFn( + `CREATE TABLE \`backend_transactions\` ( + \`id\` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, + \`backend_transaction_id\` BIGINT UNSIGNED NOT NULL, + \`transaction_id\` BIGINT UNSIGNED NULL DEFAULT NULL, + \`type_id\` INT UNSIGNED NOT NULL, + \`balance\` DECIMAL(40, 20) NULL DEFAULT NULL, + \`created_at\` DATETIME(3) NOT NULL, + \`confirmed_at\` DATETIME NULL DEFAULT NULL, + \`verifiedOnBackend\` TINYINT NOT NULL DEFAULT 0, + PRIMARY KEY (\`id\`), + FOREIGN KEY (\`transaction_id\`) REFERENCES transactions(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `, + ) + await queryFn(`ALTER TABLE \`communities\` ADD UNIQUE(\`iota_topic\`);`) await queryFn(`ALTER TABLE \`users\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL;`) @@ -126,6 +141,7 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom await queryFn(`ALTER TABLE \`invalid_transactions\` DROP INDEX \`iota_message_id\`;`) await queryFn(`ALTER TABLE \`invalid_transactions\` ADD INDEX(\`iota_message_id\`); `) await queryFn(`DROP TABLE \`transactions\`;`) + await queryFn(`DROP TABLE \`backend_transactions\`;`) await queryFn( `ALTER TABLE \`users\` CHANGE \`created_at\` \`created_at\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, From 3b6240de1f5867592caeaed252a8232ccab4c7b4 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Thu, 28 Dec 2023 19:24:01 +0100 Subject: [PATCH 33/47] split DltConnectorClient into multiple files similar to gms client --- backend/jest.config.js | 1 + .../DltConnectorClient.test.ts | 0 .../{ => dltConnector}/DltConnectorClient.ts | 51 ++----------------- .../dltConnector/enum/TransactionErrorType.ts | 14 +++++ .../apis/dltConnector/enum/TransactionType.ts | 11 ++++ .../dltConnector/model/TransactionError.ts | 7 +++ .../dltConnector/model/TransactionRecipe.ts | 8 +++ .../dltConnector/model/TransactionResult.ts | 8 +++ .../apis/dltConnector/model/UserIdentifier.ts | 5 ++ .../sendTransactionsToDltConnector.test.ts | 12 ++--- .../util/sendTransactionsToDltConnector.ts | 4 +- backend/tsconfig.json | 1 + .../CreateTransationRecipe.context.ts | 8 ++- 13 files changed, 73 insertions(+), 57 deletions(-) rename backend/src/apis/{ => dltConnector}/DltConnectorClient.test.ts (100%) rename backend/src/apis/{ => dltConnector}/DltConnectorClient.ts (87%) create mode 100644 backend/src/apis/dltConnector/enum/TransactionErrorType.ts create mode 100644 backend/src/apis/dltConnector/enum/TransactionType.ts create mode 100644 backend/src/apis/dltConnector/model/TransactionError.ts create mode 100644 backend/src/apis/dltConnector/model/TransactionRecipe.ts create mode 100644 backend/src/apis/dltConnector/model/TransactionResult.ts create mode 100644 backend/src/apis/dltConnector/model/UserIdentifier.ts diff --git a/backend/jest.config.js b/backend/jest.config.js index 625dca00f..32606c382 100644 --- a/backend/jest.config.js +++ b/backend/jest.config.js @@ -16,6 +16,7 @@ module.exports = { moduleNameMapper: { '@/(.*)': '/src/$1', '@arg/(.*)': '/src/graphql/arg/$1', + '@dltConnector/(.*)': '/src/apis/dltConnector/$1', '@enum/(.*)': '/src/graphql/enum/$1', '@model/(.*)': '/src/graphql/model/$1', '@union/(.*)': '/src/graphql/union/$1', diff --git a/backend/src/apis/DltConnectorClient.test.ts b/backend/src/apis/dltConnector/DltConnectorClient.test.ts similarity index 100% rename from backend/src/apis/DltConnectorClient.test.ts rename to backend/src/apis/dltConnector/DltConnectorClient.test.ts diff --git a/backend/src/apis/DltConnectorClient.ts b/backend/src/apis/dltConnector/DltConnectorClient.ts similarity index 87% rename from backend/src/apis/DltConnectorClient.ts rename to backend/src/apis/dltConnector/DltConnectorClient.ts index 14f95fbe7..800834c85 100644 --- a/backend/src/apis/DltConnectorClient.ts +++ b/backend/src/apis/dltConnector/DltConnectorClient.ts @@ -1,3 +1,4 @@ +import { Contribution } from '@entity/Contribution' import { Transaction as DbTransaction } from '@entity/Transaction' import { User as DbUser } from '@entity/User' import { gql, GraphQLClient } from 'graphql-request' @@ -6,7 +7,9 @@ import { CONFIG } from '@/config' import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' import { LogError } from '@/server/LogError' import { backendLogger as logger } from '@/server/logger' -import { Contribution } from '@entity/Contribution' + +import { TransactionResult } from './model/TransactionResult' +import { UserIdentifier } from './model/UserIdentifier' const sendTransaction = gql` mutation ($input: TransactionInput!) { @@ -16,52 +19,6 @@ const sendTransaction = gql` } ` -enum TransactionType { - GRADIDO_TRANSFER = 1, - GRADIDO_CREATION = 2, - GROUP_FRIENDS_UPDATE = 3, - REGISTER_ADDRESS = 4, - GRADIDO_DEFERRED_TRANSFER = 5, - COMMUNITY_ROOT = 6, -} - -enum TransactionErrorType { - NOT_IMPLEMENTED_YET = 'Not Implemented yet', - MISSING_PARAMETER = 'Missing parameter', - ALREADY_EXIST = 'Already exist', - DB_ERROR = 'DB Error', - PROTO_DECODE_ERROR = 'Proto Decode Error', - PROTO_ENCODE_ERROR = 'Proto Encode Error', - INVALID_SIGNATURE = 'Invalid Signature', - LOGIC_ERROR = 'Logic Error', - NOT_FOUND = 'Not found', -} - -interface TransactionError { - type: TransactionErrorType - message: string - name: string -} - -interface TransactionRecipe { - id: number - createdAt: string - type: TransactionType - topic: string -} - -interface TransactionResult { - error?: TransactionError - recipe?: TransactionRecipe - succeed: boolean -} - -interface UserIdentifier { - uuid: string - communityUuid: string - accountNr?: number -} - // from ChatGPT function getTransactionTypeString(id: TransactionTypeId): string { const key = Object.keys(TransactionTypeId).find( diff --git a/backend/src/apis/dltConnector/enum/TransactionErrorType.ts b/backend/src/apis/dltConnector/enum/TransactionErrorType.ts new file mode 100644 index 000000000..5a2c5485e --- /dev/null +++ b/backend/src/apis/dltConnector/enum/TransactionErrorType.ts @@ -0,0 +1,14 @@ +/** + * Error Types for dlt-connector graphql responses + */ +export enum TransactionErrorType { + NOT_IMPLEMENTED_YET = 'Not Implemented yet', + MISSING_PARAMETER = 'Missing parameter', + ALREADY_EXIST = 'Already exist', + DB_ERROR = 'DB Error', + PROTO_DECODE_ERROR = 'Proto Decode Error', + PROTO_ENCODE_ERROR = 'Proto Encode Error', + INVALID_SIGNATURE = 'Invalid Signature', + LOGIC_ERROR = 'Logic Error', + NOT_FOUND = 'Not found', +} diff --git a/backend/src/apis/dltConnector/enum/TransactionType.ts b/backend/src/apis/dltConnector/enum/TransactionType.ts new file mode 100644 index 000000000..51b87c134 --- /dev/null +++ b/backend/src/apis/dltConnector/enum/TransactionType.ts @@ -0,0 +1,11 @@ +/** + * Transaction Types on Blockchain + */ +export enum TransactionType { + GRADIDO_TRANSFER = 1, + GRADIDO_CREATION = 2, + GROUP_FRIENDS_UPDATE = 3, + REGISTER_ADDRESS = 4, + GRADIDO_DEFERRED_TRANSFER = 5, + COMMUNITY_ROOT = 6, +} diff --git a/backend/src/apis/dltConnector/model/TransactionError.ts b/backend/src/apis/dltConnector/model/TransactionError.ts new file mode 100644 index 000000000..a2b1348a5 --- /dev/null +++ b/backend/src/apis/dltConnector/model/TransactionError.ts @@ -0,0 +1,7 @@ +import { TransactionErrorType } from '@dltConnector/enum/TransactionErrorType' + +export interface TransactionError { + type: TransactionErrorType + message: string + name: string +} diff --git a/backend/src/apis/dltConnector/model/TransactionRecipe.ts b/backend/src/apis/dltConnector/model/TransactionRecipe.ts new file mode 100644 index 000000000..edd7deadb --- /dev/null +++ b/backend/src/apis/dltConnector/model/TransactionRecipe.ts @@ -0,0 +1,8 @@ +import { TransactionType } from '@dltConnector/enum/TransactionType' + +export interface TransactionRecipe { + id: number + createdAt: string + type: TransactionType + topic: string +} diff --git a/backend/src/apis/dltConnector/model/TransactionResult.ts b/backend/src/apis/dltConnector/model/TransactionResult.ts new file mode 100644 index 000000000..510907429 --- /dev/null +++ b/backend/src/apis/dltConnector/model/TransactionResult.ts @@ -0,0 +1,8 @@ +import { TransactionError } from './TransactionError' +import { TransactionRecipe } from './TransactionRecipe' + +export interface TransactionResult { + error?: TransactionError + recipe?: TransactionRecipe + succeed: boolean +} diff --git a/backend/src/apis/dltConnector/model/UserIdentifier.ts b/backend/src/apis/dltConnector/model/UserIdentifier.ts new file mode 100644 index 000000000..e265593be --- /dev/null +++ b/backend/src/apis/dltConnector/model/UserIdentifier.ts @@ -0,0 +1,5 @@ +export interface UserIdentifier { + uuid: string + communityUuid: string + accountNr?: number +} diff --git a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts index 05a5b44cf..0d85a35af 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts @@ -22,17 +22,15 @@ import { logger, i18n as localization } from '@test/testSetup' import { CONFIG } from '@/config' import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' - -import { sendTransactionsToDltConnector } from './sendTransactionsToDltConnector' -import { Contribution } from '@entity/Contribution' -import { User } from '@entity/User' -import { userFactory } from '@/seeds/factory/user' -import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { creations } from '@/seeds/creation' import { creationFactory } from '@/seeds/factory/creation' +import { userFactory } from '@/seeds/factory/user' +import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' +import { bobBaumeister } from '@/seeds/users/bob-baumeister' import { peterLustig } from '@/seeds/users/peter-lustig' import { raeuberHotzenplotz } from '@/seeds/users/raeuber-hotzenplotz' -import { bobBaumeister } from '@/seeds/users/bob-baumeister' + +import { sendTransactionsToDltConnector } from './sendTransactionsToDltConnector' /* // Mock the GraphQLClient diff --git a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts index 9c6d50725..d381a35fc 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts @@ -3,7 +3,8 @@ import { Community } from '@entity/Community' import { DltTransaction } from '@entity/DltTransaction' import { Transaction } from '@entity/Transaction' -import { DltConnectorClient } from '@/apis/DltConnectorClient' +import { DltConnectorClient } from '@dltConnector/DltConnectorClient' + import { backendLogger as logger } from '@/server/logger' import { Monitor, MonitorNames } from '@/util/Monitor' @@ -52,7 +53,6 @@ export async function sendTransactionsToDltConnector(): Promise { `error while sending to dlt-connector or writing messageId of dltTx=${dltTx.id}`, e, ) - console.log('error', e) } } } else { diff --git a/backend/tsconfig.json b/backend/tsconfig.json index 6d27ca0fa..7e329926b 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -49,6 +49,7 @@ "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ "@/*": ["src/*"], "@arg/*": ["src/graphql/arg/*"], + "@dltConnector/*": ["src/apis/dltConnector/*"], "@enum/*": ["src/graphql/enum/*"], "@model/*": ["src/graphql/model/*"], "@union/*": ["src/graphql/union/*"], diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts index 078ec8e5c..6c65e9036 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -37,10 +37,14 @@ export class CreateTransactionRecipeContext { return this.transactionRecipeRole.getTransaction() } - public async run(): Promise { + /** + * @returns true if a transaction recipe was created and false if it wasn't necessary + */ + public async run(): Promise { if (this.draft instanceof TransactionDraft) { this.transactionRecipeRole = new TransactionRecipeRole() await this.transactionRecipeRole.create(this.draft) + return true } else if (this.draft instanceof CommunityDraft) { if (!this.community) { throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community was not set') @@ -49,6 +53,8 @@ export class CreateTransactionRecipeContext { this.draft, this.community, ) + return true } + return false } } From 374f3cd7ebcf204c34e848cda5a7957a98ebfa5f Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 29 Dec 2023 14:43:35 +0100 Subject: [PATCH 34/47] make backendTransactionId unique --- .../0003-refactor_transaction_recipe/BackendTransaction.ts | 4 ++-- dlt-database/migrations/0003-refactor_transaction_recipe.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts index 12b9c83cf..89dd3dbb0 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts @@ -9,8 +9,8 @@ export class BackendTransaction extends BaseEntity { @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) id: number - @Column({ name: 'backend_transaction_id', type: 'bigint', unsigned: true, nullable: true }) - backendTransactionId?: number + @Column({ name: 'backend_transaction_id', type: 'bigint', unsigned: true, unique: true }) + backendTransactionId: number @ManyToOne(() => Transaction, (transaction) => transaction.backendTransactions) @JoinColumn({ name: 'transaction_id' }) diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index a3e8265e7..ac427cd21 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -72,6 +72,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis \`confirmed_at\` DATETIME NULL DEFAULT NULL, \`verifiedOnBackend\` TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (\`id\`), + UNIQUE (\`backend_transaction_id\`), FOREIGN KEY (\`transaction_id\`) REFERENCES transactions(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `, From 4c178ec92ad401d088f140df760b59185fa9768c Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 29 Dec 2023 15:16:43 +0100 Subject: [PATCH 35/47] update transaction_id to not nullable --- .../0003-refactor_transaction_recipe/BackendTransaction.ts | 6 +++--- dlt-database/migrations/0003-refactor_transaction_recipe.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts index 89dd3dbb0..c84a15f41 100644 --- a/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts +++ b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts @@ -14,10 +14,10 @@ export class BackendTransaction extends BaseEntity { @ManyToOne(() => Transaction, (transaction) => transaction.backendTransactions) @JoinColumn({ name: 'transaction_id' }) - transaction?: Transaction + transaction: Transaction - @Column({ name: 'transaction_id', type: 'bigint', unsigned: true, nullable: true }) - transactionId?: number + @Column({ name: 'transaction_id', type: 'bigint', unsigned: true }) + transactionId: number @Column({ name: 'type_id', unsigned: true, nullable: false }) typeId: number diff --git a/dlt-database/migrations/0003-refactor_transaction_recipe.ts b/dlt-database/migrations/0003-refactor_transaction_recipe.ts index ac427cd21..0c022cc42 100644 --- a/dlt-database/migrations/0003-refactor_transaction_recipe.ts +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -65,7 +65,7 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis `CREATE TABLE \`backend_transactions\` ( \`id\` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, \`backend_transaction_id\` BIGINT UNSIGNED NOT NULL, - \`transaction_id\` BIGINT UNSIGNED NULL DEFAULT NULL, + \`transaction_id\` BIGINT UNSIGNED NOT NULL, \`type_id\` INT UNSIGNED NOT NULL, \`balance\` DECIMAL(40, 20) NULL DEFAULT NULL, \`created_at\` DATETIME(3) NOT NULL, From 6b64f2036cdf5c6cf88cbd5fcb62c8760b1a973d Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Sat, 30 Dec 2023 09:02:58 +0100 Subject: [PATCH 36/47] changes for review suggestions --- backend/.gitignore | 1 + dlt-connector/src/data/proto/3_3/TransactionBody.ts | 2 ++ dlt-connector/src/typeorm/DataSource.ts | 2 +- .../entity/0002-refactor_add_community/ConfirmedTransaction.ts | 1 + 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/.gitignore b/backend/.gitignore index 6eadcc884..63b375206 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -4,5 +4,6 @@ /build/ package-json.lock coverage +log.txt # emacs *~ diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 70199c03c..a4169b488 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -126,12 +126,14 @@ export class TransactionBody extends Message { public getRecipientPublicKey(): Buffer | undefined { if (this.transfer) { + // this.transfer.recipient contains the publicKey of the recipient return this.transfer.recipient } if (this.creation) { return this.creation.recipient.pubkey } if (this.deferredTransfer) { + // this.deferredTransfer.transfer.recipient contains the publicKey of the recipient return this.deferredTransfer.transfer.recipient } return undefined diff --git a/dlt-connector/src/typeorm/DataSource.ts b/dlt-connector/src/typeorm/DataSource.ts index 18be65300..ecdfc1b66 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -59,7 +59,7 @@ export class Connection { public async init(): Promise { await this.connection.initialize() try { - await Connection.getInstance() + Connection.getInstance() } catch (error) { // try and catch for logging logger.fatal(`Couldn't open connection to database!`) diff --git a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts index e973f9571..1cdc591bf 100644 --- a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts +++ b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts @@ -10,6 +10,7 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' +// the relation in future account don't match which this any longer, so we can only link with the local account here import { Account } from './Account' // TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked import { TransactionRecipe } from '../0001-init_db/TransactionRecipe' From 9cfd0f973dbb2620bc22d2f55e0b67e60202d6e1 Mon Sep 17 00:00:00 2001 From: Einhornimmond Date: Sat, 30 Dec 2023 09:17:14 +0100 Subject: [PATCH 37/47] lint --- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index a4169b488..1fd58105f 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -126,14 +126,14 @@ export class TransactionBody extends Message { public getRecipientPublicKey(): Buffer | undefined { if (this.transfer) { - // this.transfer.recipient contains the publicKey of the recipient + // this.transfer.recipient contains the publicKey of the recipient return this.transfer.recipient } if (this.creation) { return this.creation.recipient.pubkey } if (this.deferredTransfer) { - // this.deferredTransfer.transfer.recipient contains the publicKey of the recipient + // this.deferredTransfer.transfer.recipient contains the publicKey of the recipient return this.deferredTransfer.transfer.recipient } return undefined From 6f5d69c0303be5443ec07faad5b1e18fe4c3f4d8 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 11:12:51 +0100 Subject: [PATCH 38/47] update also linked gradido id and linked name --- backend/src/config/index.ts | 2 +- .../graphql/resolver/ContributionResolver.ts | 4 +++- ..._linked_user_gradidoId_of_contributions.ts | 19 +++++++++++++++++++ dht-node/src/config/index.ts | 2 +- federation/src/config/index.ts | 2 +- 5 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index ed415da08..8960b9e97 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -12,7 +12,7 @@ Decimal.set({ }) const constants = { - DB_VERSION: '0079-fill_linked_user_id_of_contributions', + DB_VERSION: '0080-0080-fill_linked_user_gradidoId_of_contributions', DECAY_START_TIME: new Date('2021-05-13 17:46:31-0000'), // GMT+0 LOG4JS_CONFIG: 'log4js-config.json', // default log level on production should be info diff --git a/backend/src/graphql/resolver/ContributionResolver.ts b/backend/src/graphql/resolver/ContributionResolver.ts index c07a691a3..850a715b7 100644 --- a/backend/src/graphql/resolver/ContributionResolver.ts +++ b/backend/src/graphql/resolver/ContributionResolver.ts @@ -451,7 +451,9 @@ export class ContributionResolver { transaction.userId = contribution.userId transaction.userGradidoID = user.gradidoID transaction.userName = fullName(user.firstName, user.lastName) - transaction.linkedUserId = contribution.moderatorId + transaction.linkedUserId = moderatorUser.id + transaction.linkedUserGradidoID = moderatorUser.gradidoID + transaction.linkedUserName = fullName(moderatorUser.firstName, moderatorUser.lastName) transaction.previous = lastTransaction ? lastTransaction.id : null transaction.amount = contribution.amount transaction.creationDate = contribution.contributionDate diff --git a/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts new file mode 100644 index 000000000..ab76a09d6 --- /dev/null +++ b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts @@ -0,0 +1,19 @@ +export async function upgrade(queryFn: (query: string, values?: any[]) => Promise>) { + await queryFn( + `UPDATE \`transactions\` AS t + JOIN \`contributions\` AS c ON t.id = c.transaction_id + JOIN \`users\` AS u ON u.id = c.confirmed_by + SET + t.linked_user_gradido_id = u.gradido_id, + t.linked_user_name = CONCAT(u.first_name, ' ', u.last_name) + WHERE t.type_id = ?`, + [1], + ) +} + +export async function downgrade(queryFn: (query: string, values?: any[]) => Promise>) { + await queryFn( + `UPDATE \`transactions\` SET \`linked_user_gradido_id\` = NULL, \`linked_user_name\` = NULL where \`type_id\` = ?;`, + [1], + ) +} diff --git a/dht-node/src/config/index.ts b/dht-node/src/config/index.ts index b0661126f..3459ec058 100644 --- a/dht-node/src/config/index.ts +++ b/dht-node/src/config/index.ts @@ -4,7 +4,7 @@ import dotenv from 'dotenv' dotenv.config() const constants = { - DB_VERSION: '0079-fill_linked_user_id_of_contributions', + DB_VERSION: '0080-fill_linked_user_gradidoId_of_contributions', LOG4JS_CONFIG: 'log4js-config.json', // default log level on production should be info LOG_LEVEL: process.env.LOG_LEVEL || 'info', diff --git a/federation/src/config/index.ts b/federation/src/config/index.ts index 9ce6f18e3..5f1b2e0c6 100644 --- a/federation/src/config/index.ts +++ b/federation/src/config/index.ts @@ -10,7 +10,7 @@ Decimal.set({ }) const constants = { - DB_VERSION: '0079-fill_linked_user_id_of_contributions', + DB_VERSION: '0080-fill_linked_user_gradidoId_of_contributions', DECAY_START_TIME: new Date('2021-05-13 17:46:31-0000'), // GMT+0 LOG4JS_CONFIG: 'log4js-config.json', // default log level on production should be info From d0d18518d361a93432ff979e31f919b883758612 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 11:21:08 +0100 Subject: [PATCH 39/47] fix spelling --- backend/src/config/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 8960b9e97..7fbc0aae0 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -12,7 +12,7 @@ Decimal.set({ }) const constants = { - DB_VERSION: '0080-0080-fill_linked_user_gradidoId_of_contributions', + DB_VERSION: '0080-fill_linked_user_gradidoId_of_contributions', DECAY_START_TIME: new Date('2021-05-13 17:46:31-0000'), // GMT+0 LOG4JS_CONFIG: 'log4js-config.json', // default log level on production should be info From 1300e9670d87b6190bd3cbaa1925a177429771de Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 11:52:11 +0100 Subject: [PATCH 40/47] add community uuid --- .../resolver/ContributionResolver.test.ts | 2 +- .../graphql/resolver/ContributionResolver.ts | 1 + .../src/graphql/resolver/TransactionResolver.ts | 4 ++++ ...ll_linked_user_gradidoId_of_contributions.ts | 17 ++++++++++++++++- 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/backend/src/graphql/resolver/ContributionResolver.test.ts b/backend/src/graphql/resolver/ContributionResolver.test.ts index 8b2bf141e..a188c5d2c 100644 --- a/backend/src/graphql/resolver/ContributionResolver.test.ts +++ b/backend/src/graphql/resolver/ContributionResolver.test.ts @@ -2609,7 +2609,7 @@ describe('ContributionResolver', () => { expect(transaction[0].linkedTransactionId).toEqual(null) expect(transaction[0].transactionLinkId).toEqual(null) expect(transaction[0].previous).toEqual(null) - expect(transaction[0].linkedUserId).toEqual(null) + expect(transaction[0].linkedUserId).toEqual(admin.id) expect(transaction[0].typeId).toEqual(1) }) diff --git a/backend/src/graphql/resolver/ContributionResolver.ts b/backend/src/graphql/resolver/ContributionResolver.ts index 850a715b7..d560d3ade 100644 --- a/backend/src/graphql/resolver/ContributionResolver.ts +++ b/backend/src/graphql/resolver/ContributionResolver.ts @@ -454,6 +454,7 @@ export class ContributionResolver { transaction.linkedUserId = moderatorUser.id transaction.linkedUserGradidoID = moderatorUser.gradidoID transaction.linkedUserName = fullName(moderatorUser.firstName, moderatorUser.lastName) + transaction.linkedUserCommunityUuid = moderatorUser.communityUuid transaction.previous = lastTransaction ? lastTransaction.id : null transaction.amount = contribution.amount transaction.creationDate = contribution.contributionDate diff --git a/backend/src/graphql/resolver/TransactionResolver.ts b/backend/src/graphql/resolver/TransactionResolver.ts index d379efef3..b4fd5c4e3 100644 --- a/backend/src/graphql/resolver/TransactionResolver.ts +++ b/backend/src/graphql/resolver/TransactionResolver.ts @@ -109,9 +109,11 @@ export const executeTransaction = async ( transactionSend.userId = sender.id transactionSend.userGradidoID = sender.gradidoID transactionSend.userName = fullName(sender.firstName, sender.lastName) + transactionSend.userCommunityUuid = sender.communityUuid transactionSend.linkedUserId = recipient.id transactionSend.linkedUserGradidoID = recipient.gradidoID transactionSend.linkedUserName = fullName(recipient.firstName, recipient.lastName) + transactionSend.linkedUserCommunityUuid = recipient.communityUuid transactionSend.amount = amount.mul(-1) transactionSend.balance = sendBalance.balance transactionSend.balanceDate = receivedCallDate @@ -129,9 +131,11 @@ export const executeTransaction = async ( transactionReceive.userId = recipient.id transactionReceive.userGradidoID = recipient.gradidoID transactionReceive.userName = fullName(recipient.firstName, recipient.lastName) + transactionReceive.userCommunityUuid = recipient.communityUuid transactionReceive.linkedUserId = sender.id transactionReceive.linkedUserGradidoID = sender.gradidoID transactionReceive.linkedUserName = fullName(sender.firstName, sender.lastName) + transactionReceive.linkedUserCommunityUuid = sender.communityUuid transactionReceive.amount = amount const receiveBalance = await calculateBalance(recipient.id, amount, receivedCallDate) transactionReceive.balance = receiveBalance ? receiveBalance.balance : amount diff --git a/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts index ab76a09d6..815d2e113 100644 --- a/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts +++ b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts @@ -5,10 +5,21 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis JOIN \`users\` AS u ON u.id = c.confirmed_by SET t.linked_user_gradido_id = u.gradido_id, - t.linked_user_name = CONCAT(u.first_name, ' ', u.last_name) + t.linked_user_name = CONCAT(u.first_name, ' ', u.last_name), + t.linked_user_community_uuid = u.community_uuid WHERE t.type_id = ?`, [1], ) + + // fill user community uuid fields in transactions + await queryFn( + `UPDATE \`transactions\` AS t + JOIN \`users\` AS u ON u.id = t.user_id, + JOIN \`users\` AS lu ON lu.id = t.linked_user_id, + SET + t.user_community_uuid = u.community_uuid, + t.linked_user_community_uuid = lu.community_uuid`, + ) } export async function downgrade(queryFn: (query: string, values?: any[]) => Promise>) { @@ -16,4 +27,8 @@ export async function downgrade(queryFn: (query: string, values?: any[]) => Prom `UPDATE \`transactions\` SET \`linked_user_gradido_id\` = NULL, \`linked_user_name\` = NULL where \`type_id\` = ?;`, [1], ) + + await queryFn( + `UPDATE \`transactions\` SET \`user_community_uuid\` = NULL, \`linked_user_community_uuid\` = NULL;`, + ) } From 01bd9ac7ff0276b5779252f4783fdb8f16bb7076 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 11:53:37 +0100 Subject: [PATCH 41/47] fill also user_community_id on contributions --- backend/src/graphql/resolver/ContributionResolver.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/src/graphql/resolver/ContributionResolver.ts b/backend/src/graphql/resolver/ContributionResolver.ts index d560d3ade..5684835e4 100644 --- a/backend/src/graphql/resolver/ContributionResolver.ts +++ b/backend/src/graphql/resolver/ContributionResolver.ts @@ -451,6 +451,7 @@ export class ContributionResolver { transaction.userId = contribution.userId transaction.userGradidoID = user.gradidoID transaction.userName = fullName(user.firstName, user.lastName) + transaction.userCommunityUuid = user.communityUuid transaction.linkedUserId = moderatorUser.id transaction.linkedUserGradidoID = moderatorUser.gradidoID transaction.linkedUserName = fullName(moderatorUser.firstName, moderatorUser.lastName) From de2384d8a7ea2338fcff2b48f2958b174d286676 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 12:40:17 +0100 Subject: [PATCH 42/47] fix mysql syntax error --- .../0080-fill_linked_user_gradidoId_of_contributions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts index 815d2e113..ae5ef6ccf 100644 --- a/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts +++ b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts @@ -14,8 +14,8 @@ export async function upgrade(queryFn: (query: string, values?: any[]) => Promis // fill user community uuid fields in transactions await queryFn( `UPDATE \`transactions\` AS t - JOIN \`users\` AS u ON u.id = t.user_id, - JOIN \`users\` AS lu ON lu.id = t.linked_user_id, + JOIN \`users\` AS u ON u.id = t.user_id + JOIN \`users\` AS lu ON lu.id = t.linked_user_id SET t.user_community_uuid = u.community_uuid, t.linked_user_community_uuid = lu.community_uuid`, From 75a7481a1b5859540e55c378db950d6bf09ed19b Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 15:53:23 +0100 Subject: [PATCH 43/47] adjust backend to moving logic into dlt-connector --- .../apis/dltConnector/DltConnectorClient.ts | 94 ++----------------- .../util/sendTransactionsToDltConnector.ts | 12 +-- 2 files changed, 10 insertions(+), 96 deletions(-) diff --git a/backend/src/apis/dltConnector/DltConnectorClient.ts b/backend/src/apis/dltConnector/DltConnectorClient.ts index 800834c85..765d09fb4 100644 --- a/backend/src/apis/dltConnector/DltConnectorClient.ts +++ b/backend/src/apis/dltConnector/DltConnectorClient.ts @@ -1,6 +1,4 @@ -import { Contribution } from '@entity/Contribution' import { Transaction as DbTransaction } from '@entity/Transaction' -import { User as DbUser } from '@entity/User' import { gql, GraphQLClient } from 'graphql-request' import { CONFIG } from '@/config' @@ -79,98 +77,24 @@ export class DltConnectorClient { return DltConnectorClient.instance } - protected async getCorrectUserUUID( - transaction: DbTransaction, - type: 'sender' | 'recipient', - ): Promise { - let confirmingUserId: number | undefined - logger.info('confirming user id', confirmingUserId) - switch (transaction.typeId) { - case TransactionTypeId.CREATION: - confirmingUserId = ( - await Contribution.findOneOrFail({ where: { transactionId: transaction.id } }) - ).confirmedBy - if (!confirmingUserId) { - throw new LogError( - "couldn't find id of confirming moderator for contribution transaction!", - ) - } - if (type === 'sender') { - return (await DbUser.findOneOrFail({ where: { id: confirmingUserId } })).gradidoID - } else if (type === 'recipient') { - return transaction.userGradidoID - } - break - case TransactionTypeId.SEND: - if (type === 'sender') { - return transaction.userGradidoID - } else if (type === 'recipient') { - if (!transaction.linkedUserGradidoID) { - throw new LogError('missing linked user gradido id') - } - return transaction.linkedUserGradidoID - } - break - case TransactionTypeId.RECEIVE: - if (type === 'sender') { - if (!transaction.linkedUserGradidoID) { - throw new LogError('missing linked user gradido id') - } - return transaction.linkedUserGradidoID - } else if (type === 'recipient') { - return transaction.userGradidoID - } - } - throw new LogError('unhandled case') - } - - protected async getCorrectUserIdentifier( - transaction: DbTransaction, - senderCommunityUuid: string, - type: 'sender' | 'recipient', - recipientCommunityUuid?: string, - ): Promise { - // sender and receiver user on creation transaction - // sender user on send transaction (SEND and RECEIVE) - if (type === 'sender' || transaction.typeId === TransactionTypeId.CREATION) { - return { - uuid: await this.getCorrectUserUUID(transaction, type), - communityUuid: senderCommunityUuid, - } - } - // recipient user on SEND and RECEIVE transactions - return { - uuid: await this.getCorrectUserUUID(transaction, type), - communityUuid: recipientCommunityUuid ?? senderCommunityUuid, - } - } - /** * transmit transaction via dlt-connector to iota * and update dltTransactionId of transaction in db with iota message id */ - public async transmitTransaction( - transaction: DbTransaction, - senderCommunityUuid: string, - recipientCommunityUuid?: string, - ): Promise { + public async transmitTransaction(transaction: DbTransaction): Promise { const typeString = getTransactionTypeString(transaction.typeId) // no negative values in dlt connector, gradido concept don't use negative values so the code don't use it too const amountString = transaction.amount.abs().toString() const params = { input: { - senderUser: await this.getCorrectUserIdentifier( - transaction, - senderCommunityUuid, - 'sender', - recipientCommunityUuid, - ), - recipientUser: await this.getCorrectUserIdentifier( - transaction, - senderCommunityUuid, - 'recipient', - recipientCommunityUuid, - ), + user: { + uuid: transaction.userGradidoID, + communityUuid: transaction.userCommunityUuid, + } as UserIdentifier, + linkedUser: { + uuid: transaction.linkedUserGradidoID, + communityUuid: transaction.linkedUserCommunityUuid, + } as UserIdentifier, amount: amountString, type: typeString, createdAt: transaction.balanceDate.toISOString(), diff --git a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts index d381a35fc..733c12594 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts @@ -1,5 +1,4 @@ import { IsNull } from '@dbTools/typeorm' -import { Community } from '@entity/Community' import { DltTransaction } from '@entity/DltTransaction' import { Transaction } from '@entity/Transaction' @@ -18,12 +17,6 @@ export async function sendTransactionsToDltConnector(): Promise { 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') - } if (dltConnector) { logger.debug('with sending to DltConnector...') const dltTransactions = await DltTransaction.find({ @@ -37,10 +30,7 @@ export async function sendTransactionsToDltConnector(): Promise { continue } try { - const result = await dltConnector.transmitTransaction( - dltTx.transaction, - senderCommunityUuid, - ) + const result = await dltConnector.transmitTransaction(dltTx.transaction) // message id isn't known at this point of time, because transaction will not direct sended to iota, // it will first go to db and then sended, if no transaction is in db before if (result) { From ed4e46a14a769c8c26829c8dfbb43397d3880ec7 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 15:54:02 +0100 Subject: [PATCH 44/47] move translation logic from backend into dlt-connector, refactor --- .../src/data/proto/3_3/TransactionBody.ts | 14 +---- .../src/data/proto/TransactionBody.builder.ts | 21 +++++++ .../src/data/proto/transactionBody.logic.ts | 57 ----------------- .../src/graphql/input/TransactionDraft.ts | 4 +- .../resolver/TransactionsResolver.test.ts | 28 ++++----- .../community/HomeCommunity.role.ts | 3 +- .../transaction/AbstractTransaction.role.ts | 62 +++++++++++++++++++ .../CreateTransationRecipe.context.ts | 41 +++++++----- .../transaction/CreationTransaction.role.ts | 18 ++++++ .../transaction/ReceiveTransaction.role.ts | 21 +++++++ .../transaction/SendTransaction.role.ts | 21 +++++++ .../transaction/TransactionRecipe.role.ts | 19 ++++-- 12 files changed, 199 insertions(+), 110 deletions(-) delete mode 100644 dlt-connector/src/data/proto/transactionBody.logic.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/AbstractTransaction.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/CreationTransaction.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/ReceiveTransaction.role.ts create mode 100644 dlt-connector/src/interactions/backendToDb/transaction/SendTransaction.role.ts diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index 1fd58105f..c30d2a6e7 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -7,7 +7,6 @@ import { LogError } from '@/server/LogError' import { timestampToDate } from '@/utils/typeConverter' import { AbstractTransaction } from '../AbstractTransaction' -import { determineCrossGroupType, determineOtherGroup } from '../transactionBody.logic' import { CommunityRoot } from './CommunityRoot' import { PROTO_TRANSACTION_BODY_VERSION_NUMBER } from './const' @@ -25,19 +24,12 @@ import { Timestamp } from './Timestamp' export class TransactionBody extends Message { public constructor(transaction?: TransactionDraft | CommunityDraft) { if (transaction) { - let type = CrossGroupType.LOCAL - let otherGroup = '' - if (transaction instanceof TransactionDraft) { - type = determineCrossGroupType(transaction) - otherGroup = determineOtherGroup(type, transaction) - } - super({ memo: 'Not implemented yet', createdAt: new Timestamp(new Date(transaction.createdAt)), versionNumber: PROTO_TRANSACTION_BODY_VERSION_NUMBER, - type, - otherGroup, + type: CrossGroupType.LOCAL, + otherGroup: '', }) } else { super() @@ -126,14 +118,12 @@ export class TransactionBody extends Message { public getRecipientPublicKey(): Buffer | undefined { if (this.transfer) { - // this.transfer.recipient contains the publicKey of the recipient return this.transfer.recipient } if (this.creation) { return this.creation.recipient.pubkey } if (this.deferredTransfer) { - // this.deferredTransfer.transfer.recipient contains the publicKey of the recipient return this.deferredTransfer.transfer.recipient } return undefined diff --git a/dlt-connector/src/data/proto/TransactionBody.builder.ts b/dlt-connector/src/data/proto/TransactionBody.builder.ts index cf9479015..22d943d48 100644 --- a/dlt-connector/src/data/proto/TransactionBody.builder.ts +++ b/dlt-connector/src/data/proto/TransactionBody.builder.ts @@ -7,6 +7,7 @@ import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { LogError } from '@/server/LogError' import { CommunityRoot } from './3_3/CommunityRoot' +import { CrossGroupType } from './3_3/enum/CrossGroupType' import { GradidoCreation } from './3_3/GradidoCreation' import { GradidoTransfer } from './3_3/GradidoTransfer' import { TransactionBody } from './3_3/TransactionBody' @@ -78,6 +79,26 @@ export class TransactionBodyBuilder { return this } + public setCrossGroupType(type: CrossGroupType): this { + if (!this.body) { + throw new LogError( + 'body is undefined, please call fromTransactionDraft or fromCommunityDraft before', + ) + } + this.body.type = type + return this + } + + public setOtherGroup(otherGroup: string): this { + if (!this.body) { + throw new LogError( + 'body is undefined, please call fromTransactionDraft or fromCommunityDraft before', + ) + } + this.body.otherGroup = otherGroup + return this + } + public fromTransactionDraft(transactionDraft: TransactionDraft): TransactionBodyBuilder { this.body = new TransactionBody(transactionDraft) // TODO: load pubkeys for sender and recipient user from db diff --git a/dlt-connector/src/data/proto/transactionBody.logic.ts b/dlt-connector/src/data/proto/transactionBody.logic.ts deleted file mode 100644 index 99dbc2ed6..000000000 --- a/dlt-connector/src/data/proto/transactionBody.logic.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { InputTransactionType } from '@/graphql/enum/InputTransactionType' -import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { TransactionError } from '@/graphql/model/TransactionError' - -import { CrossGroupType } from './3_3/enum/CrossGroupType' - -export const determineCrossGroupType = ({ - senderUser, - recipientUser, - type, -}: TransactionDraft): CrossGroupType => { - if ( - !recipientUser.communityUuid || - recipientUser.communityUuid === '' || - senderUser.communityUuid === recipientUser.communityUuid || - type === InputTransactionType.CREATION - ) { - return CrossGroupType.LOCAL - } else if (type === InputTransactionType.SEND) { - return CrossGroupType.INBOUND - } else if (type === InputTransactionType.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 - case CrossGroupType.CROSS: - throw new TransactionError(TransactionErrorType.NOT_IMPLEMENTED_YET, 'not implemented yet') - } -} diff --git a/dlt-connector/src/graphql/input/TransactionDraft.ts b/dlt-connector/src/graphql/input/TransactionDraft.ts index 7c43e9554..541797565 100755 --- a/dlt-connector/src/graphql/input/TransactionDraft.ts +++ b/dlt-connector/src/graphql/input/TransactionDraft.ts @@ -14,12 +14,12 @@ export class TransactionDraft { @Field(() => UserIdentifier) @IsObject() @ValidateNested() - senderUser: UserIdentifier + user: UserIdentifier @Field(() => UserIdentifier) @IsObject() @ValidateNested() - recipientUser: UserIdentifier + linkedUser: UserIdentifier @Field(() => Int) @IsPositive() diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index b5d5ee126..6eb443e21 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -62,8 +62,8 @@ const createUserStoreAccount = async (uuid: string): Promise => } describe('Transaction Resolver Test', () => { - let senderUser: UserIdentifier - let recipientUser: UserIdentifier + let user: UserIdentifier + let linkedUser: UserIdentifier beforeAll(async () => { await TestDB.instance.setupTestDB() apolloTestServer = await createApolloTestServer() @@ -74,8 +74,8 @@ describe('Transaction Resolver Test', () => { communityDraft.createdAt = new Date().toString() const addCommunityContext = new AddCommunityContext(communityDraft) await addCommunityContext.run() - senderUser = await createUserStoreAccount('0ec72b74-48c2-446f-91ce-31ad7d9f4d65') - recipientUser = await createUserStoreAccount('ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe') + user = await createUserStoreAccount('0ec72b74-48c2-446f-91ce-31ad7d9f4d65') + linkedUser = await createUserStoreAccount('ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe') }) afterAll(async () => { @@ -88,8 +88,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {succeed, recipe { id, topic }} }', variables: { input: { - senderUser, - recipientUser, + user, + linkedUser, type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: '10', createdAt: '2012-04-17T17:12:00Z', @@ -110,8 +110,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser, - recipientUser, + user, + linkedUser, type: 'INVALID', amount: '10', createdAt: '2012-04-17T17:12:00Z', @@ -136,8 +136,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser, - recipientUser, + user, + linkedUser, type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: 'no number', createdAt: '2012-04-17T17:12:00Z', @@ -162,8 +162,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser, - recipientUser, + user, + linkedUser, type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: '10', createdAt: 'not valid', @@ -198,8 +198,8 @@ describe('Transaction Resolver Test', () => { 'mutation ($input: TransactionDraft!) { sendTransaction(data: $input) {error {type, message}, succeed} }', variables: { input: { - senderUser, - recipientUser, + user, + linkedUser, type: getEnumValue(InputTransactionType, InputTransactionType.CREATION), amount: '10', createdAt: '2012-04-17T17:12:00Z', diff --git a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts index 0b134b97c..256cfe1a5 100644 --- a/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -28,8 +28,7 @@ export class HomeCommunityRole extends CommunityRole { this.self.aufAccount = AccountFactory.createAufAccount(keyPair, this.self.createdAt) this.self.gmwAccount = AccountFactory.createGmwAccount(keyPair, this.self.createdAt) - const transactionRecipeContext = new CreateTransactionRecipeContext(communityDraft) - transactionRecipeContext.setCommunity(this.self) + const transactionRecipeContext = new CreateTransactionRecipeContext(communityDraft, this.self) await transactionRecipeContext.run() this.transactionRecipe = transactionRecipeContext.getTransactionRecipe() } diff --git a/dlt-connector/src/interactions/backendToDb/transaction/AbstractTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/AbstractTransaction.role.ts new file mode 100644 index 000000000..62fcf90de --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/AbstractTransaction.role.ts @@ -0,0 +1,62 @@ +import { CrossGroupType } from '@/data/proto/3_3/enum/CrossGroupType' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' +import { TransactionError } from '@/graphql/model/TransactionError' + +export abstract class AbstractTransactionRole { + // eslint-disable-next-line no-useless-constructor + public constructor(protected self: TransactionDraft) {} + + abstract getSigningUser(): UserIdentifier + abstract getRecipientUser(): UserIdentifier + abstract getCrossGroupType(): CrossGroupType + + public isCrossGroupTransaction(): boolean { + return ( + this.self.user.communityUuid !== this.self.linkedUser.communityUuid && + this.self.linkedUser.communityUuid !== '' + ) + } + + /** + * otherGroup is the group/community on which this part of the transaction isn't stored + * Alice from 'gdd1' Send 10 GDD to Bob in 'gdd2' + * OUTBOUND came from sender, stored on sender community blockchain + * OUTBOUND: stored on 'gdd1', otherGroup: 'gdd2' + * INBOUND: goes to receiver, stored on receiver community blockchain + * INBOUND: stored on 'gdd2', otherGroup: 'gdd1' + * @returns + */ + public getOtherGroup(): string { + let user: UserIdentifier + const type = this.getCrossGroupType() + switch (type) { + case CrossGroupType.LOCAL: + return '' + case CrossGroupType.INBOUND: + user = this.getSigningUser() + if (!user.communityUuid) { + throw new TransactionError( + TransactionErrorType.MISSING_PARAMETER, + 'missing sender/signing user community id for cross group transaction', + ) + } + return user.communityUuid + case CrossGroupType.OUTBOUND: + user = this.getRecipientUser() + if (!user.communityUuid) { + throw new TransactionError( + TransactionErrorType.MISSING_PARAMETER, + 'missing recipient user community id for cross group transaction', + ) + } + return user.communityUuid + default: + throw new TransactionError( + TransactionErrorType.NOT_IMPLEMENTED_YET, + `type not implemented yet ${type}`, + ) + } + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts index 6c65e9036..8fa3dc443 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -1,12 +1,17 @@ import { Community } from '@entity/Community' import { Transaction } from '@entity/Transaction' +import { InputTransactionType } from '@/graphql/enum/InputTransactionType' import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { CommunityDraft } from '@/graphql/input/CommunityDraft' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' +import { AbstractTransactionRole } from './AbstractTransaction.role' import { CommunityRootTransactionRole } from './CommunityRootTransaction.role' +import { CreationTransactionRole } from './CreationTransaction.role' +import { ReceiveTransactionRole } from './ReceiveTransaction.role' +import { SendTransactionRole } from './SendTransaction.role' import { TransactionRecipeRole } from './TransactionRecipe.role' /** @@ -16,22 +21,11 @@ import { TransactionRecipeRole } from './TransactionRecipe.role' export class CreateTransactionRecipeContext { private transactionRecipeRole: TransactionRecipeRole - private community?: Community - public constructor(private draft: CommunityDraft | TransactionDraft) { - if (draft instanceof CommunityDraft) { - this.transactionRecipeRole = new CommunityRootTransactionRole() - } else if (draft instanceof TransactionDraft) { - this.transactionRecipeRole = new TransactionRecipeRole() - } - } - - public setCommunity(community: Community) { - this.community = community - } - - public getCommunity(): Community | undefined { - return this.community - } + // eslint-disable-next-line no-useless-constructor + public constructor( + private draft: CommunityDraft | TransactionDraft, + private community?: Community, + ) {} public getTransactionRecipe(): Transaction { return this.transactionRecipeRole.getTransaction() @@ -43,7 +37,20 @@ export class CreateTransactionRecipeContext { public async run(): Promise { if (this.draft instanceof TransactionDraft) { this.transactionRecipeRole = new TransactionRecipeRole() - await this.transactionRecipeRole.create(this.draft) + // contain logic for translation from backend to dlt-connector format + let transactionTypeRole: AbstractTransactionRole + switch (this.draft.type) { + case InputTransactionType.CREATION: + transactionTypeRole = new CreationTransactionRole(this.draft) + break + case InputTransactionType.SEND: + transactionTypeRole = new SendTransactionRole(this.draft) + break + case InputTransactionType.RECEIVE: + transactionTypeRole = new ReceiveTransactionRole(this.draft) + break + } + await this.transactionRecipeRole.create(this.draft, transactionTypeRole) return true } else if (this.draft instanceof CommunityDraft) { if (!this.community) { diff --git a/dlt-connector/src/interactions/backendToDb/transaction/CreationTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CreationTransaction.role.ts new file mode 100644 index 000000000..7b82f8805 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreationTransaction.role.ts @@ -0,0 +1,18 @@ +import { CrossGroupType } from '@/data/proto/3_3/enum/CrossGroupType' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' + +import { AbstractTransactionRole } from './AbstractTransaction.role' + +export class CreationTransactionRole extends AbstractTransactionRole { + public getSigningUser(): UserIdentifier { + return this.self.linkedUser + } + + public getRecipientUser(): UserIdentifier { + return this.self.user + } + + public getCrossGroupType(): CrossGroupType { + return CrossGroupType.LOCAL + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/ReceiveTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/ReceiveTransaction.role.ts new file mode 100644 index 000000000..bf7c69f0e --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/ReceiveTransaction.role.ts @@ -0,0 +1,21 @@ +import { CrossGroupType } from '@/data/proto/3_3/enum/CrossGroupType' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' + +import { AbstractTransactionRole } from './AbstractTransaction.role' + +export class ReceiveTransactionRole extends AbstractTransactionRole { + public getSigningUser(): UserIdentifier { + return this.self.linkedUser + } + + public getRecipientUser(): UserIdentifier { + return this.self.user + } + + public getCrossGroupType(): CrossGroupType { + if (this.isCrossGroupTransaction()) { + return CrossGroupType.INBOUND + } + return CrossGroupType.LOCAL + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/SendTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/SendTransaction.role.ts new file mode 100644 index 000000000..927efdc24 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/SendTransaction.role.ts @@ -0,0 +1,21 @@ +import { CrossGroupType } from '@/data/proto/3_3/enum/CrossGroupType' +import { UserIdentifier } from '@/graphql/input/UserIdentifier' + +import { AbstractTransactionRole } from './AbstractTransaction.role' + +export class SendTransactionRole extends AbstractTransactionRole { + public getSigningUser(): UserIdentifier { + return this.self.user + } + + public getRecipientUser(): UserIdentifier { + return this.self.linkedUser + } + + public getCrossGroupType(): CrossGroupType { + if (this.isCrossGroupTransaction()) { + return CrossGroupType.OUTBOUND + } + return CrossGroupType.LOCAL + } +} diff --git a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts index 7f77a5e82..d36aa98cc 100644 --- a/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -8,6 +8,8 @@ import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' import { TransactionDraft } from '@/graphql/input/TransactionDraft' import { TransactionError } from '@/graphql/model/TransactionError' +import { AbstractTransactionRole } from './AbstractTransaction.role' + export class TransactionRecipeRole { protected transactionBuilder: TransactionBuilder @@ -15,13 +17,16 @@ export class TransactionRecipeRole { this.transactionBuilder = new TransactionBuilder() } - public async create(transactionDraft: TransactionDraft): Promise { - const senderUser = transactionDraft.senderUser - const recipientUser = transactionDraft.recipientUser + public async create( + transactionDraft: TransactionDraft, + transactionTypeRole: AbstractTransactionRole, + ): Promise { + const signingUser = transactionTypeRole.getSigningUser() + const recipientUser = transactionTypeRole.getRecipientUser() // loading signing and recipient account // TODO: look for ways to use only one db call for both - const signingAccount = await UserRepository.findAccountByUserIdentifier(senderUser) + const signingAccount = await UserRepository.findAccountByUserIdentifier(signingUser) if (!signingAccount) { throw new TransactionError( TransactionErrorType.NOT_FOUND, @@ -40,13 +45,15 @@ export class TransactionRecipeRole { .setSigningAccount(signingAccount) .setRecipientAccount(recipientAccount) .fromTransactionDraft(transactionDraft) + .setCrossGroupType(transactionTypeRole.getCrossGroupType()) + .setOtherGroup(transactionTypeRole.getOtherGroup()) // build transaction entity this.transactionBuilder .fromTransactionBodyBuilder(transactionBodyBuilder) .addBackendTransaction(transactionDraft) - await this.transactionBuilder.setSenderCommunityFromSenderUser(senderUser) - if (recipientUser.communityUuid !== senderUser.communityUuid) { + await this.transactionBuilder.setSenderCommunityFromSenderUser(signingUser) + if (recipientUser.communityUuid !== signingUser.communityUuid) { await this.transactionBuilder.setOtherCommunityFromRecipientUser(recipientUser) } const transaction = this.transactionBuilder.getTransaction() From c97a6310c83a09de35b1ab54fa8eeb9660ea7465 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 16:49:32 +0100 Subject: [PATCH 45/47] remove log.txt correct this time --- backend/.gitignore | 1 - backend/log.txt | 2533 -------------------------------------------- 2 files changed, 2534 deletions(-) delete mode 100644 backend/log.txt diff --git a/backend/.gitignore b/backend/.gitignore index 63b375206..6eadcc884 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -4,6 +4,5 @@ /build/ package-json.lock coverage -log.txt # emacs *~ diff --git a/backend/log.txt b/backend/log.txt deleted file mode 100644 index b496d4791..000000000 --- a/backend/log.txt +++ /dev/null @@ -1,2533 +0,0 @@ - FAIL  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionResolver.test.tssrc/graphql/resolver/ContributionResolver.test.ts]8;; (9.447 s) - ContributionResolver - createContribution - unauthenticated - ✓ returns an error (8 ms) - authenticated with valid user - input not valid - ✓ throws error when memo length smaller than 5 chars (7 ms) - ✓ throws error when memo length greater than 255 chars (5 ms) - ✓ throws error when creationDate not-valid (4 ms) - ✓ throws error when creationDate 3 month behind (13 ms) - ✓ logs the error "No information for available creations for the given date" again (1 ms) - valid input - ✓ creates contribution - ✓ stores the CONTRIBUTION_CREATE event in the database (4 ms) - updateContribution - unauthenticated - ✓ returns an error (2 ms) - authenticated - Memo length smaller than 5 chars - ✓ throws error (5 ms) - Memo length greater than 255 chars - ✓ throws error (6 ms) - wrong contribution id - ✓ throws an error (8 ms) - ✓ logs the error "Contribution not found" - wrong user tries to update the contribution - ✓ throws an error (10 ms) - ✓ logs the error "Can not update contribution of another user" (1 ms) - admin tries to update a user contribution - ✕ throws an error (24 ms) - ✕ logs the error "An admin is not allowed to update an user contribution" (1 ms) - contribution has wrong status - ✓ throws an error (9 ms) - ✓ logs the error "Contribution can not be updated due to status" (1 ms) - update too much so that the limit is exceeded - ✓ throws an error (10 ms) - ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) - update creation to a date that is older than 3 months - ✓ throws an error (6 ms) - ✓ logs the error "Month of contribution can not be changed" (1 ms) - valid input - ✓ updates contribution (19 ms) - ✓ stores the CONTRIBUTION_UPDATE event in the database (97 ms) - denyContribution - unauthenticated - ✓ returns an error (2 ms) - authenticated without admin rights - ✓ returns an error (6 ms) - authenticated with admin rights - wrong contribution id - ✓ throws an error (6 ms) - ✓ logs the error "Contribution not found" (1 ms) - deny contribution that is already confirmed - ✓ throws an error (218 ms) - ✓ logs the error "Contribution not found" - deny contribution that is already deleted - ✓ throws an error (216 ms) - ✓ logs the error "Contribution not found" (1 ms) - deny contribution that is already denied - ✓ throws an error (211 ms) - ✓ logs the error "Contribution not found" (1 ms) - valid input - ✓ deny contribution (103 ms) - ✓ stores the ADMIN_CONTRIBUTION_DENY event in the database (2 ms) - ✓ calls sendContributionDeniedEmail - deleteContribution - unauthenticated - ✓ returns an error (1 ms) - authenticated - wrong contribution id - ✓ returns an error (7 ms) - ✓ logs the error "Contribution not found" (1 ms) - other user sends a deleteContribution - ✓ returns an error (5 ms) - ✓ logs the error "Can not delete contribution of another user" (1 ms) - User deletes own contribution - ✓ deletes successfully (20 ms) - ✓ stores the CONTRIBUTION_DELETE event in the database (2 ms) - User deletes already confirmed contribution - ✓ throws an error (199 ms) - ✓ logs the error "A confirmed contribution can not be deleted" (1 ms) - listContributions - unauthenticated - ✓ returns an error (2 ms) - authenticated - no status filter - ✕ returns creations (15 ms) - with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] - ✕ returns only unconfirmed creations (9 ms) - listAllContribution - unauthenticated - ✓ returns an error (1 ms) - authenticated - ✓ throws an error with "NOT_VALID" in statusFilter (6 ms) - ✓ throws an error with a null in statusFilter (2 ms) - ✓ throws an error with null and "NOT_VALID" in statusFilter (2 ms) - ✓ returns all contributions without statusFilter (8 ms) - ✓ returns all contributions for statusFilter = null (8 ms) - ✓ returns all contributions for statusFilter = [] (7 ms) - ✓ returns all CONFIRMED contributions (6 ms) - ✓ returns all PENDING contributions (6 ms) - ✓ returns all IN_PROGRESS Creation (6 ms) - ✓ returns all DENIED Creation (6 ms) - ✓ does not return any DELETED Creation (6 ms) - ✓ returns all CONFIRMED and PENDING Creation (7 ms) - contributions - unauthenticated - adminCreateContribution - ✓ returns an error (2 ms) - adminUpdateContribution - ✓ returns an error (1 ms) - adminDeleteContribution - ✓ returns an error (1 ms) - confirmContribution - ✓ returns an error (1 ms) - authenticated - without admin rights - adminCreateContribution - ✓ returns an error (7 ms) - adminUpdateContribution - ✓ returns an error (4 ms) - adminDeleteContribution - ✓ returns an error (3 ms) - confirmContribution - ✓ returns an error (3 ms) - with admin rights - adminCreateContribution - user to create for does not exist - ✓ throws an error (7 ms) - ✓ logs the error "Could not find user" (1 ms) - user to create for is deleted - ✓ throws an error (6 ms) - ✓ logs the error "Cannot create contribution since the user was deleted" (1 ms) - user to create for has email not confirmed - ✓ throws an error (7 ms) - ✓ logs the error "Cannot create contribution since the users email is not activated" (1 ms) - valid user to create for - date of creation is not a date string - ✓ throws an error (4 ms) - date of creation is four months ago - ✓ throws an error (7 ms) - ✓ logs the error "No information for available creations for the given date" - date of creation is in the future - ✓ throws an error (7 ms) - ✓ logs the error "No information for available creations for the given date" - amount of creation is too high - ✓ throws an error (7 ms) - ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) - creation is valid - ✓ returns an array of the open creations for the last three months (18 ms) - ✓ stores the ADMIN_CONTRIBUTION_CREATE event in the database (5 ms) - user tries to update admin contribution - ✓ logs and throws "Cannot update contribution of moderator" error (8 ms) - second creation surpasses the available amount - ✓ returns an array of the open creations for the last three months (9 ms) - ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) - adminUpdateContribution - creation does not exist - ✓ throws an error (5 ms) - ✓ logs the error "Contribution not found" - creation update is not valid - ✓ throws an error (8 ms) - ✓ logs the error "The amount to be created exceeds the amount still available for this month" (1 ms) - creation update is successful changing month - ○ skipped returns update creation object - ○ skipped stores the ADMIN_CONTRIBUTION_UPDATE event in the database - creation update is successful without changing month - ✓ returns update creation object (16 ms) - ✓ stores the ADMIN_CONTRIBUTION_UPDATE event in the database (3 ms) - adminDeleteContribution - creation id does not exist - ✓ throws an error (8 ms) - ✓ logs the error "Contribution not found" - admin deletes own user contribution - ✓ throws an error (5 ms) - creation id does exist - ✓ returns true (25 ms) - ✓ stores the ADMIN_CONTRIBUTION_DELETE event in the database (4 ms) - ✓ calls sendContributionDeletedEmail - creation already confirmed - ✓ throws an error (350 ms) - confirmContribution - creation does not exits - ✓ throws an error (5 ms) - ✓ logs the error "Contribution not found" (1 ms) - confirm own creation - ✓ thows an error (5 ms) - ✓ logs the error "Moderator can not confirm own contribution" (1 ms) - confirm creation for other user - ✓ returns true (21 ms) - ✓ stores the ADMIN_CONTRIBUTION_CONFIRM event in the database (4 ms) - ✓ creates a transaction (3 ms) - ✓ calls sendContributionConfirmedEmail - ✓ stores the EMAIL_CONFIRMATION event in the database (4 ms) - ✓ logs the error "Contribution already confirmed" (1 ms) - confirm same contribution again - ✓ throws an error (6 ms) - confirm two creations one after the other quickly - ✓ throws no error for the second confirmation (43 ms) - adminListContributions - unauthenticated - ✓ returns an error (2 ms) - authenticated as user - ✓ returns an error (4 ms) - authenticated as admin - ✓ throw error for invalid ContributionStatus in statusFilter array (1 ms) - ✕ returns 18 creations in total (20 ms) - ✓ returns two pending creations with page size set to 2 (9 ms) - with user query - ✕ returns only contributions of the queried user (10 ms) - ✕ returns only contributions of the queried user without hashtags (10 ms) - ✓ returns only contributions with #firefighter (7 ms) - ✓ returns no contributions with #firefighter and no hashtag (6 ms) - ✓ returns only contributions of the queried user email (8 ms) - - ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › throws an error - - expect(received).toEqual(expected) // deep equality - - Expected: [[GraphQLError: An admin is not allowed to update an user contribution]] - Received: undefined - -   509 | }, -   510 | }) - > 511 | expect(errorObjects).toEqual([ -   | ^ -   512 | new GraphQLError('An admin is not allowed to update an user contribution'), -   513 | ]) -   514 | }) - - at src/graphql/resolver/ContributionResolver.test.ts:511:32 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › logs the error "An admin is not allowed to update an user contribution" - - expect(jest.fn()).toBeCalledWith(...expected) - - Expected: "An admin is not allowed to update an user contribution" - - Number of calls: 0 - -   515 | -   516 | it('logs the error "An admin is not allowed to update an user contribution"', () => { - > 517 | expect(logger.error).toBeCalledWith( -   | ^ -   518 | 'An admin is not allowed to update an user contribution', -   519 | ) -   520 | }) - - at Object. (src/graphql/resolver/ContributionResolver.test.ts:517:32) - - ● ContributionResolver › listContributions › authenticated › no status filter › returns creations - - expect(received).toMatchObject(expected) - - - Expected - 16 - + Received + 64 - -  Object { -  "contributionCount": 6, - - "contributionList": ArrayContaining [ - - ObjectContaining { - + "contributionList": Array [ - + Object { -  "amount": "100", - - "id": 25, - - "memo": "Test contribution to confirm", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, - + "id": 27, - + "memo": "Test contribution to delete", -  "messagesCount": 0, - - }, - - ObjectContaining { - - "amount": "10", - - "id": 23, - - "memo": "Test PENDING contribution update", - - "messagesCount": 1, - + "status": "DELETED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "id": 26, -  "memo": "Test contribution to deny", -  "messagesCount": 0, - + "status": "DENIED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - - "id": 27, - - "memo": "Test contribution to delete", - + "confirmedAt": "2023-11-06T08:36:49.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 25, - + "memo": "Test contribution to confirm", -  "messagesCount": 0, - + "status": "CONFIRMED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 24, -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, - + "status": "IN_PROGRESS", -  }, - - ObjectContaining { - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 23, - + "memo": "Test PENDING contribution update", - + "messagesCount": 2, - + "status": "PENDING", - + }, - + Object { -  "amount": "1000", - + "confirmedAt": "2023-11-06T08:36:46.000Z", - + "confirmedBy": 283, - + "contributionDate": "2022-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 22, -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, - + "status": "CONFIRMED", -  }, -  ], -  } - -   1103 | }, -   1104 | }) - > 1105 | expect(contributionListResult).toMatchObject({ -   | ^ -   1106 | contributionCount: 6, -   1107 | contributionList: expect.arrayContaining([ -   1108 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:1105:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › listContributions › authenticated › with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] › returns only unconfirmed creations - - expect(received).toMatchObject(expected) - - - Expected - 19 - + Received + 44 - -  Object { -  "contributionCount": 4, - - "contributionList": ArrayContaining [ - - ObjectNotContaining { - - "status": "CONFIRMED", - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, - + "id": 27, - + "memo": "Test contribution to delete", - + "messagesCount": 0, - + "status": "DELETED", -  }, - - ObjectContaining { - - "amount": "10", - - "id": 23, - - "memo": "Test PENDING contribution update", - - "messagesCount": 1, - - "status": "PENDING", - - }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "id": 26, -  "memo": "Test contribution to deny", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - - "id": 27, - - "memo": "Test contribution to delete", - - "messagesCount": 0, - - "status": "DELETED", - - }, - - ObjectContaining { - - "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 24, -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, -  "status": "IN_PROGRESS", - + }, - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 23, - + "memo": "Test PENDING contribution update", - + "messagesCount": 2, - + "status": "PENDING", -  }, -  ], -  } - -   1161 | }, -   1162 | }) - > 1163 | expect(contributionListResult).toMatchObject({ -   | ^ -   1164 | contributionCount: 4, -   1165 | contributionList: expect.arrayContaining([ -   1166 | expect.not.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:1163:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › returns 18 creations in total - - expect(received).toMatchObject(expected) - - - Expected - 57 - + Received + 165 - - @@ -1,165 +1,273 @@ -  Object { -  "contributionCount": 18, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<100>, - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:51.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 39, -  "lastName": "Lustig", -  "memo": "#firefighters", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<50>, - + Object { - + "amount": "50", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 38, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<50>, - + Object { - + "amount": "50", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 37, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<450>, - + Object { - + "amount": "450", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 36, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<400>, - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": "2023-11-06T08:36:50.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bob", - - "id": Any, - + "id": 34, -  "lastName": "der Baumeister", -  "memo": "Confirmed Contribution", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 32, -  "lastName": "Bloxberg", -  "memo": "Aktives Grundeinkommen", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "firstName": "Räuber", - - "id": Any, - + "id": 30, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Räuber", - - "id": Any, - + "id": 29, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": "2023-11-06T08:36:48.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Räuber", - - "id": Any, - + "id": 28, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 27, -  "lastName": "Bloxberg", -  "memo": "Test contribution to delete", -  "messagesCount": 0, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "firstName": "Bibi", - - "id": Any, - + "id": 26, -  "lastName": "Bloxberg", -  "memo": "Test contribution to deny", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": "2023-11-06T08:36:49.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 25, -  "lastName": "Bloxberg", -  "memo": "Test contribution to confirm", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 24, -  "lastName": "Bloxberg", -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, -  "status": "IN_PROGRESS", -  }, - - ObjectContaining { - - "amount": decimalEqual<10>, - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 23, -  "lastName": "Bloxberg", -  "memo": "Test PENDING contribution update", - - "messagesCount": 2, - + "messagesCount": 3, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<1000>, - + Object { - + "amount": "1000", - + "confirmedAt": "2023-11-06T08:36:46.000Z", - + "confirmedBy": 283, - + "contributionDate": "2022-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 22, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - -   2827 | // console.log('17 contributions: %s', JSON.stringify(contributionListObject, null, 2)) -   2828 | expect(contributionListObject.contributionList).toHaveLength(18) - > 2829 | expect(contributionListObject).toMatchObject({ -   | ^ -   2830 | contributionCount: 18, -   2831 | contributionList: expect.arrayContaining([ -   2832 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:2829:40 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user - - expect(received).toMatchObject(expected) - - - Expected - 14 - + Received + 38 - -  Object { -  "contributionCount": 4, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<100>, - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:51.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 39, -  "lastName": "Lustig", -  "memo": "#firefighters", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<400>, - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, -  ], -  } - -   3057 | }) -   3058 | expect(contributionListObject.contributionList).toHaveLength(4) - > 3059 | expect(contributionListObject).toMatchObject({ -   | ^ -   3060 | contributionCount: 4, -   3061 | contributionList: expect.arrayContaining([ -   3062 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:3059:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user without hashtags - - expect(received).toMatchObject(expected) - - - Expected - 11 - + Received + 29 - -  Object { -  "contributionCount": 3, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<400>, - + "contributionList": Array [ - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, -  ], -  } - -   3111 | }) -   3112 | expect(contributionListObject.contributionList).toHaveLength(3) - > 3113 | expect(contributionListObject).toMatchObject({ -   | ^ -   3114 | contributionCount: 3, -   3115 | contributionList: expect.arrayContaining([ -   3116 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:3113:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/UserResolver.test.tssrc/graphql/resolver/UserResolver.test.ts]8;; (12.687 s) - UserResolver - createUser - ✓ returns success (2 ms) - valid input data - ✓ stores the USER_REGISTER event in the database (5 ms) - filling all tables - ✓ saves the user in users table (1 ms) - ✓ creates an email contact - account activation email - ✓ sends an account activation email (1 ms) - ✓ stores the EMAIL_CONFIRMATION event in the database (2 ms) - user already exists - ✓ logs an info (1 ms) - ✓ sends an account multi registration email (1 ms) - ✓ results with partly faked user with random "id" - ✓ stores the EMAIL_ACCOUNT_MULTIREGISTRATION event in the database (7 ms) - unknown language - ✓ sets "de" as default language (63 ms) - no publisher id - ✓ sets publisher id to 0 (55 ms) - redeem codes - contribution link - ✓ sets the contribution link id (4 ms) - ✓ stores the USER_ACTIVATE_ACCOUNT event in the database (2 ms) - ✓ stores the USER_REGISTER_REDEEM event in the database (3 ms) - transaction link - ✓ sets the referrer id to bob baumeister id (3 ms) - ✓ stores the USER_REGISTER_REDEEM event in the database (2 ms) - setPassword - valid optin code and valid password - ✓ sets email checked to true (1 ms) - ✓ updates the password (76 ms) - ✓ calls the klicktipp API - ✓ returns true (1 ms) - no valid password - ✓ throws an error (21 ms) - ✓ logs the error thrown (1 ms) - no valid optin code - ✓ throws an error (2 ms) - ✓ logs the error found - login - no users in database - ✓ throws an error (6 ms) - ✓ logs the error found (1 ms) - user is in database and correct login data - ✓ returns the user object (1 ms) - ✓ sets the token in the header (1 ms) - ✓ stores the USER_LOGIN event in the database (4 ms) - user is in database and wrong password - ✓ returns an error (1 ms) - ✓ logs the error thrown (1 ms) - user is in database but deleted - ✓ returns an error (1 ms) - ✓ logs the error thrown - user is in database but email not confirmed - ✓ returns an error (1 ms) - ✓ logs the error thrown - user is in database but password is not set - ○ skipped returns an error - ○ skipped logs the error thrown - logout - unauthenticated - ✓ throws an error (4 ms) - authenticated - ✓ returns true (10 ms) - ✓ stores the USER_LOGOUT event in the database (6 ms) - verifyLogin - unauthenticated - ✓ throws an error (1 ms) - user exists but is not logged in - ✓ throws an error (1 ms) - authenticated - ✓ returns user object (5 ms) - ✓ stores the USER_LOGIN event in the database (4 ms) - forgotPassword - user is not in DB - duration not expired - ✓ returns true (3 ms) - user exists in DB - duration not expired - ✓ throws an error (7 ms) - duration reset to 0 - ✓ returns true (36 ms) - ✓ sends reset password email (1 ms) - ✓ stores the EMAIL_FORGOT_PASSWORD event in the database (5 ms) - request reset password again - ✓ thows an error (6 ms) - ✓ logs the error found - queryOptIn - wrong optin code - ✓ throws an error (8 ms) - correct optin code - ✓ returns true (2 ms) - updateUserInfos - unauthenticated - ✓ throws an error (2 ms) - authenticated - ✓ returns true (13 ms) - first-name, last-name and language - ✓ updates the fields in DB (14 ms) - ✓ stores the USER_INFO_UPDATE event in the database (7 ms) - alias - valid alias - ✓ updates the user in DB (17 ms) - language is not valid - ✓ throws an error (5 ms) - ✓ logs the error found - password - wrong old password - ✓ throws an error (81 ms) - ✓ logs the error found - invalid new password - ✓ throws an error (5 ms) - ✓ logs the error found (1 ms) - correct old and new password - ✓ returns true (166 ms) - ✓ can login with new password (89 ms) - ✓ cannot login with old password (82 ms) - ✓ logs the error thrown (1 ms) - searchAdminUsers - unauthenticated - ✓ throws an error (3 ms) - authenticated - ✓ finds peter@lustig.de (8 ms) - password encryption type - user just registered - ✓ has password type gradido id (79 ms) - user has encryption type email - ✓ changes to gradidoID on login (259 ms) - ✓ can login after password change (93 ms) - set user role - unauthenticated - ✓ returns an error (2 ms) - authenticated - with user rights - ✓ returns an error (4 ms) - with moderator rights - ✓ returns an error (4 ms) - with admin rights - ✓ returns user with new moderator-role (18 ms) - user to get a new role does not exist - ✓ throws an error (8 ms) - ✓ logs the error thrown (1 ms) - change role with success - user gets new role - to admin - ✓ returns admin-rolename (17 ms) - ✓ stores the ADMIN_USER_ROLE_SET event in the database (5 ms) - to moderator - ✓ returns date string (18 ms) - ✓ stores the ADMIN_USER_ROLE_SET event in the database (2 ms) - to usual user - ✓ returns null (16 ms) - change role with error - his own role - ✓ throws an error (7 ms) - ✓ logs the error thrown - to not allowed role - ✓ throws an error (4 ms) - user has already role to be set - to admin - ✓ throws an error (26 ms) - ✓ logs the error thrown (1 ms) - to moderator - ✓ throws an error (25 ms) - ✓ logs the error thrown (1 ms) - to usual user - ✓ throws an error (23 ms) - ✓ logs the error thrown - delete user - unauthenticated - ✓ returns an error (2 ms) - authenticated - without admin rights - ✓ returns an error (4 ms) - with admin rights - user to be deleted does not exist - ✓ throws an error (6 ms) - ✓ logs the error thrown - delete self - ✓ throws an error (7 ms) - ✓ logs the error thrown - delete with success - ✓ returns date string (19 ms) - ✓ stores the ADMIN_USER_DELETE event in the database (8 ms) - delete deleted user - ✓ throws an error (6 ms) - ✓ logs the error thrown - sendActivationEmail - unauthenticated - ✓ returns an error (2 ms) - authenticated - without admin rights - ✓ returns an error (3 ms) - with admin rights - user does not exist - ✓ throws an error (6 ms) - ✓ logs the error thrown - user is deleted - ✓ throws an error (155 ms) - ✓ logs the error thrown - sendActivationEmail with success - ✓ returns true (36 ms) - ✓ sends an account activation email (4 ms) - ✓ stores the EMAIL_ADMIN_CONFIRMATION event in the database (7 ms) - unDelete user - unauthenticated - ✓ returns an error (2 ms) - authenticated - without admin rights - ✓ returns an error (4 ms) - with admin rights - user to be undelete does not exist - ✓ throws an error (5 ms) - ✓ logs the error thrown - user to undelete is not deleted - ✓ throws an error (6 ms) - ✓ logs the error thrown - undelete deleted user - ✓ returns null (14 ms) - ✓ stores the ADMIN_USER_UNDELETE event in the database (8 ms) - search users - unauthenticated - ✓ returns an error (4 ms) - authenticated - without admin rights - ✓ returns an error (4 ms) - with admin rights - without any filters - ✓ finds all users (18 ms) - all filters are null - ✓ finds all users (14 ms) - filter by unchecked email - ✓ finds only users with unchecked email (10 ms) - filter by deleted users - ✓ finds only users with deleted account (9 ms) - filter by deleted account and unchecked email - ✓ finds no users (6 ms) - user - unauthenticated - ✓ throws and logs "401 Unauthorized" error (2 ms) - authenticated - identifier is no gradido ID, no email and no alias - ✓ throws and logs "Unknown identifier type" error (8 ms) - identifier is not found - ✓ throws and logs "No user found to given identifier" error (8 ms) - identifier is found via email, but not matching community - ✓ returns user (6 ms) - identifier is found via email - ✓ returns user (9 ms) - identifier is found via gradidoID - ✓ returns user (7 ms) - identifier is found via alias - ✓ returns user (7 ms) - check username - reserved alias - ✓ returns false (2 ms) - valid alias - ✓ returns true (3 ms) - printTimeDuration - ✓ works with 10 minutes (1 ms) - ✓ works with 1440 minutes (1 ms) - ✓ works with 1410 minutes - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/TransactionLinkResolver.test.tssrc/graphql/resolver/TransactionLinkResolver.test.ts]8;; (5.288 s) - TransactionLinkResolver - createTransactionLink - unauthenticated - ✓ throws an error (9 ms) - authenticated - ✓ throws error when amount is zero (6 ms) - ✓ throws error when amount is negative (4 ms) - ✓ throws error when memo text is too short (5 ms) - ✓ throws error when memo text is too long (7 ms) - ✓ throws error when user has not enough GDD (13 ms) - ✓ logs the error "User has not enough GDD" - redeemTransactionLink - unauthenticated - ✓ throws an error (1 ms) - authenticated - contributionLink - input not valid - ✓ throws error when link does not exists (14 ms) - ✓ logs the error "No contribution link found to given code" (1 ms) - ✓ throws error when link is not valid yet (31 ms) - ✓ logs the error "Contribution link is not valid yet" (1 ms) - ✓ throws error when contributionLink cycle is invalid (26 ms) - ✓ logs the error "Contribution link has unknown cycle" - ✓ throws error when link is no longer valid (24 ms) - ✓ logs the error "Contribution link is no longer valid" (1 ms) - redeem daily Contribution Link - ✓ has a daily contribution link in the database (3 ms) - user has pending contribution of 1000 GDD - ✓ does not allow the user to redeem the contribution link (11 ms) - ✓ logs the error "Creation from contribution link was not successful" (1 ms) - user has no pending contributions that would not allow to redeem the link - ✓ allows the user to redeem the contribution link (24 ms) - ✓ stores the CONTRIBUTION_LINK_REDEEM event in the database (10 ms) - ✓ does not allow the user to redeem the contribution link a second time on the same day (8 ms) - ✓ logs the error "Creation from contribution link was not successful" - after one day - ✓ allows the user to redeem the contribution link again (25 ms) - ✓ does not allow the user to redeem the contribution link a second time on the same day (15 ms) - ✓ logs the error "Creation from contribution link was not successful" - transaction link - link does not exits - ✓ throws and logs the error (6 ms) - link exists - ✓ stores the TRANSACTION_LINK_CREATE event in the database (5 ms) - own link - ✓ throws and logs an error (13 ms) - ✓ delete own link (16 ms) - ✓ stores the TRANSACTION_LINK_DELETE event in the database (9 ms) - other link - ✓ successfully redeems link (99 ms) - ✓ stores the TRANSACTION_LINK_REDEEM event in the database (16 ms) - listTransactionLinksAdmin - unauthenticated - ✓ returns an error (5 ms) - authenticated - without admin rights - ✓ returns an error (4 ms) - with admin rights - ✓ throws error when user does not exists (6 ms) - ✓ logs the error "Could not find requested User" - without any filters - ✓ finds 6 open transaction links and no deleted or redeemed (14 ms) - all filters are null - ✓ finds 6 open transaction links and no deleted or redeemed (7 ms) - filter with deleted - ✓ finds 6 open transaction links, 1 deleted, and no redeemed (7 ms) - filter by expired - ✓ finds 5 open transaction links, 1 expired, and no redeemed (10 ms) - filter by redeemed - ○ skipped finds 6 open transaction links, 1 deleted, and no redeemed - transactionLinkCode - ✓ returns a string of length 24 - ✓ returns a string that ends with the hex value of date - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionMessageResolver.test.tssrc/graphql/resolver/ContributionMessageResolver.test.ts]8;; - ContributionMessageResolver - adminCreateContributionMessage - unauthenticated - ✓ returns an error (12 ms) - authenticated - input not valid - ✓ throws error when contribution does not exist (11 ms) - ✓ logs the error "ContributionMessage was not sent successfully: Error: Contribution not found" (1 ms) - ✓ throws error when contribution.userId equals user.id (116 ms) - ✓ logs the error "ContributionMessage was not sent successfully: Error: Admin can not answer on his own contribution" (1 ms) - contribution message type MODERATOR - ✓ creates ContributionMessage (17 ms) - ✓ does not call sendAddedContributionMessageEmail (1 ms) - ✓ does not change contribution status (2 ms) - valid input - ✓ creates ContributionMessage (52 ms) - ✓ calls sendAddedContributionMessageEmail (1 ms) - ✓ changes contribution status (4 ms) - ✓ stores the ADMIN_CONTRIBUTION_MESSAGE_CREATE event in the database (3 ms) - createContributionMessage - unauthenticated - ✓ returns an error (2 ms) - authenticated - input not valid - ✓ throws error when contribution does not exist (11 ms) - ✓ logs the error "ContributionMessage was not sent successfully: Error: Contribution not found" - ✓ throws error when other user tries to send createContributionMessage (99 ms) - ✓ logs the error "ContributionMessage was not sent successfully: Error: Can not send message to contribution of another user" (1 ms) - valid input - ✓ creates ContributionMessage (15 ms) - ✓ stores the CONTRIBUTION_MESSAGE_CREATE event in the database (2 ms) - listContributionMessages - unauthenticated - ✓ returns an error (2 ms) - authenticated - ✓ returns a list of contributionmessages without type MODERATOR (11 ms) - adminListContributionMessages - unauthenticated - ✓ returns an error (2 ms) - authenticated as user - ✓ returns an error (5 ms) - authenticated as admin - ✓ returns a list of contributionmessages with type MODERATOR (11 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/TransactionResolver.test.tssrc/graphql/resolver/TransactionResolver.test.ts]8;; - send coins - unknown recipient - ✓ throws an error (106 ms) - ✓ logs the error thrown (1 ms) - deleted recipient - ✓ throws an error (94 ms) - ✓ logs the error thrown (1 ms) - recipient account not activated - ✓ throws an error (92 ms) - ✓ logs the error thrown (1 ms) - errors in the transaction itself - sender and recipient are the same - ✓ throws an error (27 ms) - ✓ logs the error thrown (1 ms) - memo text is too short - ✓ throws an error (4 ms) - memo text is too long - ✓ throws an error (6 ms) - user has not enough GDD - ✓ throws an error (14 ms) - ✓ logs the error thrown - user has some GDD - trying to send negative amount - ✓ throws an error (4 ms) - good transaction - ✓ sends the coins (37 ms) - ✓ stores the TRANSACTION_SEND event in the database (35 ms) - ✓ stores the TRANSACTION_RECEIVE event in the database (6 ms) - sendTransactionsToDltConnector - ✓ has wait till sendTransactionsToDltConnector created all dlt-transactions (1 ms) - send coins via gradido ID - ✓ sends the coins (45 ms) - send coins via alias - ✓ sends the coins (38 ms) - peter's transactions - ✓ has all expected transactions (173 ms) - X-Com send coins via gradido ID - ✓ sends the coins (52 ms) - more transactions to test semaphore - ✓ sends the coins four times in a row (251 ms) - transactionList - unauthenticated - ✓ throws an error (9 ms) - authenticated - no transactions - ✓ has no transactions and balance 0 (82 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/creations.test.tssrc/graphql/resolver/util/creations.test.ts]8;; - util/creation - getUserCreations - ✓ has the correct data setup (4 ms) - call getUserCreation now - ✓ returns the expected open contributions (4 ms) - run forward in time one hour before next month - ✓ has the clock set correctly (1 ms) - call getUserCreation with UTC - ✓ returns the expected open contributions (2 ms) - call getUserCreation with JST (GMT+0900) - ✓ returns the expected open contributions (2 ms) - call getUserCreation with PST (GMT-0800) - ✓ returns the expected open contributions (2 ms) - run two hours forward to be in the next month in UTC - ✓ has the clock set correctly - call getUserCreation with UTC - ✓ returns the expected open contributions (2 ms) - call getUserCreation with JST (GMT+0900) - ✓ returns the expected open contributions (2 ms) - call getUserCreation with PST (GMT-0800) - ✓ returns the expected open contributions (3 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionLinkResolver.test.tssrc/graphql/resolver/ContributionLinkResolver.test.ts]8;; - Contribution Links - unauthenticated - createContributionLink - ✓ returns an error (11 ms) - listContributionLinks - ✓ returns an error (2 ms) - updateContributionLink - ✓ returns an error (3 ms) - deleteContributionLink - ✓ returns an error (2 ms) - authenticated - without admin rights - createContributionLink - ✓ returns an error (6 ms) - listContributionLinks - ✓ returns an empty object (7 ms) - updateContributionLink - ✓ returns an error (7 ms) - deleteContributionLink - ✓ returns an error (4 ms) - with admin rights - createContributionLink - ✓ returns a contribution link object (18 ms) - ✓ has a contribution link stored in db (4 ms) - ✓ stores the ADMIN_CONTRIBUTION_LINK_CREATE event in the database (5 ms) - ✓ returns an error if missing startDate (8 ms) - ✓ logs the error "A Start-Date must be set" (1 ms) - ✓ returns an error if missing endDate (4 ms) - ✓ logs the error "An End-Date must be set" (1 ms) - ✓ returns an error if endDate is before startDate (4 ms) - ✓ logs the error "The value of validFrom must before or equals the validTo" - ✓ returns an error if name is shorter than 5 characters (4 ms) - ✓ returns an error if name is longer than 100 characters (7 ms) - ✓ returns an error if memo is shorter than 5 characters (4 ms) - ✓ returns an error if memo is longer than 255 characters (4 ms) - ✓ returns an error if amount is not positive (4 ms) - listContributionLinks - one link in DB - ✓ returns the link and count 1 (6 ms) - updateContributionLink - ✓ logs the error "Contribution Link not found" - no valid id - ✓ returns an error (8 ms) - valid id - ✓ returns updated contribution link object (15 ms) - ✓ updated the DB record (2 ms) - ✓ stores the ADMIN_CONTRIBUTION_LINK_UPDATE event in the database (2 ms) - deleteContributionLink - no valid id - ✓ returns an error (5 ms) - ✓ logs the error "Contribution Link not found" - valid id - ✓ returns true (18 ms) - ✓ stores the ADMIN_CONTRIBUTION_LINK_DELETE event in the database (5 ms) - ✓ does not list this contribution link anymore (8 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/KlicktippResolver.test.tssrc/graphql/resolver/KlicktippResolver.test.ts]8;; - KlicktippResolver - subscribeNewsletter - unauthenticated - ✓ returns an error (9 ms) - authenticated - ✓ calls API (11 ms) - ✓ stores the NEWSLETTER_SUBSCRIBE event in the database (5 ms) - unsubscribeNewsletter - unauthenticated - ✓ returns an error (2 ms) - authenticated - ✓ calls API (11 ms) - ✓ stores the NEWSLETTER_UNSUBSCRIBE event in the database (5 ms) - -(node:16141) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit -(Use `node --trace-warnings ...` to show where the warning was created) - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/util/klicktipp.test.tssrc/util/klicktipp.test.ts]8;; - klicktipp - exportEventDataToKlickTipp - ✓ calls the KlicktippController (13 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/semaphore.test.tssrc/graphql/resolver/semaphore.test.ts]8;; - semaphore - ✓ creates a lot of transactions without errors (772 ms) - redeem transaction link twice - ✓ does throw error on second redeem call (107 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/validateAlias.test.tssrc/graphql/resolver/util/validateAlias.test.ts]8;; - validate alias - alias too short - ✓ throws and logs an error (1 ms) - alias too long - ✓ throws and logs an error (1 ms) - alias contains invalid characters - ✓ throws and logs an error - alias is a reserved word - ✓ throws and logs an error (1 ms) - alias is a reserved word with uppercase characters - ✓ throws and logs an error (1 ms) - hyphens and underscore - alias starts with underscore - ✓ throws and logs an error (3 ms) - alias contains two following hyphens - ✓ throws and logs an error (1 ms) - test against existing alias in database - alias exists in database - ✓ throws and logs an error (3 ms) - alias exists in database with in lower-case - ✓ throws and logs an error (3 ms) - valid alias - ✓ resolves to true (2 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/CommunityResolver.test.tssrc/graphql/resolver/CommunityResolver.test.ts]8;; - CommunityResolver - getCommunities - with empty list - ✓ returns no community entry (13 ms) - only home-communities entries - ✓ returns 3 home-community entries (50 ms) - plus foreign-communities entries - ✓ returns 3 home community and 3 foreign community entries (17 ms) - communities - with empty list - ✓ returns no community entry (33 ms) - with one home-community entry - ✓ returns 1 home-community entry (29 ms) - returns 2 filtered communities even with 3 existing entries - ✓ returns 2 community entries (43 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.tssrc/graphql/resolver/util/sendTransactionsToDltConnector.test.ts]8;; - create and send Transactions to DltConnector - with 3 creations but inactive dlt-connector - ✓ found 3 dlt-transactions (102 ms) - with 3 creations and active dlt-connector - ✓ found 3 dlt-transactions (104 ms) - with 3 verified creations, 1 sendCoins and active dlt-connector - ✓ found 3 dlt-transactions (114 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/EmailOptinCodes.test.tssrc/graphql/resolver/EmailOptinCodes.test.ts]8;; - EmailOptinCodes - queryOptIn - ✓ has a valid optin code (4 ms) - run time forward until code must be expired - ✓ throws an error (23 ms) - ✓ does not allow to set password (11 ms) - forgotPassword - ✓ throws an error (11 ms) - run time forward until code can be resent - ✓ cann send email again (17 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/federation/validateCommunities.test.tssrc/federation/validateCommunities.test.ts]8;; - validate Communities - start validation logic without loop - ✓ logs zero communities found (13 ms) - with one Community of api 1_0 but missing pubKey response - ✓ logs one community found (25 ms) - ✓ logs requestGetPublicKey missing response data (12 ms) - with one Community of api 1_0 and not matching pubKey - ✓ logs one community found (22 ms) - ✓ logs requestGetPublicKey for community api 1_0 (14 ms) - ✓ logs not matching publicKeys (14 ms) - with one Community of api 1_0 and matching pubKey - ✓ logs one community found (36 ms) - ✓ logs requestGetPublicKey for community api 1_0 (24 ms) - ✓ logs community pubKey verified (65 ms) - with two Communities of api 1_0 and 1_1 - ✓ logs two communities found (18 ms) - ✓ logs requestGetPublicKey for community api 1_0 (19 ms) - ✓ logs requestGetPublicKey for community api 1_1 (21 ms) - with three Communities of api 1_0, 1_1 and 2_0 - ✓ logs three community found (26 ms) - ✓ logs requestGetPublicKey for community api 1_0 (28 ms) - ✓ logs requestGetPublicKey for community api 1_1 (17 ms) - ✓ logs unsupported api for community with api 2_0 (19 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/apis/DltConnectorClient.test.tssrc/apis/DltConnectorClient.test.ts]8;; - undefined DltConnectorClient - ✓ invalid url (2 ms) - ✓ DLT_CONNECTOR is false (1 ms) - transmitTransaction - ✓ invalid transaction type (2 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/emails/sendEmailVariants.test.tssrc/emails/sendEmailVariants.test.ts]8;; - sendEmailVariants - sendAddedContributionMessageEmail - calls "sendEmailTranslated" - ✓ with expected parameters (2 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot (1 ms) - sendAccountActivationEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot (1 ms) - sendAccountMultiRegistrationEmail - calls "sendEmailTranslated" - ✓ with expected parameters - result - ✓ is the expected object - ✓ has the correct html as snapshot (1 ms) - sendContributionConfirmedEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object - ✓ has the correct html as snapshot - sendContributionDeniedEmail - calls "sendEmailTranslated" - ✓ with expected parameters - result - ✓ has expected result (1 ms) - ✓ has the correct html as snapshot (1 ms) - sendContributionDeletedEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot - sendResetPasswordEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot - sendTransactionLinkRedeemedEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot - sendTransactionReceivedEmail - calls "sendEmailTranslated" - ✓ with expected parameters (1 ms) - result - ✓ is the expected object (1 ms) - ✓ has the correct html as snapshot - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/test/helpers.test.tstest/helpers.test.ts]8;; - contributionDateFormatter - ✓ formats the date correctly (2 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/emails/sendEmailTranslated.test.tssrc/emails/sendEmailTranslated.test.ts]8;; - sendEmailTranslated - config email is false - ✓ logs warning (2 ms) - ✓ returns false - config email is true - ✓ calls the transporter (104 ms) - ○ skipped calls "i18n.setLocale" with "en" - ○ skipped calls "i18n.__" for translation - call of "sendEmailTranslated" - ✓ has expected result (50 ms) - with email EMAIL_TEST_MODUS true - ✓ call of "sendEmailTranslated" with faked "to" (39 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/server/LogError.test.tssrc/server/LogError.test.ts]8;; - LogError - ✓ logs an Error when created (2 ms) - ✓ logs an Error including additional data when created (1 ms) - ✓ does not contain additional data in Error object when thrown (3 ms) - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/util/decay.test.tssrc/util/decay.test.ts]8;; - utils/decay - ✓ has base 0.99999997802044727 - ✓ returns input amount when from and to is the same (1 ms) - decayFormula - ✓ has base 0.99999997802044727 (1 ms) - ✓ has correct backward calculation - ○ skipped has correct forward calculation - - PASS  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/config/index.test.tssrc/config/index.test.ts]8;; - config/index - decay start block - ✓ has the correct date set (2 ms) - -Running coverage on untested files...Browserslist: caniuse-lite is outdated. Please run: - npx browserslist@latest --update-db - Why you should do it regularly: https://github.com/browserslist/browserslist#browsers-data-updating -Summary of all failing tests - FAIL  ]8;;file:///home/einhornimmond/code/gradido_apollo/backend/src/graphql/resolver/ContributionResolver.test.tssrc/graphql/resolver/ContributionResolver.test.ts]8;; (9.447 s) - ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › throws an error - - expect(received).toEqual(expected) // deep equality - - Expected: [[GraphQLError: An admin is not allowed to update an user contribution]] - Received: undefined - -   509 | }, -   510 | }) - > 511 | expect(errorObjects).toEqual([ -   | ^ -   512 | new GraphQLError('An admin is not allowed to update an user contribution'), -   513 | ]) -   514 | }) - - at src/graphql/resolver/ContributionResolver.test.ts:511:32 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › updateContribution › authenticated › admin tries to update a user contribution › logs the error "An admin is not allowed to update an user contribution" - - expect(jest.fn()).toBeCalledWith(...expected) - - Expected: "An admin is not allowed to update an user contribution" - - Number of calls: 0 - -   515 | -   516 | it('logs the error "An admin is not allowed to update an user contribution"', () => { - > 517 | expect(logger.error).toBeCalledWith( -   | ^ -   518 | 'An admin is not allowed to update an user contribution', -   519 | ) -   520 | }) - - at Object. (src/graphql/resolver/ContributionResolver.test.ts:517:32) - - ● ContributionResolver › listContributions › authenticated › no status filter › returns creations - - expect(received).toMatchObject(expected) - - - Expected - 16 - + Received + 64 - -  Object { -  "contributionCount": 6, - - "contributionList": ArrayContaining [ - - ObjectContaining { - + "contributionList": Array [ - + Object { -  "amount": "100", - - "id": 25, - - "memo": "Test contribution to confirm", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, - + "id": 27, - + "memo": "Test contribution to delete", -  "messagesCount": 0, - - }, - - ObjectContaining { - - "amount": "10", - - "id": 23, - - "memo": "Test PENDING contribution update", - - "messagesCount": 1, - + "status": "DELETED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "id": 26, -  "memo": "Test contribution to deny", -  "messagesCount": 0, - + "status": "DENIED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - - "id": 27, - - "memo": "Test contribution to delete", - + "confirmedAt": "2023-11-06T08:36:49.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 25, - + "memo": "Test contribution to confirm", -  "messagesCount": 0, - + "status": "CONFIRMED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 24, -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, - + "status": "IN_PROGRESS", -  }, - - ObjectContaining { - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 23, - + "memo": "Test PENDING contribution update", - + "messagesCount": 2, - + "status": "PENDING", - + }, - + Object { -  "amount": "1000", - + "confirmedAt": "2023-11-06T08:36:46.000Z", - + "confirmedBy": 283, - + "contributionDate": "2022-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 22, -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, - + "status": "CONFIRMED", -  }, -  ], -  } - -   1103 | }, -   1104 | }) - > 1105 | expect(contributionListResult).toMatchObject({ -   | ^ -   1106 | contributionCount: 6, -   1107 | contributionList: expect.arrayContaining([ -   1108 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:1105:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › listContributions › authenticated › with status filter [PENDING, IN_PROGRESS, DENIED, DELETED] › returns only unconfirmed creations - - expect(received).toMatchObject(expected) - - - Expected - 19 - + Received + 44 - -  Object { -  "contributionCount": 4, - - "contributionList": ArrayContaining [ - - ObjectNotContaining { - - "status": "CONFIRMED", - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, - + "id": 27, - + "memo": "Test contribution to delete", - + "messagesCount": 0, - + "status": "DELETED", -  }, - - ObjectContaining { - - "amount": "10", - - "id": 23, - - "memo": "Test PENDING contribution update", - - "messagesCount": 1, - - "status": "PENDING", - - }, - - ObjectContaining { - + Object { -  "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "id": 26, -  "memo": "Test contribution to deny", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - + Object { -  "amount": "100", - - "id": 27, - - "memo": "Test contribution to delete", - - "messagesCount": 0, - - "status": "DELETED", - - }, - - ObjectContaining { - - "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, -  "id": 24, -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, -  "status": "IN_PROGRESS", - + }, - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deletedAt": null, - + "deniedAt": null, - + "deniedBy": null, - + "id": 23, - + "memo": "Test PENDING contribution update", - + "messagesCount": 2, - + "status": "PENDING", -  }, -  ], -  } - -   1161 | }, -   1162 | }) - > 1163 | expect(contributionListResult).toMatchObject({ -   | ^ -   1164 | contributionCount: 4, -   1165 | contributionList: expect.arrayContaining([ -   1166 | expect.not.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:1163:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › returns 18 creations in total - - expect(received).toMatchObject(expected) - - - Expected - 57 - + Received + 165 - - @@ -1,165 +1,273 @@ -  Object { -  "contributionCount": 18, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<100>, - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:51.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 39, -  "lastName": "Lustig", -  "memo": "#firefighters", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<50>, - + Object { - + "amount": "50", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 38, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<50>, - + Object { - + "amount": "50", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 37, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<450>, - + Object { - + "amount": "450", - + "confirmedAt": "2023-11-06T08:36:51.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-09-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 36, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido liebe Bibi!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<400>, - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": "2023-11-06T08:36:50.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bob", - - "id": Any, - + "id": 34, -  "lastName": "der Baumeister", -  "memo": "Confirmed Contribution", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 32, -  "lastName": "Bloxberg", -  "memo": "Aktives Grundeinkommen", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "firstName": "Räuber", - - "id": Any, - + "id": 30, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Räuber", - - "id": Any, - + "id": 29, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<166>, - + Object { - + "amount": "166", - + "confirmedAt": "2023-11-06T08:36:48.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:48.000Z", - + "createdAt": "2023-11-06T08:36:48.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Räuber", - - "id": Any, - + "id": 28, -  "lastName": "Hotzenplotz", -  "memo": "Whatever contribution", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 27, -  "lastName": "Bloxberg", -  "memo": "Test contribution to delete", -  "messagesCount": 0, -  "status": "DELETED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": "2023-11-06T08:36:48.000Z", - + "deniedBy": 283, -  "firstName": "Bibi", - - "id": Any, - + "id": 26, -  "lastName": "Bloxberg", -  "memo": "Test contribution to deny", -  "messagesCount": 0, -  "status": "DENIED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": "2023-11-06T08:36:49.000Z", - + "confirmedBy": 283, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 25, -  "lastName": "Bloxberg", -  "memo": "Test contribution to confirm", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:46.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 24, -  "lastName": "Bloxberg", -  "memo": "Test IN_PROGRESS contribution", -  "messagesCount": 1, -  "status": "IN_PROGRESS", -  }, - - ObjectContaining { - - "amount": decimalEqual<10>, - + Object { - + "amount": "10", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:47.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 23, -  "lastName": "Bloxberg", -  "memo": "Test PENDING contribution update", - - "messagesCount": 2, - + "messagesCount": 3, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<1000>, - + Object { - + "amount": "1000", - + "confirmedAt": "2023-11-06T08:36:46.000Z", - + "confirmedBy": 283, - + "contributionDate": "2022-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:46.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Bibi", - - "id": Any, - + "id": 22, -  "lastName": "Bloxberg", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "CONFIRMED", -  }, - -   2827 | // console.log('17 contributions: %s', JSON.stringify(contributionListObject, null, 2)) -   2828 | expect(contributionListObject.contributionList).toHaveLength(18) - > 2829 | expect(contributionListObject).toMatchObject({ -   | ^ -   2830 | contributionCount: 18, -   2831 | contributionList: expect.arrayContaining([ -   2832 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:2829:40 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user - - expect(received).toMatchObject(expected) - - - Expected - 14 - + Received + 38 - -  Object { -  "contributionCount": 4, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<100>, - + "contributionList": Array [ - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T08:36:51.000Z", - + "createdAt": "2023-11-06T08:36:51.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 39, -  "lastName": "Lustig", -  "memo": "#firefighters", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<400>, - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, -  ], -  } - -   3057 | }) -   3058 | expect(contributionListObject.contributionList).toHaveLength(4) - > 3059 | expect(contributionListObject).toMatchObject({ -   | ^ -   3060 | contributionCount: 4, -   3061 | contributionList: expect.arrayContaining([ -   3062 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:3059:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - ● ContributionResolver › adminListContributions › authenticated as admin › with user query › returns only contributions of the queried user without hashtags - - expect(received).toMatchObject(expected) - - - Expected - 11 - + Received + 29 - -  Object { -  "contributionCount": 3, - - "contributionList": ArrayContaining [ - - ObjectContaining { - - "amount": decimalEqual<400>, - + "contributionList": Array [ - + Object { - + "amount": "400", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 35, -  "lastName": "Lustig", -  "memo": "Herzlich Willkommen bei Gradido!", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<100>, - + Object { - + "amount": "100", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-11-06T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:50.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 33, -  "lastName": "Lustig", -  "memo": "Test env contribution", -  "messagesCount": 0, -  "status": "PENDING", -  }, - - ObjectContaining { - - "amount": decimalEqual<200>, - + Object { - + "amount": "200", - + "confirmedAt": null, - + "confirmedBy": null, - + "contributionDate": "2023-10-01T00:00:00.000Z", - + "createdAt": "2023-11-06T08:36:49.000Z", - + "deniedAt": null, - + "deniedBy": null, -  "firstName": "Peter", - - "id": Any, - + "id": 31, -  "lastName": "Lustig", -  "memo": "Das war leider zu Viel!", - - "messagesCount": 0, - + "messagesCount": 1, -  "status": "DELETED", -  }, -  ], -  } - -   3111 | }) -   3112 | expect(contributionListObject.contributionList).toHaveLength(3) - > 3113 | expect(contributionListObject).toMatchObject({ -   | ^ -   3114 | contributionCount: 3, -   3115 | contributionList: expect.arrayContaining([ -   3116 | expect.objectContaining({ - - at src/graphql/resolver/ContributionResolver.test.ts:3113:42 - at fulfilled (src/graphql/resolver/ContributionResolver.test.ts:5:58) - - -Test Suites: 1 failed, 21 passed, 22 total -Tests: 7 failed, 8 skipped, 482 passed, 497 total -Snapshots: 9 passed, 9 total -Time: 59.16 s -Ran all test suites. -error Command failed with exit code 1. From 7b2ca22f01d91b2289a1d8ee2c0c29de15970b5a Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 16:54:51 +0100 Subject: [PATCH 46/47] fix test --- backend/src/apis/dltConnector/DltConnectorClient.test.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/backend/src/apis/dltConnector/DltConnectorClient.test.ts b/backend/src/apis/dltConnector/DltConnectorClient.test.ts index 421b957e9..d99093a1b 100644 --- a/backend/src/apis/dltConnector/DltConnectorClient.test.ts +++ b/backend/src/apis/dltConnector/DltConnectorClient.test.ts @@ -113,10 +113,7 @@ describe('transmitTransaction', () => { const localTransaction = new DbTransaction() localTransaction.typeId = 12 try { - await DltConnectorClient.getInstance()?.transmitTransaction( - localTransaction, - 'senderCommunityUUID', - ) + await DltConnectorClient.getInstance()?.transmitTransaction(localTransaction) } catch (e) { expect(e).toMatchObject( new LogError('invalid transaction type id: ' + localTransaction.typeId.toString()), From 980517559d77ea79f62acfacd8c926d3aceb4eb5 Mon Sep 17 00:00:00 2001 From: einhorn_b Date: Fri, 5 Jan 2024 17:12:30 +0100 Subject: [PATCH 47/47] fix lost update --- dlt-connector/src/data/proto/3_3/TransactionBody.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dlt-connector/src/data/proto/3_3/TransactionBody.ts b/dlt-connector/src/data/proto/3_3/TransactionBody.ts index c30d2a6e7..0c2733606 100644 --- a/dlt-connector/src/data/proto/3_3/TransactionBody.ts +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -118,12 +118,14 @@ export class TransactionBody extends Message { public getRecipientPublicKey(): Buffer | undefined { if (this.transfer) { + // this.transfer.recipient contains the publicKey of the recipient return this.transfer.recipient } if (this.creation) { return this.creation.recipient.pubkey } if (this.deferredTransfer) { + // this.deferredTransfer.transfer.recipient contains the publicKey of the recipient return this.deferredTransfer.transfer.recipient } return undefined