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 84% rename from backend/src/apis/DltConnectorClient.test.ts rename to backend/src/apis/dltConnector/DltConnectorClient.test.ts index 56fa3d13f..d99093a1b 100644 --- a/backend/src/apis/DltConnectorClient.test.ts +++ b/backend/src/apis/dltConnector/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, + }, + }) }), } }), diff --git a/backend/src/apis/DltConnectorClient.ts b/backend/src/apis/dltConnector/DltConnectorClient.ts similarity index 67% rename from backend/src/apis/DltConnectorClient.ts rename to backend/src/apis/dltConnector/DltConnectorClient.ts index f01a55d6c..765d09fb4 100644 --- a/backend/src/apis/DltConnectorClient.ts +++ b/backend/src/apis/dltConnector/DltConnectorClient.ts @@ -6,6 +6,9 @@ import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' import { LogError } from '@/server/LogError' import { backendLogger as logger } from '@/server/logger' +import { TransactionResult } from './model/TransactionResult' +import { UserIdentifier } from './model/UserIdentifier' + const sendTransaction = gql` mutation ($input: TransactionInput!) { sendTransaction(data: $input) { @@ -78,32 +81,42 @@ export class DltConnectorClient { * transmit transaction via dlt-connector to iota * and update dltTransactionId of transaction in db with iota message id */ - public async transmitTransaction( - transaction: DbTransaction, - senderCommunityUuid?: string, - recipientCommunityUuid?: string, - ): Promise { + public async transmitTransaction(transaction: DbTransaction): 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: { + 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(), + 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) } 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/config/index.ts b/backend/src/config/index.ts index 022dc38a2..1ec5a98e6 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-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.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 c07a691a3..5684835e4 100644 --- a/backend/src/graphql/resolver/ContributionResolver.ts +++ b/backend/src/graphql/resolver/ContributionResolver.ts @@ -451,7 +451,11 @@ export class ContributionResolver { transaction.userId = contribution.userId transaction.userGradidoID = user.gradidoID transaction.userName = fullName(user.firstName, user.lastName) - transaction.linkedUserId = contribution.moderatorId + transaction.userCommunityUuid = user.communityUuid + 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/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts index d9a2da569..0d85a35af 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.test.ts @@ -22,6 +22,13 @@ import { logger, i18n as localization } from '@test/testSetup' import { CONFIG } from '@/config' import { TransactionTypeId } from '@/graphql/enum/TransactionTypeId' +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 { sendTransactionsToDltConnector } from './sendTransactionsToDltConnector' @@ -423,9 +430,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 +450,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 +476,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 +484,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 +492,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 +526,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 +578,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 +586,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..733c12594 100644 --- a/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts +++ b/backend/src/graphql/resolver/util/sendTransactionsToDltConnector.ts @@ -1,9 +1,9 @@ import { IsNull } from '@dbTools/typeorm' -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' @@ -17,13 +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') - } - const recipientCommunityUuid = '' if (dltConnector) { logger.debug('with sending to DltConnector...') const dltTransactions = await DltTransaction.find({ @@ -37,22 +30,14 @@ export async function sendTransactionsToDltConnector(): Promise { continue } try { - const messageId = 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 + 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) { + 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}`, 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/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..ae5ef6ccf --- /dev/null +++ b/database/migrations/0080-fill_linked_user_gradidoId_of_contributions.ts @@ -0,0 +1,34 @@ +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), + 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>) { + await queryFn( + `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;`, + ) +} diff --git a/dht-node/src/config/index.ts b/dht-node/src/config/index.ts index 47f7d8085..5a462a06c 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/dlt-connector/.eslintrc.js b/dlt-connector/.eslintrc.js index c477a4cb1..fa43a5f1a 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', @@ -75,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/@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/jest.config.js b/dlt-connector/jest.config.js index 723aa840b..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: 77, + lines: 71, }, }, setupFiles: ['/test/testSetup.ts'], @@ -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/package.json b/dlt-connector/package.json index da26893d1..5a4c54394 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", @@ -51,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/config/index.ts b/dlt-connector/src/config/index.ts index 37332a4b2..e6febb482 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/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/TransactionBase.ts b/dlt-connector/src/controller/TransactionBase.ts deleted file mode 100644 index 9833226a9..000000000 --- a/dlt-connector/src/controller/TransactionBase.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { TransactionValidationLevel } from '@/graphql/enum/TransactionValidationLevel' - -export abstract class TransactionBase { - // validate if transaction is valid, maybe expensive because depending on level several transactions will be fetched from db - public abstract validate(level: TransactionValidationLevel): boolean -} 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/controller/TransactionBody.ts b/dlt-connector/src/controller/TransactionBody.ts deleted file mode 100644 index ae5f37710..000000000 --- a/dlt-connector/src/controller/TransactionBody.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { CrossGroupType } from '@/graphql/enum/CrossGroupType' -import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' -import { TransactionType } from '@/graphql/enum/TransactionType' -import { TransactionDraft } from '@/graphql/input/TransactionDraft' -import { TransactionError } from '@/graphql/model/TransactionError' -import { GradidoCreation } from '@/proto/3_3/GradidoCreation' -import { GradidoTransfer } from '@/proto/3_3/GradidoTransfer' -import { TransactionBody } from '@/proto/3_3/TransactionBody' - -export const create = (transaction: TransactionDraft): TransactionBody => { - const body = new TransactionBody(transaction) - // TODO: load pubkeys for sender and recipient user from db - switch (transaction.type) { - case TransactionType.CREATION: - body.creation = new GradidoCreation(transaction) - body.data = 'gradidoCreation' - break - case TransactionType.SEND: - case TransactionType.RECEIVE: - body.transfer = new GradidoTransfer(transaction) - body.data = 'gradidoTransfer' - break - } - return body -} - -export const determineCrossGroupType = ({ - senderUser, - recipientUser, - type, -}: TransactionDraft): CrossGroupType => { - if ( - !recipientUser.communityUuid || - recipientUser.communityUuid === '' || - senderUser.communityUuid === recipientUser.communityUuid || - type === TransactionType.CREATION - ) { - return CrossGroupType.LOCAL - } else if (type === TransactionType.SEND) { - return CrossGroupType.INBOUND - } else if (type === TransactionType.RECEIVE) { - return CrossGroupType.OUTBOUND - } - throw new TransactionError( - TransactionErrorType.NOT_IMPLEMENTED_YET, - 'cannot determine CrossGroupType', - ) -} - -export const determineOtherGroup = ( - type: CrossGroupType, - { senderUser, recipientUser }: TransactionDraft, -): string => { - switch (type) { - case CrossGroupType.LOCAL: - return '' - case CrossGroupType.INBOUND: - if (!recipientUser.communityUuid) { - throw new TransactionError( - TransactionErrorType.MISSING_PARAMETER, - 'missing recipient user community id for cross group transaction', - ) - } - return recipientUser.communityUuid - case CrossGroupType.OUTBOUND: - if (!senderUser.communityUuid) { - throw new TransactionError( - TransactionErrorType.MISSING_PARAMETER, - 'missing sender user community id for cross group transaction', - ) - } - return senderUser.communityUuid - } -} diff --git a/dlt-connector/src/data/Account.factory.ts b/dlt-connector/src/data/Account.factory.ts new file mode 100644 index 000000000..a8c1f162d --- /dev/null +++ b/dlt-connector/src/data/Account.factory.ts @@ -0,0 +1,60 @@ +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 +const AUF_ACCOUNT_DERIVATION_INDEX = 2 + +export class AccountFactory { + public static createAccount( + createdAt: Date, + derivationIndex: number, + type: AddressType, + parentKeyPair: KeyPair, + ): Account { + const account = Account.create() + account.derivationIndex = derivationIndex + account.derive2Pubkey = parentKeyPair.derive([derivationIndex]).publicKey + account.type = type.valueOf() + account.createdAt = createdAt + account.balanceOnConfirmation = new Decimal(0) + account.balanceOnCreation = new Decimal(0) + account.balanceCreatedAt = createdAt + 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( + createdAt, + hardenDerivationIndex(GMW_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_GMW, + keyPair, + ) + } + + public static createAufAccount(keyPair: KeyPair, createdAt: Date): Account { + return AccountFactory.createAccount( + createdAt, + hardenDerivationIndex(AUF_ACCOUNT_DERIVATION_INDEX), + AddressType.COMMUNITY_AUF, + keyPair, + ) + } +} diff --git a/dlt-connector/src/data/Account.repository.ts b/dlt-connector/src/data/Account.repository.ts new file mode 100644 index 000000000..6931e6ea6 --- /dev/null +++ b/dlt-connector/src/data/Account.repository.ts @@ -0,0 +1,34 @@ +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({ + findAccountsByPublicKeys(publicKeys: Buffer[]): Promise { + return this.findBy({ derive2Pubkey: In(publicKeys) }) + }, + + async findAccountByPublicKey(publicKey: Buffer | undefined): Promise { + if (!publicKey) return undefined + return (await this.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/Account.test.ts b/dlt-connector/src/data/Account.test.ts new file mode 100644 index 000000000..f28065cce --- /dev/null +++ b/dlt-connector/src/data/Account.test.ts @@ -0,0 +1,197 @@ +import 'reflect-metadata' +import { Decimal } from 'decimal.js-light' + +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' + +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 = 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', () => { + 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, + derive2Pubkey: Buffer.from( + 'cb88043ef4833afc01d6ed9b34e1aa48e79dce5ff97c07090c6600ec05f6d994', + 'hex', + ), + type: AddressType.COMMUNITY_HUMAN, + createdAt: now, + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: 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, + derive2Pubkey: Buffer.from( + 'cb88043ef4833afc01d6ed9b34e1aa48e79dce5ff97c07090c6600ec05f6d994', + 'hex', + ), + type: AddressType.COMMUNITY_HUMAN, + createdAt: now, + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), + }) + }) + + it('test createGmwAccount', () => { + const account = AccountFactory.createGmwAccount(keyPair1, now) + expect(account).toMatchObject({ + derivationIndex: 2147483649, + derive2Pubkey: Buffer.from( + '05f0060357bb73bd290283870fc47a10b3764f02ca26938479ed853f46145366', + 'hex', + ), + type: AddressType.COMMUNITY_GMW, + createdAt: now, + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: new Decimal(0), + }) + }) + + it('test createAufAccount', () => { + const account = AccountFactory.createAufAccount(keyPair1, now) + expect(account).toMatchObject({ + derivationIndex: 2147483650, + derive2Pubkey: Buffer.from( + '6c749f8693a4a58c948e5ae54df11e2db33d2f98673b56e0cf19c0132614ab59', + 'hex', + ), + type: AddressType.COMMUNITY_AUF, + createdAt: now, + balanceCreatedAt: now, + balanceOnConfirmation: new Decimal(0), + balanceOnCreation: 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/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/Community.repository.ts b/dlt-connector/src/data/Community.repository.ts new file mode 100644 index 000000000..78023b15e --- /dev/null +++ b/dlt-connector/src/data/Community.repository.ts @@ -0,0 +1,76 @@ +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 { KeyPair } from './KeyPair' + +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 this.find({ + where: { iotaTopic }, + }) + return result.length > 0 + }, + + async findByCommunityArg({ uuid, foreign, confirmed }: CommunityArg): Promise { + return await this.find({ + where: { + ...(uuid && { iotaTopic: iotaTopicFromCommunityUUID(uuid) }), + ...(foreign && { foreign }), + ...(confirmed && { confirmedAt: Not(IsNull()) }), + }, + }) + }, + + async findByCommunityUuid(communityUuid: string): Promise { + return await this.findOneBy({ iotaTopic: iotaTopicFromCommunityUUID(communityUuid) }) + }, + + async findByIotaTopic(iotaTopic: string): Promise { + return await this.findOneBy({ iotaTopic }) + }, + + findCommunitiesByTopics(topics: string[]): Promise { + return this.findBy({ iotaTopic: In(topics) }) + }, + + async getCommunityForUserIdentifier( + identifier: UserIdentifier, + ): Promise { + if (!identifier.communityUuid) { + throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community uuid not set') + } + return ( + (await this.findOneBy({ + iotaTopic: iotaTopicFromCommunityUUID(identifier.communityUuid), + })) ?? undefined + ) + }, + + findAll(select: FindOptionsSelect): Promise { + return this.find({ select }) + }, + + async loadHomeCommunityKeyPair(): Promise { + const community = await this.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..59e9a5066 --- /dev/null +++ b/dlt-connector/src/data/KeyPair.ts @@ -0,0 +1,87 @@ +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: 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: 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 + } + } + + /** + * 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]) + } + + public getExtendPublicKey(): Buffer { + return Buffer.concat([this._publicKey, this._chainCode]) + } + + 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 new file mode 100644 index 000000000..115391e91 --- /dev/null +++ b/dlt-connector/src/data/Transaction.builder.ts @@ -0,0 +1,179 @@ +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 { 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' + +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 getCommunity(): Community { + return this.transaction.community + } + + public setSigningAccount(signingAccount: Account): TransactionBuilder { + this.transaction.signingAccount = signingAccount + return this + } + + public setRecipientAccount(recipientAccount: Account): TransactionBuilder { + this.transaction.recipientAccount = recipientAccount + return this + } + + public setCommunity(community: Community): TransactionBuilder { + this.transaction.community = community + return this + } + + public setOtherCommunity(otherCommunity?: Community): TransactionBuilder { + if (!this.transaction.community) { + throw new LogError('Please set community first!') + } + + this.transaction.otherCommunity = + otherCommunity && + this.transaction.community && + this.transaction.community.id !== otherCommunity.id + ? otherCommunity + : undefined + return this + } + + public setSignature(signature: Buffer): TransactionBuilder { + this.transaction.signature = signature + return this + } + + public addBackendTransaction(transactionDraft: TransactionDraft): TransactionBuilder { + if (!this.transaction.backendTransactions) { + this.transaction.backendTransactions = [] + } + this.transaction.backendTransactions.push( + BackendTransactionFactory.createFromTransactionDraft(transactionDraft), + ) + return this + } + + public async setSenderCommunityFromSenderUser( + senderUser: UserIdentifier, + ): Promise { + // get sender community + const community = await CommunityRepository.getCommunityForUserIdentifier(senderUser) + if (!community) { + throw new LogError("couldn't find community for transaction") + } + return this.setCommunity(community) + } + + public async setOtherCommunityFromRecipientUser( + recipientUser: UserIdentifier, + ): Promise { + // get recipient community + const otherCommunity = await CommunityRepository.getCommunityForUserIdentifier(recipientUser) + return this.setOtherCommunity(otherCommunity) + } + + 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 + } + + 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/Transaction.repository.ts b/dlt-connector/src/data/Transaction.repository.ts new file mode 100644 index 000000000..6ba622c9c --- /dev/null +++ b/dlt-connector/src/data/Transaction.repository.ts @@ -0,0 +1,43 @@ +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) + .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 }, + }) + }, + 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() + }, + removeConfirmedTransaction(transactions: Transaction[]): Transaction[] { + return transactions.filter( + (transaction: Transaction) => + transaction.runningHash === undefined || transaction.runningHash.length === 0, + ) + }, + }) diff --git a/dlt-connector/src/data/User.factory.ts b/dlt-connector/src/data/User.factory.ts new file mode 100644 index 000000000..a8c7f0e71 --- /dev/null +++ b/dlt-connector/src/data/User.factory.ts @@ -0,0 +1,18 @@ +import { User } from '@entity/User' + +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 { + 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..0a906682d --- /dev/null +++ b/dlt-connector/src/data/User.logic.ts @@ -0,0 +1,42 @@ +import { User } from '@entity/User' + +import { LogError } from '@/server/LogError' +import { hardenDerivationIndex } from '@/utils/derivationHelper' +import { uuid4ToBuffer } from '@/utils/typeConverter' + +import { KeyPair } from './KeyPair' + +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 = 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', + ) + } + if (!this.user.derive1Pubkey) { + this.user.derive1Pubkey = keyPair.publicKey + } + return keyPair + } +} diff --git a/dlt-connector/src/data/User.repository.ts b/dlt-connector/src/data/User.repository.ts new file mode 100644 index 000000000..6e5a66203 --- /dev/null +++ b/dlt-connector/src/data/User.repository.ts @@ -0,0 +1,24 @@ +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({ + 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/CommunityRoot.ts b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts new file mode 100644 index 000000000..c03460741 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/CommunityRoot.ts @@ -0,0 +1,35 @@ +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 +export class CommunityRoot extends Message implements AbstractTransaction { + 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-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 69% rename from dlt-connector/src/proto/3_3/GradidoConfirmedTransaction.ts rename to dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts index 7f0a58109..d59b991e8 100644 --- a/dlt-connector/src/proto/3_3/GradidoConfirmedTransaction.ts +++ b/dlt-connector/src/data/proto/3_3/ConfirmedTransaction.ts @@ -1,4 +1,7 @@ -import { Field, Message } from '@apollo/protobufjs' +import { Field, Message } from 'protobufjs' + +import { base64ToBuffer } from '@/utils/typeConverter' + import { GradidoTransaction } from './GradidoTransaction' import { TimestampSeconds } from './TimestampSeconds' @@ -10,9 +13,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 99% rename from dlt-connector/src/proto/3_3/GradidoCreation.test.ts rename to dlt-connector/src/data/proto/3_3/GradidoCreation.test.ts index 8b3fd1b3f..06011838c 100644 --- a/dlt-connector/src/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 new file mode 100644 index 000000000..0fa08eff5 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoCreation.ts @@ -0,0 +1,53 @@ +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' + +// 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 AbstractTransaction { + 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() + } + } + + // 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 + + 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 73% rename from dlt-connector/src/proto/3_3/GradidoDeferredTransfer.ts rename to dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts index 7b27c064a..f48719b16 100644 --- a/dlt-connector/src/proto/3_3/GradidoDeferredTransfer.ts +++ b/dlt-connector/src/data/proto/3_3/GradidoDeferredTransfer.ts @@ -1,4 +1,8 @@ -import { Field, Message } from '@apollo/protobufjs' +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' @@ -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 AbstractTransaction +{ // 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,8 @@ export class GradidoDeferredTransfer extends Message { // split for n recipient // max gradido per recipient? or per transaction with cool down? + + 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..4aaa3e25c --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoTransaction.ts @@ -0,0 +1,44 @@ +import { Field, Message } from 'protobufjs' + +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 { + 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..7e9da40bd --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/GradidoTransfer.ts @@ -0,0 +1,49 @@ +import { Account } from '@entity/Account' +import { Transaction } from '@entity/Transaction' +import Decimal from 'decimal.js-light' +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 +export class GradidoTransfer extends Message implements AbstractTransaction { + 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() + } + } + + // 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 + + 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 62% rename from dlt-connector/src/proto/3_3/GroupFriendsUpdate.ts rename to dlt-connector/src/data/proto/3_3/GroupFriendsUpdate.ts index 64e74a694..b64e80a73 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 { Transaction } from '@entity/Transaction' +import { Field, Message } from 'protobufjs' + +import { AbstractTransaction } from '../AbstractTransaction' // 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 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, @@ -12,4 +16,8 @@ export class GroupFriendsUpdate extends Message { // (if fusion between src coin and dst coin is enabled) @Field.d(1, 'bool') public colorFusion: boolean + + 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..87f09afbd --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/RegisterAddress.ts @@ -0,0 +1,29 @@ +/* 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' + +// https://www.npmjs.com/package/@apollo/protobufjs +// eslint-disable-next-line no-use-before-define +export class RegisterAddress extends Message implements AbstractTransaction { + @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 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..0c2733606 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/TransactionBody.ts @@ -0,0 +1,133 @@ +import { Transaction } from '@entity/Transaction' +import { Field, Message, OneOf } from 'protobufjs' + +import { CommunityDraft } from '@/graphql/input/CommunityDraft' +import { TransactionDraft } from '@/graphql/input/TransactionDraft' +import { LogError } from '@/server/LogError' +import { timestampToDate } from '@/utils/typeConverter' + +import { AbstractTransaction } from '../AbstractTransaction' + +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 { Timestamp } from './Timestamp' + +// 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) { + super({ + memo: 'Not implemented yet', + createdAt: new Timestamp(new Date(transaction.createdAt)), + versionNumber: PROTO_TRANSACTION_BODY_VERSION_NUMBER, + type: CrossGroupType.LOCAL, + 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 + } + + // 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 + 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.getTransactionDetails()?.fillTransactionRecipe(recipe) + } + + 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/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/const.ts b/dlt-connector/src/data/proto/3_3/const.ts new file mode 100644 index 000000000..9733e14a2 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/const.ts @@ -0,0 +1 @@ +export const PROTO_TRANSACTION_BODY_VERSION_NUMBER = '3.3' diff --git a/dlt-connector/src/graphql/enum/AddressType.ts b/dlt-connector/src/data/proto/3_3/enum/AddressType.ts similarity index 66% rename from dlt-connector/src/graphql/enum/AddressType.ts rename to dlt-connector/src/data/proto/3_3/enum/AddressType.ts index 26efd2825..eace1e022 100644 --- a/dlt-connector/src/graphql/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 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..fee592e57 --- /dev/null +++ b/dlt-connector/src/data/proto/3_3/enum/CrossGroupType.ts @@ -0,0 +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, + 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 new file mode 100644 index 000000000..ac089b096 --- /dev/null +++ b/dlt-connector/src/data/proto/AbstractTransaction.ts @@ -0,0 +1,5 @@ +import { Transaction } from '@entity/Transaction' + +export abstract class AbstractTransaction { + 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..22d943d48 --- /dev/null +++ b/dlt-connector/src/data/proto/TransactionBody.builder.ts @@ -0,0 +1,138 @@ +import { Account } from '@entity/Account' +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 { CrossGroupType } from './3_3/enum/CrossGroupType' +import { GradidoCreation } from './3_3/GradidoCreation' +import { GradidoTransfer } from './3_3/GradidoTransfer' +import { TransactionBody } from './3_3/TransactionBody' + +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 + this.signingAccount = undefined + this.recipientAccount = 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.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', + ) + } + return this.body + } + + public getSigningAccount(): Account | undefined { + return this.signingAccount + } + + public getRecipientAccount(): Account | undefined { + return this.recipientAccount + } + + public setSigningAccount(signingAccount: Account): TransactionBodyBuilder { + this.signingAccount = signingAccount + return this + } + + public setRecipientAccount(recipientAccount: Account): TransactionBodyBuilder { + this.recipientAccount = recipientAccount + 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 + 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, + 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/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/AccountType.ts b/dlt-connector/src/graphql/enum/AccountType.ts new file mode 100644 index 000000000..810c89044 --- /dev/null +++ b/dlt-connector/src/graphql/enum/AccountType.ts @@ -0,0 +1,21 @@ +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 + 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/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 new file mode 100755 index 000000000..41eeac6cb --- /dev/null +++ b/dlt-connector/src/graphql/enum/InputTransactionType.ts @@ -0,0 +1,14 @@ +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, + 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..1b01bc0da 100644 --- a/dlt-connector/src/graphql/enum/TransactionErrorType.ts +++ b/dlt-connector/src/graphql/enum/TransactionErrorType.ts @@ -1,10 +1,17 @@ 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', 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', } registerEnumType(TransactionErrorType, { diff --git a/dlt-connector/src/graphql/enum/TransactionType.ts b/dlt-connector/src/graphql/enum/TransactionType.ts deleted file mode 100755 index aaa5bf92e..000000000 --- a/dlt-connector/src/graphql/enum/TransactionType.ts +++ /dev/null @@ -1,12 +0,0 @@ -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 -}) 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 2021dd9e1..541797565 100755 --- a/dlt-connector/src/graphql/input/TransactionDraft.ts +++ b/dlt-connector/src/graphql/input/TransactionDraft.ts @@ -1,32 +1,37 @@ // https://www.npmjs.com/package/@apollo/protobufjs - +import { IsEnum, IsObject, IsPositive, ValidateNested } from 'class-validator' import { Decimal } from 'decimal.js-light' -import { TransactionType } from '@enum/TransactionType' -import { InputType, Field } from 'type-graphql' -import { UserIdentifier } from './UserIdentifier' +import { InputType, Field, Int } from 'type-graphql' + +import { InputTransactionType } from '@enum/InputTransactionType' import { isValidDateString } from '@validator/DateString' import { IsPositiveDecimal } from '@validator/Decimal' -import { IsEnum, IsObject, ValidateNested } from 'class-validator' + +import { UserIdentifier } from './UserIdentifier' @InputType() export class TransactionDraft { @Field(() => UserIdentifier) @IsObject() @ValidateNested() - senderUser: UserIdentifier + user: UserIdentifier @Field(() => UserIdentifier) @IsObject() @ValidateNested() - recipientUser: UserIdentifier + linkedUser: UserIdentifier + + @Field(() => Int) + @IsPositive() + backendTransactionId: number @Field(() => Decimal) @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/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/input/UserAccountDraft.ts b/dlt-connector/src/graphql/input/UserAccountDraft.ts new file mode 100644 index 000000000..9ae544e32 --- /dev/null +++ b/dlt-connector/src/graphql/input/UserAccountDraft.ts @@ -0,0 +1,26 @@ +// https://www.npmjs.com/package/@apollo/protobufjs + +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) + @IsObject() + @ValidateNested() + user: UserIdentifier + + @Field(() => String) + @isValidDateString() + createdAt: string + + @Field(() => AccountType) + @IsEnum(AccountType) + accountType: AccountType +} diff --git a/dlt-connector/src/graphql/model/Community.ts b/dlt-connector/src/graphql/model/Community.ts new file mode 100644 index 000000000..7a69288dc --- /dev/null +++ b/dlt-connector/src/graphql/model/Community.ts @@ -0,0 +1,36 @@ +import { Community as CommunityEntity } from '@entity/Community' +import { ObjectType, Field, Int } from 'type-graphql' + +@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/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 new file mode 100644 index 000000000..263ccce4a --- /dev/null +++ b/dlt-connector/src/graphql/model/TransactionRecipe.ts @@ -0,0 +1,32 @@ +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 = transactionType.toString() + this.topic = community.iotaTopic + } + + @Field(() => Int) + id: number + + @Field(() => String) + createdAt: string + + @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 938c8bcf6..370c9827d 100644 --- a/dlt-connector/src/graphql/model/TransactionResult.ts +++ b/dlt-connector/src/graphql/model/TransactionResult.ts @@ -1,15 +1,17 @@ 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,8 +20,8 @@ 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 diff --git a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts index 7f1f3ea3c..0fa61cc48 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.test.ts @@ -1,34 +1,40 @@ import 'reflect-metadata' -import { ApolloServer } from '@apollo/server' -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 { TransactionResult } from '@model/TransactionResult' +import { createApolloTestServer } from '@test/ApolloServerMock' + +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 +51,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/CommunityResolver.ts b/dlt-connector/src/graphql/resolver/CommunityResolver.ts index d6f9f2d46..d4bbeb28e 100644 --- a/dlt-connector/src/graphql/resolver/CommunityResolver.ts +++ b/dlt-connector/src/graphql/resolver/CommunityResolver.ts @@ -1,47 +1,67 @@ -import { Resolver, Arg, Mutation } from 'type-graphql' +import { Resolver, Query, Arg, Mutation, Args } from 'type-graphql' +import { CommunityArg } from '@arg/CommunityArg' +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 { TransactionResult } from '../model/TransactionResult' -import { TransactionError } from '../model/TransactionError' -import { create as createCommunity, isExist } from '@/controller/Community' -import { TransactionErrorType } from '../enum/TransactionErrorType' +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 { + @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 { + 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!'), + ) + } + // 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 { - 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 + // 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) diff --git a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts index 7c02a4306..6eb443e21 100644 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.test.ts @@ -1,8 +1,28 @@ import 'reflect-metadata' -import { ApolloServer } from '@apollo/server' -import { createApolloTestServer } from '@test/ApolloServerMock' import assert from 'assert' -import { TransactionResult } from '../model/TransactionResult' + +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 @@ -14,63 +34,88 @@ jest.mock('@/client/IotaClient', () => { } }) +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() + 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, communityKeyPair) + const userLogic = new UserLogic(user) + const account = AccountFactory.createAccountFromUserAccountDraft( + userAccountDraft, + userLogic.calculateKeyPair(communityKeyPair), + ) + 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', () => { + let user: UserIdentifier + let linkedUser: UserIdentifier beforeAll(async () => { + 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() + user = await createUserStoreAccount('0ec72b74-48c2-446f-91ce-31ad7d9f4d65') + linkedUser = await createUserStoreAccount('ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe') }) - 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) {succeed, recipe { id, topic }} }', variables: { input: { - senderUser: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, - type: 'SEND', + user, + linkedUser, + type: getEnumValue(InputTransactionType, InputTransactionType.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.recipe).toBeDefined() + 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: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, + user, + linkedUser, type: 'INVALID', amount: '10', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) @@ -79,7 +124,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.', }, ], }) @@ -88,18 +133,15 @@ 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: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, - type: 'SEND', + user, + linkedUser, + type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: 'no number', createdAt: '2012-04-17T17:12:00Z', + backendTransactionId: 1, }, }, }) @@ -117,18 +159,15 @@ 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: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, - type: 'SEND', + user, + linkedUser, + type: getEnumValue(InputTransactionType, InputTransactionType.SEND), amount: '10', createdAt: 'not valid', + backendTransactionId: 1, }, }, }) @@ -156,18 +195,15 @@ 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: { - uuid: '0ec72b74-48c2-446f-91ce-31ad7d9f4d65', - }, - recipientUser: { - uuid: 'ddc8258e-fcb5-4e48-8d1d-3a07ec371dbe', - }, - type: 'CREATION', + user, + linkedUser, + 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 282eb11cd..10b55573e 100755 --- a/dlt-connector/src/graphql/resolver/TransactionsResolver.ts +++ b/dlt-connector/src/graphql/resolver/TransactionsResolver.ts @@ -1,40 +1,48 @@ -import { Resolver, Query, Arg, Mutation } from 'type-graphql' +import { Resolver, 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 { TransactionRepository } from '@/data/Transaction.repository' +import { CreateTransactionRecipeContext } from '@/interactions/backendToDb/transaction/CreateTransationRecipe.context' +import { LogError } from '@/server/LogError' -import { sendMessage as iotaSendMessage } from '@/client/IotaClient' -import { GradidoTransaction } from '@/proto/3_3/GradidoTransaction' -import { TransactionResult } from '../model/TransactionResult' import { TransactionError } from '../model/TransactionError' +import { TransactionRecipe } from '../model/TransactionRecipe' +import { TransactionResult } from '../model/TransactionResult' @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 { - const body = createTransactionBody(transaction) - const message = createGradidoTransaction(body) - const messageBuffer = GradidoTransaction.encode(message).finish() - const resultMessage = await iotaSendMessage(messageBuffer) - return new TransactionResult(resultMessage.messageId) - } catch (error) { + await createTransactionRecipeContext.run() + const transactionRecipe = createTransactionRecipeContext.getTransactionRecipe() + // 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 instanceof TransactionError) { return new TransactionResult(error) } else { diff --git a/dlt-connector/src/graphql/schema.ts b/dlt-connector/src/graphql/schema.ts index fc9c26919..19a6d5566 100755 --- a/dlt-connector/src/graphql/schema.ts +++ b/dlt-connector/src/graphql/schema.ts @@ -2,14 +2,15 @@ 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({ resolvers: [TransactionResolver, CommunityResolver], scalarsMap: [{ type: Decimal, scalar: DecimalScalar }], + emitSchemaFile: true, validate: { validationError: { target: false }, skipMissingProperties: true, diff --git a/dlt-connector/src/index.ts b/dlt-connector/src/index.ts index 5284d9b1e..c72978b35 100644 --- a/dlt-connector/src/index.ts +++ b/dlt-connector/src/index.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { CONFIG } from '@/config' + import createServer from './server/createServer' async function main() { 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..bc8f90c32 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/AddCommunity.context.ts @@ -0,0 +1,31 @@ +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' + +/** + * @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 { + 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 new file mode 100644 index 000000000..30d91bfed --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/Community.role.ts @@ -0,0 +1,28 @@ +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' + +export abstract class CommunityRole { + protected self: Community + public constructor() { + this.self = Community.create() + } + + public async create(communityDraft: CommunityDraft, topic: string): Promise { + 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 new file mode 100644 index 000000000..cf93deaa5 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/ForeignCommunity.role.ts @@ -0,0 +1,4 @@ +import { CommunityRole } from './Community.role' + +// 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 new file mode 100644 index 000000000..256cfe1a5 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/community/HomeCommunity.role.ts @@ -0,0 +1,51 @@ +import { Community } from '@entity/Community' +import { Transaction } from '@entity/Transaction' + +import { CONFIG } from '@/config' +import { AccountFactory } from '@/data/Account.factory' +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 = 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) + this.self.gmwAccount = AccountFactory.createGmwAccount(keyPair, this.self.createdAt) + + const transactionRecipeContext = new CreateTransactionRecipeContext(communityDraft, this.self) + await transactionRecipeContext.run() + this.transactionRecipe = transactionRecipeContext.getTransactionRecipe() + } + + public async store(): Promise { + try { + return await getDataSource().transaction(async (transactionalEntityManager) => { + const community = await transactionalEntityManager.save(this.self) + await transactionalEntityManager.save(this.transactionRecipe) + return community + }) + } 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/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/CommunityRootTransaction.role.ts b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts new file mode 100644 index 000000000..75b885f2f --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/CommunityRootTransaction.role.ts @@ -0,0 +1,25 @@ +import { Community } from '@entity/Community' + +import { KeyPair } from '@/data/KeyPair' +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( + communityDraft: CommunityDraft, + community: Community, + ): CommunityRootTransactionRole { + // create proto transaction body + const transactionBody = new TransactionBodyBuilder() + .fromCommunityDraft(communityDraft, community) + .build() + // build transaction entity + this.transactionBuilder.fromTransactionBody(transactionBody).setCommunity(community) + const transaction = this.transactionBuilder.getTransaction() + // sign + 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 new file mode 100644 index 000000000..8fa3dc443 --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/CreateTransationRecipe.context.ts @@ -0,0 +1,67 @@ +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' + +/** + * @DCI-Context + * Context for create and add Transaction Recipe to DB + */ + +export class CreateTransactionRecipeContext { + private transactionRecipeRole: TransactionRecipeRole + // eslint-disable-next-line no-useless-constructor + public constructor( + private draft: CommunityDraft | TransactionDraft, + private community?: Community, + ) {} + + public getTransactionRecipe(): Transaction { + return this.transactionRecipeRole.getTransaction() + } + + /** + * @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() + // 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) { + throw new TransactionError(TransactionErrorType.MISSING_PARAMETER, 'community was not set') + } + this.transactionRecipeRole = new CommunityRootTransactionRole().createFromCommunityRoot( + this.draft, + this.community, + ) + return true + } + return false + } +} 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 new file mode 100644 index 000000000..d36aa98cc --- /dev/null +++ b/dlt-connector/src/interactions/backendToDb/transaction/TransactionRecipe.role.ts @@ -0,0 +1,70 @@ +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 { 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 + + public constructor() { + this.transactionBuilder = new TransactionBuilder() + } + + 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(signingUser) + if (!signingAccount) { + throw new TransactionError( + TransactionErrorType.NOT_FOUND, + "couldn't found sender user account in db", + ) + } + const recipientAccount = await UserRepository.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) + .setCrossGroupType(transactionTypeRole.getCrossGroupType()) + .setOtherGroup(transactionTypeRole.getOtherGroup()) + + // build transaction entity + this.transactionBuilder + .fromTransactionBodyBuilder(transactionBodyBuilder) + .addBackendTransaction(transactionDraft) + await this.transactionBuilder.setSenderCommunityFromSenderUser(signingUser) + if (recipientUser.communityUuid !== signingUser.communityUuid) { + await this.transactionBuilder.setOtherCommunityFromRecipientUser(recipientUser) + } + const transaction = this.transactionBuilder.getTransaction() + // sign + this.transactionBuilder.setSignature( + new KeyPair(this.transactionBuilder.getCommunity()).sign(transaction.bodyBytes), + ) + return this + } + + public getTransaction(): Transaction { + return this.transactionBuilder.getTransaction() + } +} 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/server/createServer.ts b/dlt-connector/src/server/createServer.ts index 00ba0a912..e02cc3073 100755 --- a/dlt-connector/src/server/createServer.ts +++ b/dlt-connector/src/server/createServer.ts @@ -2,15 +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' 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/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/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..ecdfc1b66 100644 --- a/dlt-connector/src/typeorm/DataSource.ts +++ b/dlt-connector/src/typeorm/DataSource.ts @@ -2,25 +2,88 @@ // 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 { LogError } from '@/server/LogError' +import { logger } from '@/server/logger' -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 { + return this.connection + } + + public async init(): Promise { + await this.connection.initialize() + try { + 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.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?') + } + // return dbVersion ? dbVersion.fileName : null + if (!dbVersion[0].fileName.includes(DB_VERSION)) { + throw new LogError( + `Wrong database version detected - the backend requires '${DB_VERSION}' but found '${ + dbVersion[0].fileName ?? 'None' + }`, + ) + } + } +} + +export const getDataSource = () => Connection.getInstance().getDataSource() diff --git a/dlt-connector/src/utils/derivationHelper.test.ts b/dlt-connector/src/utils/derivationHelper.test.ts new file mode 100644 index 000000000..f14b99cdf --- /dev/null +++ b/dlt-connector/src/utils/derivationHelper.test.ts @@ -0,0 +1,16 @@ +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..d9b1c2356 --- /dev/null +++ b/dlt-connector/src/utils/typeConverter.test.ts @@ -0,0 +1,13 @@ +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..1fc46ee4b 100644 --- a/dlt-connector/src/utils/typeConverter.ts +++ b/dlt-connector/src/utils/typeConverter.ts @@ -1,5 +1,15 @@ 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 { AccountType } from '@/graphql/enum/AccountType' +import { TransactionErrorType } from '@/graphql/enum/TransactionErrorType' +import { TransactionError } from '@/graphql/model/TransactionError' +import { LogError } from '@/server/LogError' +import { logger } from '@/server/logger' + export const uuid4ToBuffer = (uuid: string): Buffer => { // Remove dashes from the UUIDv4 string const cleanedUUID = uuid.replace(/-/g, '') @@ -15,3 +25,83 @@ 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', + ) + } +} + +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 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 457954f7d..63ce78500 100644 --- a/dlt-connector/test/TestDB.ts +++ b/dlt-connector/test/TestDB.ts @@ -1,11 +1,11 @@ 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' +// 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 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..3c7a8bf36 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" @@ -2530,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" @@ -3338,11 +3399,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 +4457,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 +4577,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 +5131,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 +6313,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..7ceaf09cc 100644 --- a/dlt-database/entity/0001-init_db/Account.ts +++ b/dlt-database/entity/0001-init_db/Account.ts @@ -8,8 +8,10 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' -import { TransactionRecipe } from '../TransactionRecipe' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +// 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' import { AccountCommunity } from '../AccountCommunity' diff --git a/dlt-database/entity/0001-init_db/Community.ts b/dlt-database/entity/0001-init_db/Community.ts index 96ddd59d6..943914878 100644 --- a/dlt-database/entity/0001-init_db/Community.ts +++ b/dlt-database/entity/0001-init_db/Community.ts @@ -8,7 +8,8 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +// TransactionRecipe was removed in newer migrations, so only the version from this folder can be linked +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..408a58a69 100644 --- a/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts +++ b/dlt-database/entity/0001-init_db/ConfirmedTransaction.ts @@ -10,8 +10,10 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +// 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') 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 934e81d02..b2acbba75 100644 --- a/dlt-database/entity/0001-init_db/TransactionRecipe.ts +++ b/dlt-database/entity/0001-init_db/TransactionRecipe.ts @@ -10,9 +10,12 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' -import { Community } from '../Community' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +// 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') 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..821b75e73 100644 --- a/dlt-database/entity/0002-refactor_add_community/Account.ts +++ b/dlt-database/entity/0002-refactor_add_community/Account.ts @@ -8,8 +8,10 @@ import { BaseEntity, } from 'typeorm' import { User } from '../User' -import { TransactionRecipe } from '../TransactionRecipe' -import { ConfirmedTransaction } from '../ConfirmedTransaction' +// 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' 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..7136efa2e 100644 --- a/dlt-database/entity/0002-refactor_add_community/Community.ts +++ b/dlt-database/entity/0002-refactor_add_community/Community.ts @@ -8,7 +8,8 @@ import { BaseEntity, } from 'typeorm' import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +// 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' @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 5d2a38f65..1cdc591bf 100644 --- a/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts +++ b/dlt-database/entity/0002-refactor_add_community/ConfirmedTransaction.ts @@ -10,8 +10,10 @@ import { import { Decimal } from 'decimal.js-light' import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' -import { Account } from '../Account' -import { TransactionRecipe } from '../TransactionRecipe' +// 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' @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 new file mode 100644 index 000000000..1c01094f1 --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Account.ts @@ -0,0 +1,89 @@ +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: ['insert', 'update'], 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 }) + 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 }) + 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: 'balance_on_confirmation', + type: 'decimal', + precision: 40, + scale: 20, + default: 0, + transformer: DecimalTransformer, + }) + 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', + type: 'datetime', + nullable: true, + }) + balanceConfirmedAt: Date + + @Column({ + name: 'balance_on_creation', + type: 'decimal', + precision: 40, + scale: 20, + default: 0, + transformer: DecimalTransformer, + }) + balanceOnCreation: Decimal + + @Column({ + name: 'balance_created_at', + type: 'datetime', + precision: 3, + }) + balanceCreatedAt: 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/BackendTransaction.ts b/dlt-database/entity/0003-refactor_transaction_recipe/BackendTransaction.ts new file mode 100644 index 000000000..c84a15f41 --- /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, unique: true }) + backendTransactionId: number + + @ManyToOne(() => Transaction, (transaction) => transaction.backendTransactions) + @JoinColumn({ name: 'transaction_id' }) + transaction: Transaction + + @Column({ name: 'transaction_id', type: 'bigint', unsigned: 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/Community.ts b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts new file mode 100644 index 000000000..1233d0832 --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Community.ts @@ -0,0 +1,64 @@ +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 }) + 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(() => AccountCommunity, (accountCommunity) => accountCommunity.community) + @JoinColumn({ name: 'community_id' }) + accountCommunities: AccountCommunity[] + + @OneToMany(() => Transaction, (transaction) => transaction.community) + transactions?: Transaction[] + + @OneToMany(() => Transaction, (transaction) => transaction.otherCommunity) + friendCommunitiesTransactions?: Transaction[] +} 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..a34823dbd --- /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, unique: true }) + iotaMessageId: Buffer + + @Column({ name: 'error_message', type: 'varchar', length: 255 }) + errorMessage: string +} 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..922bf81cd --- /dev/null +++ b/dlt-database/entity/0003-refactor_transaction_recipe/Transaction.ts @@ -0,0 +1,128 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + 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 { + @PrimaryGeneratedColumn('increment', { unsigned: true, type: 'bigint' }) + id: number + + @Column({ name: 'iota_message_id', type: 'binary', length: 32, nullable: true }) + iotaMessageId?: Buffer + + @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.transactions, { + eager: true, + }) + @JoinColumn({ name: 'community_id' }) + community: Community + + @Column({ name: 'community_id', type: 'int', unsigned: true }) + communityId: number + + @ManyToOne(() => Community, (community) => community.friendCommunitiesTransactions) + @JoinColumn({ name: 'other_community_id' }) + otherCommunity?: Community + + @Column({ name: 'other_community_id', type: 'int', unsigned: true, nullable: true }) + otherCommunityId?: number + + @Column({ + type: 'decimal', + precision: 40, + scale: 20, + nullable: true, + transformer: DecimalTransformer, + }) + amount?: Decimal + + // account balance for sender based on creation date + @Column({ + name: 'account_balance_on_creation', + type: 'decimal', + precision: 40, + scale: 20, + nullable: true, + transformer: DecimalTransformer, + }) + accountBalanceOnCreation?: 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', nullable: true }) + nr?: number + + @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_on_confirmation', + type: 'decimal', + precision: 40, + scale: 20, + nullable: true, + transformer: DecimalTransformer, + }) + accountBalanceOnConfirmation?: Decimal + + @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 + + @OneToMany(() => BackendTransaction, (backendTransaction) => backendTransaction.transaction, { + cascade: ['insert', 'update'], + }) + @JoinColumn({ name: 'transaction_id' }) + backendTransactions: BackendTransaction[] +} 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/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/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/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/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/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/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/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/entity/index.ts b/dlt-database/entity/index.ts index 74c2e2258..b1215263d 100644 --- a/dlt-database/entity/index.ts +++ b/dlt-database/entity/index.ts @@ -1,19 +1,19 @@ import { Account } from './Account' import { AccountCommunity } from './AccountCommunity' +import { BackendTransaction } from './BackendTransaction' 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, + BackendTransaction, 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..0c022cc42 --- /dev/null +++ b/dlt-database/migrations/0003-refactor_transaction_recipe.ts @@ -0,0 +1,156 @@ +/* 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 \`confirmed_transactions\`;`) + await queryFn(`DROP TABLE \`transaction_recipes\`;`) + + await queryFn(` + ALTER TABLE \`accounts\` + RENAME COLUMN \`balance\` TO \`balance_on_confirmation\`, + RENAME COLUMN \`balance_date\` TO \`balance_confirmed_at\` + ; + `) + + await queryFn( + `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\` datetime(3) NOT NULL AFTER \`balance_on_creation\`;`, + ) + await queryFn( + `ALTER TABLE \`accounts\` MODIFY COLUMN \`balance_confirmed_at\` datetime NULL DEFAULT NULL;`, + ) + + await queryFn( + `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, + \`iota_message_id\` varbinary(32) 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, + \`community_id\` int unsigned NOT NULL, + \`other_community_id\` int unsigned NULL DEFAULT NULL, + \`amount\` decimal(40, 20) NULL DEFAULT NULL, + \`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, + \`signature\` varbinary(64) NOT NULL, + \`protocol_version\` varchar(255) NOT NULL DEFAULT '1', + \`nr\` bigint NULL DEFAULT NULL, + \`running_hash\` varbinary(48) NULL DEFAULT NULL, + \`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\`), + UNIQUE KEY \`signature\` (\`signature\`), + FOREIGN KEY (\`signing_account_id\`) REFERENCES accounts(id), + FOREIGN KEY (\`recipient_account_id\`) REFERENCES accounts(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; + `, + ) + + await queryFn( + `CREATE TABLE \`backend_transactions\` ( + \`id\` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, + \`backend_transaction_id\` BIGINT UNSIGNED NOT 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, + \`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; + `, + ) + + 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>) { + 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 \`balance_confirmed_at_date\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);`, + ) + await queryFn(` + ALTER TABLE \`accounts\` + 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 \`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(`DROP TABLE \`backend_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);`, + ) +} diff --git a/federation/src/config/index.ts b/federation/src/config/index.ts index 7a3ceed42..821df574a 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