diff --git a/backend/src/federation/client/1_0/AuthenticationClient.ts b/backend/src/federation/client/1_0/AuthenticationClient.ts index b504c0030..5d897093e 100644 --- a/backend/src/federation/client/1_0/AuthenticationClient.ts +++ b/backend/src/federation/client/1_0/AuthenticationClient.ts @@ -1,11 +1,11 @@ import { FederatedCommunity as DbFederatedCommunity } from 'database' import { GraphQLClient } from 'graphql-request' -import { ensureUrlEndsWithSlash } from '@/util/utilities' +import { ensureUrlEndsWithSlash } from 'core' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' +import { EncryptedTransferArgs } from 'core' import { getLogger } from 'log4js' -import { EncryptedTransferArgs } from 'core/src/graphql/model/EncryptedTransferArgs' import { openConnection } from './query/openConnection' const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.AuthenticationClient`) diff --git a/backend/src/federation/client/1_0/DisbursementClient.ts b/backend/src/federation/client/1_0/DisbursementClient.ts index bf466feef..abaf1818b 100644 --- a/backend/src/federation/client/1_0/DisbursementClient.ts +++ b/backend/src/federation/client/1_0/DisbursementClient.ts @@ -1,8 +1,7 @@ import { FederatedCommunity as DbFederatedCommunity } from 'database' import { GraphQLClient } from 'graphql-request' -import { LogError } from '@/server/LogError' -import { ensureUrlEndsWithSlash } from 'core/src/util/utilities' +import { ensureUrlEndsWithSlash } from 'core' import { getLogger } from 'log4js' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' diff --git a/backend/src/federation/client/1_0/FederationClient.ts b/backend/src/federation/client/1_0/FederationClient.ts index 525765803..c437ad085 100644 --- a/backend/src/federation/client/1_0/FederationClient.ts +++ b/backend/src/federation/client/1_0/FederationClient.ts @@ -4,7 +4,7 @@ import { GraphQLClient } from 'graphql-request' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { getPublicCommunityInfo } from '@/federation/client/1_0/query/getPublicCommunityInfo' import { getPublicKey } from '@/federation/client/1_0/query/getPublicKey' -import { ensureUrlEndsWithSlash } from 'core/src/util/utilities' +import { ensureUrlEndsWithSlash } from 'core' import { getLogger } from 'log4js' import { PublicCommunityInfoLoggingView } from './logging/PublicCommunityInfoLogging.view' diff --git a/backend/src/graphql/model/Transaction.ts b/backend/src/graphql/model/Transaction.ts index ee7250271..0560cef54 100644 --- a/backend/src/graphql/model/Transaction.ts +++ b/backend/src/graphql/model/Transaction.ts @@ -2,9 +2,8 @@ import { Transaction as dbTransaction } from 'database' import { Decimal } from 'decimal.js-light' import { Field, Int, ObjectType } from 'type-graphql' -import { TransactionTypeId } from 'core/src/graphql/enum/TransactionTypeId' +import { Decay, TransactionTypeId } from 'core' -import { Decay } from './Decay' import { User } from './User' @ObjectType() diff --git a/backend/src/graphql/resolver/BalanceResolver.ts b/backend/src/graphql/resolver/BalanceResolver.ts index f7388c027..d49c73c39 100644 --- a/backend/src/graphql/resolver/BalanceResolver.ts +++ b/backend/src/graphql/resolver/BalanceResolver.ts @@ -7,14 +7,14 @@ import { Balance } from '@model/Balance' import { RIGHTS } from '@/auth/RIGHTS' import { BalanceLoggingView } from '@/logging/BalanceLogging.view' -import { DecayLoggingView } from '@/logging/DecayLogging.view' +import { DecayLoggingView } from 'core/src/graphql/logging/DecayLogging.view' import { Context, getUser } from '@/server/context' import { calculateDecay } from 'shared' import { getLogger } from 'log4js' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { GdtResolver } from './GdtResolver' -import { getLastTransaction } from './util/getLastTransaction' +import { getLastTransaction } from 'database' import { transactionLinkSummary } from './util/transactionLinkSummary' @Resolver() diff --git a/backend/src/graphql/resolver/ContributionResolver.ts b/backend/src/graphql/resolver/ContributionResolver.ts index 6e2a302ba..263c5c4aa 100644 --- a/backend/src/graphql/resolver/ContributionResolver.ts +++ b/backend/src/graphql/resolver/ContributionResolver.ts @@ -42,7 +42,7 @@ import { import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context' import { LogError } from '@/server/LogError' import { Context, getClientTimezoneOffset, getUser } from '@/server/context' -import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK' +import { TRANSACTIONS_LOCK } from 'database' import { fullName } from 'core' import { calculateDecay, Decay } from 'shared' @@ -58,7 +58,7 @@ import { import { getOpenCreations, getUserCreation, validateContribution } from './util/creations' import { extractGraphQLFields } from './util/extractGraphQLFields' import { findContributions } from './util/findContributions' -import { getLastTransaction } from './util/getLastTransaction' +import { getLastTransaction } from 'database' import { sendTransactionsToDltConnector } from './util/sendTransactionsToDltConnector' const db = AppDatabase.getInstance() diff --git a/backend/src/graphql/resolver/TransactionLinkResolver.test.ts b/backend/src/graphql/resolver/TransactionLinkResolver.test.ts index 7862f71f0..658d74186 100644 --- a/backend/src/graphql/resolver/TransactionLinkResolver.test.ts +++ b/backend/src/graphql/resolver/TransactionLinkResolver.test.ts @@ -32,7 +32,7 @@ import { listTransactionLinksAdmin } from '@/seeds/graphql/queries' import { transactionLinks } from '@/seeds/transactionLink/index' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { peterLustig } from '@/seeds/users/peter-lustig' -import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK' +import { TRANSACTIONS_LOCK } from 'database' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { getLogger } from 'config-schema/test/testSetup' diff --git a/backend/src/graphql/resolver/TransactionLinkResolver.ts b/backend/src/graphql/resolver/TransactionLinkResolver.ts index 546d11124..cf601a300 100644 --- a/backend/src/graphql/resolver/TransactionLinkResolver.ts +++ b/backend/src/graphql/resolver/TransactionLinkResolver.ts @@ -7,12 +7,11 @@ import { ContributionCycleType } from '@enum/ContributionCycleType' import { ContributionStatus } from '@enum/ContributionStatus' import { ContributionType } from '@enum/ContributionType' import { ContributionLink } from '@model/ContributionLink' -import { Decay } from '@model/Decay' import { RedeemJwtLink } from '@model/RedeemJwtLink' import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink' import { User } from '@model/User' import { QueryLinkResult } from '@union/QueryLinkResult' -import { TransactionTypeId } from 'core' +import { Decay, TransactionTypeId } from 'core' import { AppDatabase, Community as DbCommunity, Contribution as DbContribution, ContributionLink as DbContributionLink, FederatedCommunity as DbFederatedCommunity, Transaction as DbTransaction, @@ -32,16 +31,16 @@ import { } from '@/event/Events' import { LogError } from '@/server/LogError' import { Context, getClientTimezoneOffset, getUser } from '@/server/context' -import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK' -import { TRANSACTION_LINK_LOCK } from '@/util/TRANSACTION_LINK_LOCK' import { calculateBalance } from '@/util/validate' import { fullName } from 'core' +import { TRANSACTION_LINK_LOCK, TRANSACTIONS_LOCK } from 'database' import { calculateDecay, decode, DisburseJwtPayloadType, encode, encryptAndSign, RedeemJwtPayloadType, verify } from 'shared' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { DisbursementClient as V1_0_DisbursementClient } from '@/federation/client/1_0/DisbursementClient' import { DisbursementClientFactory } from '@/federation/client/DisbursementClientFactory' import { EncryptedTransferArgs } from 'core' +import { getLastTransaction } from 'database' import { getLogger, Logger } from 'log4js' import { randombytes_random } from 'sodium-native' import { executeTransaction } from './TransactionResolver' @@ -50,7 +49,6 @@ import { getCommunityByUuid, } from './util/communities' import { getUserCreation, validateContribution } from './util/creations' -import { getLastTransaction } from './util/getLastTransaction' import { sendTransactionsToDltConnector } from './util/sendTransactionsToDltConnector' import { transactionLinkList } from './util/transactionLinkList' diff --git a/backend/src/graphql/resolver/TransactionResolver.test.ts b/backend/src/graphql/resolver/TransactionResolver.test.ts index e39fcefc4..e844ed0a5 100644 --- a/backend/src/graphql/resolver/TransactionResolver.test.ts +++ b/backend/src/graphql/resolver/TransactionResolver.test.ts @@ -13,12 +13,12 @@ import { v4 as uuidv4 } from 'uuid' import { cleanDB, testEnvironment } from '@test/helpers' -import { CONFIG } from '@/config' +// import { CONFIG } from '@/config' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { EventType } from '@/event/Events' -import { SendCoinsClient } from 'core/src/federation/client/1_0/SendCoinsClient' -import { SendCoinsArgs } from 'core/src/federation/client/1_0/model/SendCoinsArgs' -import { SendCoinsResult } from 'core/src/federation/client/1_0/model/SendCoinsResult' +// import { V1_0_SendCoinsClient } from 'core' +// import { SendCoinsArgs } from 'core' +// import { SendCoinsResult } from 'core' import { userFactory } from '@/seeds/factory/user' import { confirmContribution, diff --git a/backend/src/graphql/resolver/TransactionResolver.ts b/backend/src/graphql/resolver/TransactionResolver.ts index 5ceef0836..23e9f415f 100644 --- a/backend/src/graphql/resolver/TransactionResolver.ts +++ b/backend/src/graphql/resolver/TransactionResolver.ts @@ -17,7 +17,7 @@ import { Order } from '@enum/Order' import { Transaction } from '@model/Transaction' import { TransactionList } from '@model/TransactionList' import { User } from '@model/User' -import { TransactionTypeId } from 'core/src/graphql/enum/TransactionTypeId' +import { TransactionTypeId } from 'core' import { SendCoinsResponseJwtPayloadType } from 'shared' import { RIGHTS } from '@/auth/RIGHTS' @@ -29,7 +29,7 @@ import { import { EVENT_TRANSACTION_RECEIVE, EVENT_TRANSACTION_SEND } from '@/event/Events' import { LogError } from '@/server/LogError' import { Context, getUser } from '@/server/context' -import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK' +import { TRANSACTIONS_LOCK } from 'database' import { communityUser } from '@/util/communityUser' import { calculateBalance } from '@/util/validate' import { virtualDecayTransaction, virtualLinkTransaction } from '@/util/virtualTransactions' @@ -44,7 +44,7 @@ import { getLogger, Logger } from 'log4js' import { BalanceResolver } from './BalanceResolver' import { GdtResolver } from './GdtResolver' import { getCommunityByIdentifier, getCommunityName, isHomeCommunity } from './util/communities' -import { getLastTransaction } from './util/getLastTransaction' +import { getLastTransaction } from 'database' import { getTransactionList } from './util/getTransactionList' import { sendTransactionsToDltConnector } from './util/sendTransactionsToDltConnector' import { storeForeignUser } from './util/storeForeignUser' diff --git a/backend/src/util/validate.ts b/backend/src/util/validate.ts index 1dd8a4529..1190e32aa 100644 --- a/backend/src/util/validate.ts +++ b/backend/src/util/validate.ts @@ -2,9 +2,9 @@ import { TransactionLink as dbTransactionLink } from 'database' import { Decimal } from 'decimal.js-light' import { validate, version } from 'uuid' -import { Decay } from '@model/Decay' +import { Decay } from 'core' -import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction' +import { getLastTransaction } from 'database' import { transactionLinkSummary } from '@/graphql/resolver/util/transactionLinkSummary' import { calculateDecay } from 'shared' diff --git a/core/src/federation/client/1_0/SendCoinsClient.ts b/core/src/federation/client/1_0/SendCoinsClient.ts index f4b6d49d8..bb8d2c858 100644 --- a/core/src/federation/client/1_0/SendCoinsClient.ts +++ b/core/src/federation/client/1_0/SendCoinsClient.ts @@ -9,7 +9,7 @@ import { revertSendCoins as revertSendCoinsQuery } from './query/revertSendCoins import { revertSettledSendCoins as revertSettledSendCoinsQuery } from './query/revertSettledSendCoins' import { settleSendCoins as settleSendCoinsQuery } from './query/settleSendCoins' import { voteForSendCoins as voteForSendCoinsQuery } from './query/voteForSendCoins' -import { EncryptedTransferArgs } from 'core' +import { EncryptedTransferArgs } from '@graphql/model/EncryptedTransferArgs' const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.SendCoinsClient`) diff --git a/core/src/federation/client/1_0/logging/SendCoinsArgsLogging.view.ts b/core/src/federation/client/1_0/logging/SendCoinsArgsLogging.view.ts index 4057a2971..1db8c2887 100644 --- a/core/src/federation/client/1_0/logging/SendCoinsArgsLogging.view.ts +++ b/core/src/federation/client/1_0/logging/SendCoinsArgsLogging.view.ts @@ -1,6 +1,6 @@ import { AbstractLoggingView } from 'database' -import { SendCoinsArgs } from 'core/src/federation/client/1_0/model/SendCoinsArgs' +import { SendCoinsArgs } from '@federation/client/1_0/model/SendCoinsArgs' export class SendCoinsArgsLoggingView extends AbstractLoggingView { public constructor(private self: SendCoinsArgs) { diff --git a/core/src/federation/client/1_0/logging/SendCoinsResultLogging.view.ts b/core/src/federation/client/1_0/logging/SendCoinsResultLogging.view.ts index a83e211e8..383f4fd37 100644 --- a/core/src/federation/client/1_0/logging/SendCoinsResultLogging.view.ts +++ b/core/src/federation/client/1_0/logging/SendCoinsResultLogging.view.ts @@ -1,6 +1,6 @@ import { AbstractLoggingView } from 'database' -import { SendCoinsResult } from 'core/src/federation/client/1_0/model/SendCoinsResult' +import { SendCoinsResult } from '@federation/client/1_0/model/SendCoinsResult' export class SendCoinsResultLoggingView extends AbstractLoggingView { public constructor(private self: SendCoinsResult) { diff --git a/core/src/federation/client/1_0/query/voteForSendCoins.ts b/core/src/federation/client/1_0/query/voteForSendCoins.ts index 6fc9a11ae..9b987657c 100644 --- a/core/src/federation/client/1_0/query/voteForSendCoins.ts +++ b/core/src/federation/client/1_0/query/voteForSendCoins.ts @@ -5,13 +5,4 @@ export const voteForSendCoins = gql` voteForSendCoins(data: $args) } ` -/* - { - vote - recipGradidoID - recipFirstName - recipLastName - recipAlias - } - } -*/ + diff --git a/core/src/federation/client/1_1/SendCoinsClient.ts b/core/src/federation/client/1_1/SendCoinsClient.ts index b37f08b29..8c7f9caec 100644 --- a/core/src/federation/client/1_1/SendCoinsClient.ts +++ b/core/src/federation/client/1_1/SendCoinsClient.ts @@ -1,3 +1,3 @@ -import { SendCoinsClient as V1_0_SendCoinsClient } from 'core/src/federation/client/1_0/SendCoinsClient' +import { SendCoinsClient as V1_0_SendCoinsClient } from '@federation/client/1_0/SendCoinsClient' export class SendCoinsClient extends V1_0_SendCoinsClient {} diff --git a/backend/src/logging/DecayLogging.view.ts b/core/src/graphql/logging/DecayLogging.view.ts similarity index 92% rename from backend/src/logging/DecayLogging.view.ts rename to core/src/graphql/logging/DecayLogging.view.ts index 538beecd5..f4f20ab6f 100644 --- a/backend/src/logging/DecayLogging.view.ts +++ b/core/src/graphql/logging/DecayLogging.view.ts @@ -1,6 +1,6 @@ import { AbstractLoggingView } from 'database' -import { Decay } from '@/graphql/model/Decay' +import { Decay } from '@graphql/model/Decay' import type { Decay as DecayInterface } from 'shared' export class DecayLoggingView extends AbstractLoggingView { diff --git a/core/src/graphql/logic/processXComSendCoins.ts b/core/src/graphql/logic/processXComSendCoins.ts index 3b17939d5..a50fa2f8d 100644 --- a/core/src/graphql/logic/processXComSendCoins.ts +++ b/core/src/graphql/logic/processXComSendCoins.ts @@ -18,19 +18,105 @@ import { SendCoinsResult } from '@federation/client/1_0/model/SendCoinsResult' import { SendCoinsClientFactory } from '@federation/client/SendCoinsClientFactory' import { encryptAndSign, PendingTransactionState, SendCoinsJwtPayloadType, SendCoinsResponseJwtPayloadType, verifyAndDecrypt } from 'shared' import { TransactionTypeId } from '@graphql/enum/TransactionTypeId' -import { LogError } from '@server/LogError' +// import { LogError } from '@server/LogError' import { calculateSenderBalance } from '@util/calculateSenderBalance' import { fullName } from '@util/utilities' import { getLogger } from 'log4js' -import { settlePendingSenderTransaction } from '@graphql/resolver/util/settlePendingSenderTransaction' +import { settlePendingSenderTransaction } from './settlePendingSenderTransaction' import { SendCoinsArgsLoggingView } from '@federation/client/1_0/logging/SendCoinsArgsLogging.view' import { SendCoinsResultLoggingView } from '@federation/client/1_0/logging/SendCoinsResultLogging.view' -import { EncryptedTransferArgs } from 'core' +import { EncryptedTransferArgs } from '@graphql/model/EncryptedTransferArgs' import { randombytes_random } from 'sodium-native' const createLogger = (method: string) => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.processXComSendCoins.${method}`) +/* +export async function processXComTransaction( + receiverCom: DbCommunity, + senderCom: DbCommunity, + creationDate: Date, + amount: Decimal, + memo: string, + sender: dbUser, + recipientIdentifier: string, +): Promise { + const methodLogger = createLogger(`processXComTransaction`) + // processing a x-community sendCoins + methodLogger.info('X-Com: processing a x-community transaction...') + if (!CONFIG.FEDERATION_XCOM_SENDCOINS_ENABLED) { + throw new LogError('X-Community sendCoins disabled per configuration!') + } + const recipCom = await getCommunityByIdentifier(recipientCommunityIdentifier) + methodLogger.debug('recipient community: ', recipCom?.id) + if (recipCom === null) { + throw new LogError( + `no recipient community found for identifier: ${recipientCommunityIdentifier}`, + ) + } + if (recipCom !== null && recipCom.authenticatedAt === null) { + throw new LogError('recipient community is connected, but still not authenticated yet!') + } + let pendingResult: SendCoinsResponseJwtPayloadType | null = null + let committingResult: SendCoinsResult + const creationDate = new Date() + try { + pendingResult = await processXComPendingSendCoins( + recipCom, + homeCom, + creationDate, + amount, + memo, + senderUser, + recipientIdentifier, + ) + methodLogger.debug('processXComPendingSendCoins result: ', pendingResult) + if (pendingResult && pendingResult.vote && pendingResult.recipGradidoID) { + methodLogger.debug('vor processXComCommittingSendCoins... ') + committingResult = await processXComCommittingSendCoins( + recipCom, + homeCom, + creationDate, + amount, + memo, + senderUser, + pendingResult, + ) + methodLogger.debug('processXComCommittingSendCoins result: ', committingResult) + if (!committingResult.vote) { + methodLogger.fatal('FATAL ERROR: on processXComCommittingSendCoins for', committingResult) + throw new LogError( + 'FATAL ERROR: on processXComCommittingSendCoins with ', + recipientCommunityIdentifier, + recipientIdentifier, + amount.toString(), + memo, + ) + } + // after successful x-com-tx store the recipient as foreign user + methodLogger.debug('store recipient as foreign user...') + if (await storeForeignUser(recipCom, committingResult)) { + methodLogger.info( + 'X-Com: new foreign user inserted successfully...', + recipCom.communityUuid, + committingResult.recipGradidoID, + ) + } + } + } catch (err) { + const errmsg = `ERROR: on processXComCommittingSendCoins with ` + + recipientCommunityIdentifier + + recipientIdentifier + + amount.toString() + + memo + + err + methodLogger.error(errmsg) + throw new Error(errmsg) + } + return true +} +*/ +/* export async function processXComPendingSendCoins( receiverCom: DbCommunity, senderCom: DbCommunity, @@ -82,6 +168,149 @@ export async function processXComPendingSendCoins( }) const client = SendCoinsClientFactory.getInstance(receiverFCom) + if (client instanceof V1_0_SendCoinsClient) { + const payload = new SendCoinsJwtPayloadType(handshakeID, + receiverCom.communityUuid!, + recipientIdentifier, + creationDate.toISOString(), + amount, + memo, + senderCom.communityUuid!, + sender.gradidoID, + fullName(sender.firstName, sender.lastName), + sender.alias + ) + if(methodLogger.isDebugEnabled()) { + methodLogger.debug(`ready for voteForSendCoins with payload=${payload}`) + } + const jws = await encryptAndSign(payload, senderCom.privateJwtKey!, receiverCom.publicJwtKey!) + if(methodLogger.isDebugEnabled()) { + methodLogger.debug('jws', jws) + } + // prepare the args for the client invocation + const args = new EncryptedTransferArgs() + args.publicKey = senderCom.publicKey.toString('hex') + args.jwt = jws + args.handshakeID = handshakeID + if(methodLogger.isDebugEnabled()) { + methodLogger.debug('before client.voteForSendCoins() args:', args) + } + + const responseJwt = await client.voteForSendCoins(args) + if(methodLogger.isDebugEnabled()) { + methodLogger.debug(`response of voteForSendCoins():`, responseJwt) + } + if (responseJwt !== null) { + voteResult = await verifyAndDecrypt(handshakeID, responseJwt, senderCom.privateJwtKey!, receiverCom.publicJwtKey!) as SendCoinsResponseJwtPayloadType + if(methodLogger.isDebugEnabled()) { + methodLogger.debug(`calculated voteResult = ${JSON.stringify(voteResult, null, 2)}`) + } + if (voteResult && voteResult.vote && voteResult.recipGradidoID) { + methodLogger.debug('vor processXComCommittingSendCoins... ') + const committingResult = await processXComCommittingSendCoins( + receiverCom, + senderCom, + creationDate, + amount, + memo, + sender, + voteResult, + ) + methodLogger.debug('processXComCommittingSendCoins result: ', committingResult) + if (!committingResult.vote) { + methodLogger.fatal('FATAL ERROR: on processXComCommittingSendCoins for', committingResult) + throw new LogError( + 'FATAL ERROR: on processXComCommittingSendCoins with ', + recipientCommunityIdentifier, + recipientIdentifier, + amount.toString(), + memo, + ) + } + // after successful x-com-tx store the recipient as foreign user + methodLogger.debug('store recipient as foreign user...') + if (await storeForeignUser(receiverCom, committingResult)) { + methodLogger.info( + 'X-Com: new foreign user inserted successfully...', + receiverCom.communityUuid, + committingResult.recipGradidoID, + ) + } + } + } + } else { + const errmsg = `Client is not instance of V1_0_SendCoinsClient` + methodLogger.error(errmsg) + throw new LogError(errmsg) + } + } catch (err) { + const errmsg = `ERROR: on processXComCommittingSendCoins with ` + + recipientCommunityIdentifier + + recipientIdentifier + + amount.toString() + + memo + + err + throw new LogError(errmsg) + } +} + memo, + err, + ) + } + } +} +*/ +export async function processXComPendingSendCoins( + receiverCom: DbCommunity, + senderCom: DbCommunity, + creationDate: Date, + amount: Decimal, + memo: string, + sender: dbUser, + recipientIdentifier: string, +): Promise { + let voteResult: SendCoinsResponseJwtPayloadType + const methodLogger = createLogger(`processXComPendingSendCoins`) + try { + // even if debug is not enabled, attributes are processed so we skip the entire call for performance reasons + if(methodLogger.isDebugEnabled()) { + methodLogger.debug( + 'XCom: processXComPendingSendCoins...', { + receiverCom: new CommunityLoggingView(receiverCom), + senderCom: new CommunityLoggingView(senderCom), + amount: amount.toString(), + memo: memo.substring(0, 5), + sender: new UserLoggingView(sender), + recipientIdentifier + } + ) + } + if (await countOpenPendingTransactions([sender.gradidoID, recipientIdentifier]) > 0) { + const errmsg = `There exist still ongoing 'Pending-Transactions' for the involved users on sender-side!` + methodLogger.error(errmsg) + throw new Error(errmsg) + } + const handshakeID = randombytes_random().toString() + methodLogger.addContext('handshakeID', handshakeID) + // first calculate the sender balance and check if the transaction is allowed + const senderBalance = await calculateSenderBalance(sender.id, amount.mul(-1), creationDate) + if (!senderBalance) { + const errmsg = `User has not enough GDD or amount is < 0` + methodLogger.error(errmsg) + throw new Error(errmsg) + } + if(methodLogger.isDebugEnabled()) { + methodLogger.debug(`calculated senderBalance = ${JSON.stringify(senderBalance, null, 2)}`) + } + + const receiverFCom = await DbFederatedCommunity.findOneOrFail({ + where: { + publicKey: Buffer.from(receiverCom.publicKey), + apiVersion: CONFIG.FEDERATION_BACKEND_SEND_ON_API, + }, + }) + const client = SendCoinsClientFactory.getInstance(receiverFCom) + if (client instanceof V1_0_SendCoinsClient) { const payload = new SendCoinsJwtPayloadType(handshakeID, receiverCom.communityUuid!, diff --git a/backend/src/graphql/resolver/util/settlePendingSenderTransaction.ts b/core/src/graphql/logic/settlePendingSenderTransaction.ts similarity index 85% rename from backend/src/graphql/resolver/util/settlePendingSenderTransaction.ts rename to core/src/graphql/logic/settlePendingSenderTransaction.ts index c528b0ca7..8abd511c1 100644 --- a/backend/src/graphql/resolver/util/settlePendingSenderTransaction.ts +++ b/core/src/graphql/logic/settlePendingSenderTransaction.ts @@ -10,17 +10,16 @@ import { } from 'database' import { Decimal } from 'decimal.js-light' -import { PendingTransactionState } from 'shared' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' -import { LogError } from '@/server/LogError' -import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK' -import { calculateSenderBalance } from '@/util/calculateSenderBalance' +import { PendingTransactionState } from 'shared' +// import { LogError } from '@/server/LogError' +import { calculateSenderBalance } from 'core' +import { TRANSACTIONS_LOCK, getLastTransaction } from 'database' import { getLogger } from 'log4js' -import { getLastTransaction } from './getLastTransaction' const db = AppDatabase.getInstance() const logger = getLogger( - `${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.settlePendingSenderTransaction`, + `${LOG4JS_BASE_CATEGORY_NAME}.graphql.logic.settlePendingSenderTransaction`, ) export async function settlePendingSenderTransaction( @@ -53,15 +52,17 @@ export async function settlePendingSenderTransaction( ], }) if (openSenderPendingTx > 1 || openReceiverPendingTx > 1) { - throw new LogError('There are more than 1 pending Transactions for Sender and/or Recipient') + const errmsg = `There are more than 1 pending Transactions for Sender and/or Recipient` + logger.error(errmsg) + throw new Error(errmsg) } const lastTransaction = await getLastTransaction(senderUser.id) if (lastTransaction?.id !== pendingTx.previous) { - throw new LogError( - `X-Com: missmatching transaction order! lastTransationId=${lastTransaction?.id} != pendingTx.previous=${pendingTx.previous}`, - ) + const errmsg = `X-Com: missmatching transaction order! lastTransationId=${lastTransaction?.id} != pendingTx.previous=${pendingTx.previous}` + logger.error(errmsg) + throw new Error(errmsg) } // transfer the pendingTx to the transactions table @@ -82,7 +83,9 @@ export async function settlePendingSenderTransaction( pendingTx.balanceDate, ) if (!sendBalance) { - throw new LogError(`Sender has not enough GDD or amount is < 0', sendBalance`) + const errmsg = 'Sender has not enough GDD or amount is < 0' + logger.error(errmsg) + throw new Error(errmsg) } transactionSend.balance = sendBalance?.balance ?? new Decimal(0) transactionSend.balanceDate = pendingTx.balanceDate @@ -114,7 +117,8 @@ export async function settlePendingSenderTransaction( // void sendTransactionsToDltConnector() } catch (e) { await queryRunner.rollbackTransaction() - throw new LogError('X-Com: send Transaction was not successful', e) + logger.error('X-Com: send Transaction was not successful', e) + throw new Error('X-Com: send Transaction was not successful') } finally { await queryRunner.release() releaseLock() diff --git a/backend/src/graphql/model/Decay.ts b/core/src/graphql/model/Decay.ts similarity index 100% rename from backend/src/graphql/model/Decay.ts rename to core/src/graphql/model/Decay.ts diff --git a/core/src/index.ts b/core/src/index.ts index 3aa4a63d8..9ee34cc19 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -1,3 +1,4 @@ +export {SendCoinsClient as V1_0_SendCoinsClient} from './federation/client/1_0/SendCoinsClient' export * from './federation/client/1_0/logging/SendCoinsArgsLogging.view' export * from './federation/client/1_0/logging/SendCoinsResultLogging.view' export * from './federation/client/1_0/model/SendCoinsArgs' @@ -6,12 +7,16 @@ export * from './federation/client/1_0/query/revertSendCoins' export * from './federation/client/1_0/query/revertSettledSendCoins' export * from './federation/client/1_0/query/settleSendCoins' export * from './federation/client/1_0/query/voteForSendCoins' +export {SendCoinsClient as V1_1_SendCoinsClient} from './federation/client/1_1/SendCoinsClient' export * from './federation/client/SendCoinsClientFactory' export * from './federation/enum/apiVersionType' export * from './graphql/enum/TransactionTypeId' +export * from './graphql/logging/DecayLogging.view' export * from './graphql/logic/interpretEncryptedTransferArgs' export * from './graphql/logic/processXComSendCoins' +export * from './graphql/model/Decay' export * from './graphql/model/EncryptedTransferArgs' +export * from './util/calculateSenderBalance' export * from './util/utilities' export * from './validation/user' diff --git a/backend/src/util/calculateSenderBalance.ts b/core/src/util/calculateSenderBalance.ts similarity index 83% rename from backend/src/util/calculateSenderBalance.ts rename to core/src/util/calculateSenderBalance.ts index a01b1f15e..ce7609895 100644 --- a/backend/src/util/calculateSenderBalance.ts +++ b/core/src/util/calculateSenderBalance.ts @@ -1,8 +1,8 @@ import { Decimal } from 'decimal.js-light' -import { Decay } from '@model/Decay' +import { Decay } from '@graphql/model/Decay' -import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction' +import { getLastTransaction } from 'database' import { calculateDecay } from 'shared' diff --git a/database/package.json b/database/package.json index 6a6240fa1..26aa6b9e1 100644 --- a/database/package.json +++ b/database/package.json @@ -41,6 +41,7 @@ "@types/geojson": "^7946.0.13", "@types/jest": "27.0.2", "@types/node": "^18.7.14", + "await-semaphore": "^0.1.3", "crypto-random-bigint": "^2.1.1", "jest": "27.2.4", "ts-jest": "27.0.5", diff --git a/database/src/index.ts b/database/src/index.ts index 3ff4efa17..56dec24ee 100644 --- a/database/src/index.ts +++ b/database/src/index.ts @@ -60,4 +60,5 @@ export const entities = [ export { latestDbVersion } export * from './logging' export * from './queries' +export * from './util' export { AppDatabase } from './AppDatabase' diff --git a/database/src/queries/index.ts b/database/src/queries/index.ts index 9acf80871..b8ca12b86 100644 --- a/database/src/queries/index.ts +++ b/database/src/queries/index.ts @@ -3,5 +3,6 @@ import { LOG4JS_BASE_CATEGORY_NAME } from '../config/const' export * from './user' export * from './communities' export * from './pendingTransactions' +export * from './transactions' export const LOG4JS_QUERIES_CATEGORY_NAME = `${LOG4JS_BASE_CATEGORY_NAME}.queries` diff --git a/backend/src/graphql/resolver/util/getLastTransaction.ts b/database/src/queries/transactions.ts similarity index 100% rename from backend/src/graphql/resolver/util/getLastTransaction.ts rename to database/src/queries/transactions.ts diff --git a/backend/src/util/TRANSACTIONS_LOCK.ts b/database/src/util/TRANSACTIONS_LOCK.ts similarity index 100% rename from backend/src/util/TRANSACTIONS_LOCK.ts rename to database/src/util/TRANSACTIONS_LOCK.ts diff --git a/backend/src/util/TRANSACTION_LINK_LOCK.ts b/database/src/util/TRANSACTION_LINK_LOCK.ts similarity index 100% rename from backend/src/util/TRANSACTION_LINK_LOCK.ts rename to database/src/util/TRANSACTION_LINK_LOCK.ts diff --git a/database/src/util/index.ts b/database/src/util/index.ts new file mode 100644 index 000000000..b16b20d19 --- /dev/null +++ b/database/src/util/index.ts @@ -0,0 +1,2 @@ +export * from './TRANSACTIONS_LOCK' +export * from './TRANSACTION_LINK_LOCK' \ No newline at end of file diff --git a/federation/src/client/1_0/AuthenticationClient.ts b/federation/src/client/1_0/AuthenticationClient.ts index 60a205aa7..ac14bcb84 100644 --- a/federation/src/client/1_0/AuthenticationClient.ts +++ b/federation/src/client/1_0/AuthenticationClient.ts @@ -3,7 +3,7 @@ import { GraphQLClient } from 'graphql-request' import { getLogger, Logger } from 'log4js' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' -import { EncryptedTransferArgs } from 'core/src/graphql/model/EncryptedTransferArgs' +import { EncryptedTransferArgs } from 'core' import { authenticate } from './query/authenticate' import { openConnectionCallback } from './query/openConnectionCallback'