All files Verifyer.js

69.14% Statements 112/162
67.01% Branches 65/97
88.89% Functions 40/45
68.39% Lines 106/155

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480                1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                   25x         24x 24x   24x     24x 24x   24x 24x     1x       20x 20x     20x           20x         20x 13x     13x     13x   10x             10x   3x   3x     3x     3x 3x   7x         7x                     7x 7x               10x   10x 8x 8x 8x   4x 4x             4x     4x 4x           1x   3x                       10x                     10x 10x           16x   6x         5x   5x                           5x                         5x   4x           4x     4x 4x     4x             4x 4x               4x                                             3x                               3x     3x 3x     3x             3x 3x               3x                                                       3x 2x 2x   3x   3x                           3x 1x       2x             3x     3x 3x     3x             3x 3x               3x                                                             8x     8x 4x 4x 4x                       17x 17x 17x               24x 24x             24x         24x             24x   24x 24x         24x          
import logger from 'winston';
import { LiquidPledging } from 'giveth-liquidpledging';
import getGasPrice from './gasPrice';
import { sendEmail } from './utils';
import ForeignGivethBridge from './ForeignGivethBridge';
 
export default class Verifier {
    constructor(homeWeb3, foreignWeb3, nonceTracker, config, db) {
        this.homeWeb3 = homeWeb3;
        this.foreignWeb3 = foreignWeb3;
        this.nonceTracker = nonceTracker;
        this.db = db;
        this.config = config;
        this.lp = new LiquidPledging(foreignWeb3, config.liquidPledging);
        this.foreignBridge = new ForeignGivethBridge(foreignWeb3, config.foreignBridge);
        this.currentHomeBlockNumber = undefined;
        this.currentForeignBlockNumber = undefined;
        this.account = homeWeb3.eth.accounts.wallet[0];
    }
 
    /* istanbul ignore next */
    start() {
        const intervalId = setInterval(() => this.verify(), this.config.pollTime);
        this.verify();
    }
 
    verify() {
        return Promise.all([
            this.homeWeb3.eth.getBlockNumber(),
            this.foreignWeb3.eth.getBlockNumber(),
        ])
            .then(([homeBlockNumber, foreignBlockNumber]) => {
                this.currentHomeBlockNumber = homeBlockNumber;
                this.currentForeignBlockNumber = foreignBlockNumber;
 
                return Promise.all([this.getFailedSendTxs(), this.getPendingTxs()]);
            })
            .then(([failedTxs, pendingTxs]) => {
                const failedPromises = failedTxs.map(tx => this.verifyTx(tx));
                const pendingPromises = pendingTxs.map(tx => this.verifyTx(tx));
 
                Eif (this.config.isTest) {
                    return Promise.all([...failedPromises, ...pendingPromises]);
                }
            })
            .catch(err => console.error('Failed to fetch block number ->', err));
    }
 
    verifyTx(tx) {
        const web3 = tx.toHomeBridge ? this.homeWeb3 : this.foreignWeb3;
        const currentBlock = tx.toHomeBridge
            ? this.currentHomeBlockNumber
            : this.currentForeignBlockNumber;
        const confirmations = tx.toHomeBridge
            ? this.config.homeConfirmations
            : this.foreignConfirmations;
 
        // order matters here
        const txHash =
            tx.reSendGiverTxHash ||
            tx.reSendReceiverTxHash ||
            tx.reSendCreateGiverTxHash ||
            tx.txHash;
 
        if (tx.status === 'pending') {
            return web3.eth
                .getTransactionReceipt(txHash)
                .then(receipt => {
                    Iif (!receipt) return; // not mined
 
                    // only update if we have enough confirmations
                    if (currentBlock - receipt.blockNumber <= confirmations) return;
 
                    Eif (
                        receipt.status === true ||
                        receipt.status === '0x01' ||
                        receipt.status === '0x1' ||
                        receipt.status === 1
                    ) {
                        // this was a createGiver tx, we still need to transfer the funds to the giver
                        if (txHash === tx.reSendCreateGiverTxHash) {
                            // GiverAdded event topic
                            const { topics } = receipt.logs.find(
                                l =>
                                    l.topics[0] ===
                                    '0xad9c62a4382fd0ddbc4a0cf6c2bc7df75b0b8beb786ff59014f39daaea7f232f',
                            );
                            tx.giverId = this.homeWeb3.utils.hexToNumber(topics[1]); // idGiver is 1st indexed param, thus 2nd topic
                            // we call handleFailedTx b/c this is still a failed tx. It is just multi-step b/c we needed to create a
                            // giver.
                            logger.debug('successfully created a giver ->', tx.giverId);
                            return this.handleFailedTx(tx);
                        }
                        this.updateTxData(
                            Object.assign(tx, {
                                status: 'confirmed',
                            }),
                        );
                        return;
                    }
 
                    return this.handleFailedTx(tx);
                })
                .catch(err => {
                    // ignore unknown tx b/c it is probably too early to check
                    if (!err.message.includes('unknown transaction')) {
                        logger.error('Failed to fetch tx receipt for tx', tx, err);
                    }
                });
        } else Eif (tx.status === 'failed-send') {
            return this.handleFailedTx(tx);
        } else {
            sendEmail(this.config, `Unknown tx status \n\n ${JSON.stringify(tx, null, 2)}`);
            logger.error('Unknown tx status ->', tx);
        }
    }
 
    handleFailedTx(tx) {
        const web3 = tx.toHomeBridge ? this.homeWeb3 : this.foreignWeb3;
 
        const handleFailedReceiver = () =>
            this.fetchAdmin(tx.receiverId).then(admin => {
                logger.debug('handling failed receiver ->', tx.receiverId, admin, tx);
                if (!admin || admin.adminType === '0') {
                    // giver
                    return this.sendToGiver(tx);
                } else Iif (admin.adminType === '1') {
                    // delegate
                    if (tx.reSendCreateGiver && !tx.reSendReceiver) {
                        // giver failed, so try to send to receiver now
                        return this.sendToReceiver(tx, tx.receiverId);
                    }
                    return this.sendToGiver(tx);
                } else Eif (admin.adminType === '2') {
                    // project
                    // check if there is a parentProject we can send to if project is canceled
                    return this.getParentProjectNotCanceled(tx.receiverId).then(projectId => {
                        if (
                            !projectId ||
                            (projectId === tx.receiverId &&
                                (!tx.reSendCreateGiver || tx.reSendReceiver)) ||
                            projectId == 0
                        )
                            return this.sendToGiver(tx);
 
                        return this.sendToReceiver(tx, projectId);
                    });
                } else {
                    // shouldn't get here
                    sendEmail(
                        this.config,
                        `Unknown receiver adminType \n\n ${JSON.stringify(tx, null, 2)}`,
                    );
                    logger.error('Unknown receiver adminType ->', tx);
                }
            });
 
        Iif (tx.toHomeBridge) {
            // this shouldn't fail, send email as we need to investigate
            sendEmail(
                this.config,
                `AuthorizePayment tx failed toHomeBridge \n\n ${JSON.stringify(tx, null, 2)}`,
            );
            logger.error('AuthorizePayment tx failed toHomeBridge ->', tx);
        } else {
            // check that the giver is valid
            // if we don't have a giverId, we don't need to fetch the admin b/c this was a
            // donateAndCreateGiver call and we need to handle the failed receiver
            return (tx.giverId ? this.fetchAdmin(tx.giverId) : Promise.resolve(true)).then(
                giverAdmin => (giverAdmin ? handleFailedReceiver() : this.createGiver(tx)),
            );
        }
    }
 
    fetchAdmin(id) {
        return this.lp.getPledgeAdmin(id).catch(e => {
            // receiver may not exist, catch error and pass undefined
            logger.debug('Failed to fetch pledgeAdmin for adminId ->', id, e);
        });
    }
 
    sendToGiver(tx) {
        logger.debug('send to Giver');
        // already attempted to send to giver, notify of failure
        Iif (tx.reSendGiver) {
            this.updateTxData(Object.assign(tx, { status: 'failed' }));
            sendEmail(
                this.config,
                `ForeignBridge sendToGiver  Tx failed. NEED TO TAKE ACTION \n\n${JSON.stringify(
                    tx,
                    null,
                    2,
                )}`,
            );
            logger.error('ForeignBridge sendToGiver Tx failed. NEED TO TAKE ACTION ->', tx);
            return;
        }
 
        Iif (!tx.giver && !tx.giverId) {
            sendEmail(
                this.config,
                `Tx missing giver and giverId. Can't sendToGiver \n\n ${JSON.stringify(
                    tx,
                    null,
                    2,
                )}`,
            );
            logger.error('Tx missing giver and giverId. Cant sendToGiver ->', tx);
            return;
        }
 
        if (tx.giver && !tx.giverId) return this.createGiver(tx);
 
        const data = this.lp.$contract.methods
            .donate(tx.giverId, tx.giverId, tx.sideToken, tx.amount)
            .encodeABI();
 
        let nonce;
        let txHash;
        return this.nonceTracker
            .obtainNonce()
            .then(n => {
                nonce = n;
                return getGasPrice(this.config, false);
            })
            .then(gasPrice =>
                this.foreignBridge.bridge
                    .deposit(tx.sender, tx.mainToken, tx.amount, tx.homeTx, data, {
                        from: this.account.address,
                        nonce,
                        gasPrice,
                    })
                    .on('transactionHash', transactionHash => {
                        this.nonceTracker.releaseNonce(nonce);
                        this.updateTxData(
                            Object.assign(tx, {
                                status: 'pending',
                                reSend: true,
                                reSendGiver: true,
                                reSendGiverTxHash: transactionHash,
                            }),
                        );
                        txHash = transactionHash;
                    })
                    .catch((err, receipt) => {
                        logger.debug('ForeignBridge resend tx error ->', err, receipt, txHash);
 
                        // if we have a txHash, then we will pick on the next run
                        if (!txHash) {
                            this.nonceTracker.releaseNonce(nonce, false, false);
                            this.updateTxData(
                                Object.assign(tx, {
                                    status: 'failed-send',
                                    reSend: true,
                                    reSendGiverTxHash: false,
                                    reSendGiver: true,
                                    reSendGiverError: err,
                                }),
                            );
                        }
                    }),
            );
    }
 
    createGiver(tx) {
        Iif (tx.reSendCreateGiver) {
            this.updateTxData(Object.assign(tx, { status: 'failed' }));
            sendEmail(
                this.config,
                `ForeignBridge createGiver Tx failed. NEED TO TAKE ACTION \n\n${JSON.stringify(
                    tx,
                    null,
                    2,
                )}`,
            );
            logger.error('ForeignBridge createGiver Tx failed. NEED TO TAKE ACTION ->', tx);
            return;
        }
 
        let nonce;
        let txHash;
        return this.nonceTracker
            .obtainNonce()
            .then(n => {
                nonce = n;
                return getGasPrice(this.config, false);
            })
            .then(gasPrice =>
                this.lp
                    .addGiver(tx.giver || tx.sender, '', '', 259200, 0, {
                        from: this.account.address,
                        nonce,
                        gasPrice,
                    })
                    .on('transactionHash', transactionHash => {
                        this.nonceTracker.releaseNonce(nonce);
                        this.updateTxData(
                            Object.assign(tx, {
                                status: 'pending',
                                reSend: true,
                                reSendCreateGiver: true,
                                reSendCreateGiverTxHash: transactionHash,
                            }),
                        );
                        txHash = transactionHash;
                    })
                    .catch((err, receipt) => {
                        logger.debug(
                            'ForeignBridge resend createGiver tx error ->',
                            err,
                            receipt,
                            txHash,
                        );
 
                        // if we have a txHash, then we will pick on the next run
                        if (!txHash) {
                            this.nonceTracker.releaseNonce(nonce, false, false);
                            this.updateTxData(
                                Object.assign(tx, {
                                    status: 'failed-send',
                                    reSend: true,
                                    reSendCreateGiverError: err,
                                    reSendCreateGiverTxHash: false,
                                    reSendCreateGiver: true,
                                }),
                            );
                        }
                    }),
            );
    }
 
    sendToReceiver(tx, newReceiverId) {
        if (tx.receiverId !== newReceiverId) {
            Eif (!tx.attemptedReceiverIds) tx.attemptedReceiverIds = [tx.receiverId];
            tx.attemptedReceiverIds.push(newReceiverId);
        }
        tx.receiverId = newReceiverId;
 
        Iif (!tx.giver && !tx.giverId) {
            sendEmail(
                this.config,
                `Tx missing giver and giverId. Can't sendToParentProject\n\n ${JSON.stringify(
                    tx,
                    null,
                    2,
                )}`,
            );
            logger.error('Tx missing giver and giverId. Cant sendToParentProject ->', tx);
            return;
        }
 
        let data;
        if (tx.giver) {
            data = this.lp.$contract.methods
                .addGiverAndDonate(tx.receiverId, tx.giver, tx.sideToken, tx.amount)
                .encodeABI();
        } else {
            data = this.lp.$contract.methods
                .donate(tx.giverId, tx.receiverId, tx.sideToken, tx.amount)
                .encodeABI();
        }
 
        let nonce;
        let txHash;
        return this.nonceTracker
            .obtainNonce()
            .then(n => {
                nonce = n;
                return getGasPrice(this.config);
            })
            .then(gasPrice =>
                this.foreignBridge.bridge
                    .deposit(tx.sender, tx.mainToken, tx.amount, tx.homeTx, data, {
                        from: this.account.address,
                        nonce,
                        gasPrice,
                    })
                    .on('transactionHash', transactionHash => {
                        this.nonceTracker.releaseNonce(nonce);
                        this.updateTxData(
                            Object.assign(tx, {
                                status: 'pending',
                                reSend: true,
                                reSendReceiver: true,
                                reSendReceiverTxHash: transactionHash,
                            }),
                        );
                        txHash = transactionHash;
                    })
                    .catch((err, receipt) => {
                        logger.debug('ForeignBridge resend tx error ->', err, receipt, txHash);
 
                        // if we have a txHash, then we will pick on the next run
                        if (!txHash) {
                            this.nonceTracker.releaseNonce(nonce, false, false);
                            this.updateTxData(
                                Object.assign(tx, {
                                    status: 'failed-send',
                                    reSend: true,
                                    reSendReceiver: true,
                                    reSendReceiverTxHash: false,
                                    reSendReceiverError: err,
                                }),
                            );
                        }
                    }),
            );
    }
 
    /**
     * if projectId is active, return projectId
     * otherwise returns first parentProject that is active
     * return undefined if no active project found
     *
     * @param {*} projectId
     * @returns Promise(projectId)
     */
    getParentProjectNotCanceled(projectId) {
        return this.lp
            .isProjectCanceled(projectId)
            .then(isCanceled => {
                if (!isCanceled) return projectId;
                return this.lp.getPledgeAdmin(projectId).then(admin => {
                    Eif (admin.parentProject)
                        return this.getParentProjectNotCanceled(admin.parentProject);
 
                    return undefined;
                });
            })
            .catch(e => {
                logger.debug('Failed to getParentProjectNotCanceled =>', projectId);
                return undefined;
            });
    }
 
    updateTxData(data) {
        const { _id } = data;
        this.db.txs.update({ _id }, data, {}, err => {
            Iif (err) {
                logger.error('Error updating bridge-txs.db ->', err, data);
                process.exit();
            }
        });
    }
 
    getFailedSendTxs() {
        return new Promise((resolve, reject) => {
            this.db.txs.find(
                {
                    status: 'failed-send',
                    $or: [{ reSend: { $exists: false } }, { reSend: false }],
                    $or: [{ notified: { $exists: false } }, { notified: false }],
                },
                (err, data) => {
                    Iif (err) {
                        logger.error('Error fetching failed-send txs from db ->', err);
                        resolve([]);
                        return;
                    }
                    resolve(data);
                },
            );
        });
    }
 
    getPendingTxs() {
        return new Promise((resolve, reject) => {
            // this.db.txs.find({ status: 'pending' }, (err, data) => err ? reject(err) : resolve(Array.isArray(data) ? data : [data]))
            this.db.txs.find({ status: 'pending' }, (err, data) => {
                Iif (err) {
                    logger.error('Error fetching pending txs from db ->', err);
                    resolve([]);
                    return;
                }
                resolve(data);
            });
        });
    }
}