コード例 #1
0
        private async Task Sync(Source source, Event replacementCompletedEvent, OTContract contract,
                                MySqlConnection connection, Web3 cl, int blockchainID, EthApiService eth, ulong currentStart, ulong currentEnd)
        {
            var toBlock = new BlockParameter(currentEnd);

            var replacementCompletedEvents = await replacementCompletedEvent.GetAllChangesDefault(
                replacementCompletedEvent.CreateFilterInput(new BlockParameter(currentStart),
                                                            toBlock));


            if (replacementCompletedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + replacementCompletedEvents.Count + " replacement completed events");
            }

            foreach (EventLog <List <ParameterOutput> > eventLog in replacementCompletedEvents)
            {
                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);

                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                var challengerIdentity = (string)eventLog.Event
                                         .First(e => e.Parameter.Name == "challengerIdentity").Result;

                var chosenHolder = (string)eventLog.Event
                                   .First(e => e.Parameter.Name == "chosenHolder").Result;

                var transaction = await eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                var receipt = await eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                var row = new OTContract_Replacement_ReplacementCompleted
                {
                    TransactionHash    = eventLog.Log.TransactionHash,
                    BlockNumber        = (UInt64)eventLog.Log.BlockNumber.Value,
                    Timestamp          = block.Timestamp,
                    OfferId            = offerId,
                    ChosenHolder       = chosenHolder,
                    ChallengerIdentity = challengerIdentity,
                    GasPrice           = (UInt64)transaction.GasPrice.Value,
                    GasUsed            = (UInt64)receipt.GasUsed.Value,
                    BlockchainID       = blockchainID
                };

                await OTContract_Replacement_ReplacementCompleted.InsertIfNotExist(connection, row);

                await OTOfferHolder.Insert(connection, offerId, chosenHolder, false, blockchainID);

                await OTOfferHolder.UpdateLitigationStatusesForOffer(connection, offerId, blockchainID);
            }

            contract.LastSyncedTimestamp = DateTime.Now;
            contract.SyncBlockNumber     = (ulong)toBlock.BlockNumber.Value;

            await OTContract.Update(connection, contract, false, false);
        }
コード例 #2
0
        public static async Task ProcessOfferFinalised(MySqlConnection connection, int blockchainID, Web3 cl,
                                                       string contractAddress, EventLog <List <ParameterOutput> > eventLog)
        {
            using (await LockManager.GetLock(LockType.OfferFinalised).Lock())
            {
                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                if (!OTContract_Holding_OfferCreated.Exists(connection, offerId, blockchainID))
                {
                    //Lets get this via syncing later on as we've missed the creation of the job
                    return;
                }

                if (OTContract_Holding_OfferFinalized.Exists(connection, offerId, blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);


                var holder1 = (string)eventLog.Event.FirstOrDefault(e => e.Parameter.Name == "holder1")
                              .Result;
                var holder2 = (string)eventLog.Event.FirstOrDefault(e => e.Parameter.Name == "holder2")
                              .Result;
                var holder3 = (string)eventLog.Event.FirstOrDefault(e => e.Parameter.Name == "holder3")
                              .Result;

                var receipt = cl.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                var transaction =
                    cl.Eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                var row = new OTContract_Holding_OfferFinalized
                {
                    TransactionHash = eventLog.Log.TransactionHash,
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    Timestamp       = block.Timestamp,
                    OfferID         = offerId,
                    Holder1         = holder1,
                    Holder2         = holder2,
                    Holder3         = holder3,
                    ContractAddress = contractAddress,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    Data            = eventLog.Log.Data,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    BlockchainID    = blockchainID
                };

                OTContract_Holding_OfferFinalized.InsertIfNotExist(connection, row);
            }
        }
コード例 #3
0
        public static async Task ProcessProfileCreated(MySqlConnection connection, string contractAddress,
                                                       Function createProfileFunction, int blockchainID, Web3 cl, EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            using (await LockManager.GetLock(LockType.ProfileCreated).Lock())
            {
                var profile = (string)eventLog.Event.FirstOrDefault(p => p.Parameter.Name == "profile")
                              .Result;


                if (OTContract_Profile_ProfileCreated.Exists(connection, profile, blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);

                var initialBalance = Web3.Convert.FromWei((BigInteger)eventLog.Event
                                                          .FirstOrDefault(p => p.Parameter.Name == "initialBalance").Result);


                var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                var row = new OTContract_Profile_ProfileCreated
                {
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contractAddress,
                    Profile         = profile,
                    InitialBalance  = initialBalance,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    BlockchainID    = blockchainID
                };

                var createProfileInputData = createProfileFunction.DecodeInput(transaction.Result.Input);

                if (createProfileInputData != null)
                {
                    row.ManagementWallet =
                        (string)createProfileInputData.FirstOrDefault(p => p.Parameter.Name == "managementWallet")
                        ?.Result;

                    row.NodeId = HexHelper.ByteArrayToString((byte[])createProfileInputData
                                                             .FirstOrDefault(p => p.Parameter.Name == "profileNodeId").Result, false).Substring(0, 40);
                }

                OTContract_Profile_ProfileCreated.InsertIfNotExist(connection, row);
            }
        }
コード例 #4
0
        public static async Task ProcessOfferCreated(MySqlConnection connection, int blockchainID, Web3 cl,
                                                     string contractAddress, EventLog <Models.Program.OfferCreated> eventLog)
        {
            using (await LockManager.GetLock(LockType.OfferCreated).Lock())
            {
                string offerID = HexHelper.ByteArrayToString(eventLog.Event.offerId);

                if (OTContract_Holding_OfferCreated.Exists(connection, offerID, blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber, cl, blockchainID);

                var receipt = cl.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                var transaction = cl.Eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;


                var row = new OTContract_Holding_OfferCreated
                {
                    Timestamp = block.Timestamp,
                    LitigationIntervalInMinutes = (UInt64)eventLog.Event.litigationIntervalInMinutes,
                    DCNodeId             = HexHelper.ByteArrayToString(eventLog.Event.dcNodeId, false),
                    DataSetId            = HexHelper.ByteArrayToString(eventLog.Event.dataSetId),
                    HoldingTimeInMinutes = (UInt64)eventLog.Event.holdingTimeInMinutes,
                    TokenAmountPerHolder = Web3.Convert.FromWei(eventLog.Event.tokenAmountPerHolder),
                    TransactionIndex     = (UInt64)eventLog.Log.TransactionIndex.Value,
                    TransactionHash      = eventLog.Log.TransactionHash,
                    BlockNumber          = (UInt64)eventLog.Log.BlockNumber.Value,
                    OfferID            = offerID,
                    DataSetSizeInBytes = (UInt64)eventLog.Event.dataSetSizeInBytes,
                    ContractAddress    = contractAddress,
                    GasUsed            = (UInt64)receipt.Result.GasUsed.Value,
                    GasPrice           = (UInt64)transaction.Result.GasPrice.Value,
                    Data         = eventLog.Log.Data,
                    BlockchainID = blockchainID
                };

                if (row.DCNodeId.Length > 40)
                {
                    row.DCNodeId = row.DCNodeId.Substring(row.DCNodeId.Length - 40);
                }

                OTContract_Holding_OfferCreated.InsertIfNotExist(connection, row);
            }
        }
コード例 #5
0
        public static async Task ProcessPayout(MySqlConnection connection, int blockchainID, Web3 cl, string contractAddress, EventLog <List <ParameterOutput> > eventLog)
        {
            using (await LockManager.GetLock(LockType.PayoutInsert).Lock())
            {
                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                var amount = Web3.Convert.FromWei((BigInteger)eventLog.Event
                                                  .FirstOrDefault(e => e.Parameter.Name == "amount").Result);

                var holder = (string)eventLog.Event.FirstOrDefault(e => e.Parameter.Name == "holder")
                             .Result;

                if (OTContract_Holding_Paidout.Exists(connection, offerId, holder, amount, eventLog.Log.TransactionHash,
                                                      blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash,
                                                       eventLog.Log.BlockNumber,
                                                       cl, blockchainID);


                var receipt = cl.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                var transaction =
                    cl.Eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                OTContract_Holding_Paidout.InsertIfNotExist(connection, new OTContract_Holding_Paidout
                {
                    OfferID         = offerId,
                    Holder          = holder,
                    Amount          = amount,
                    Timestamp       = block.Timestamp,
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contractAddress,
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    Data            = eventLog.Log.Data,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    BlockchainID    = blockchainID
                });
            }
        }
コード例 #6
0
        public static async Task ProcessOfferTasks(MySqlConnection connection, int blockchainID, Web3 cl,
                                                   string contractAddress, EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            using (await LockManager.GetLock(LockType.OfferTask).Lock())
            {
                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                if (OTContract_Holding_OfferTask.Exists(connection, offerId, blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);

                var dataSetId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "dataSetId").Result);
                var dcNodeId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "dcNodeId").Result);

                var task = HexHelper.ByteArrayToString(
                    (byte[])eventLog.Event.First(e => e.Parameter.Name == "task").Result);

                var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                OTContract_Holding_OfferTask.InsertIfNotExist(connection, new OTContract_Holding_OfferTask
                {
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    Task            = task,
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contractAddress,
                    DCNodeId        = dcNodeId,
                    DataSetId       = dataSetId,
                    OfferId         = offerId,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    BlockchainID    = blockchainID
                });
            }
        }
コード例 #7
0
        public static async Task ProcessLitigationInitiated(MySqlConnection connection, int blockchainID, Web3 cl,
                                                            EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            if (OTContract_Litigation_LitigationInitiated.TransactionExists(connection, eventLog.Log.TransactionHash, blockchainID))
            {
                return;
            }

            var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                   cl, blockchainID);

            var offerId =
                HexHelper.ByteArrayToString((byte[])eventLog.Event
                                            .First(e => e.Parameter.Name == "offerId").Result);

            var holderIdentity = (string)eventLog.Event
                                 .First(e => e.Parameter.Name == "holderIdentity").Result;

            var requestedObjectIndex = (BigInteger)eventLog.Event
                                       .First(e => e.Parameter.Name == "requestedObjectIndex").Result;


            var requestedBlockIndex = (BigInteger)eventLog.Event
                                      .First(e => e.Parameter.Name == "requestedBlockIndex").Result;

            var transaction = await eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

            var receipt = await eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

            var row = new OTContract_Litigation_LitigationInitiated
            {
                TransactionHash      = eventLog.Log.TransactionHash,
                BlockNumber          = (UInt64)eventLog.Log.BlockNumber.Value,
                Timestamp            = block.Timestamp,
                OfferId              = offerId,
                RequestedObjectIndex = (UInt64)requestedObjectIndex,
                RequestedBlockIndex  = (UInt64)requestedBlockIndex,
                HolderIdentity       = holderIdentity,
                GasPrice             = (UInt64)transaction.GasPrice.Value,
                GasUsed              = (UInt64)receipt.GasUsed.Value,
                BlockchainID         = blockchainID
            };

            await OTContract_Litigation_LitigationInitiated.InsertIfNotExist(connection, row);
        }
コード例 #8
0
        public override async Task <bool> Execute(Source source, BlockchainType blockchain, BlockchainNetwork network)
        {
            ClientBase.ConnectionTimeout = new TimeSpan(0, 0, 5, 0);

            await using (var connection =
                             new MySqlConnection(OTHubSettings.Instance.MariaDB.ConnectionString))
            {
                int blockchainID = await GetBlockchainID(connection, blockchain, network);

                var cl = await GetWeb3(connection, blockchainID, blockchain);

                var profileStorageContractAddress = (await OTContract
                                                     .GetByTypeAndBlockchain(connection, (int)ContractTypeEnum.ProfileStorage, blockchainID)).SingleOrDefault(a => a.IsLatest);

                if (profileStorageContractAddress == null)
                {
                    return(false);
                }

                var profileStorageContract =
                    new Contract(new EthApiService(cl.Client),
                                 AbiHelper.GetContractAbi(ContractTypeEnum.ProfileStorage, blockchain, network),
                                 profileStorageContractAddress.Address);
                var profileFunction = profileStorageContract.GetFunction("profile");

                var currentIdentities = await OTIdentity.GetAll(connection, blockchainID);

                Dictionary <string, decimal> paidOutBalances = (await connection
                                                                .QueryAsync <PayoutGroupHolder>(
                                                                    @"SELECT Holder, SUM(Amount) Amount FROM OTContract_Holding_Paidout WHERE BlockchainID = @blockchainID GROUP BY Holder",
                                                                    new
                {
                    blockchainID = blockchainID
                }))
                                                               .ToDictionary(k => k.Holder, k => k.Amount);

                Dictionary <string, OfferGroupHolder> offerTotals = (await connection.QueryAsync <OfferGroupHolder>(
                                                                         @"select i.Identity, COUNT(o.OfferID) as OffersTotal,
(SELECT count(so.OfferID) FROM otoffer_holders sh join otoffer so on so.OfferID = sh.OfferID AND so.BlockchainID = sh.BlockchainID
    WHERE sh.blockchainid = @blockchainID and sh.Holder = i.Identity AND so.CreatedTimestamp >= Date_Add(NOW(), INTERVAL -7 DAY)) as OffersLast7Days
 from otidentity i
join otoffer_holders h on h.Holder = i.Identity AND h.BlockchainID = i.BlockchainID
join otoffer o on o.OfferID = h.OfferID AND o.BlockchainID = h.BlockchainID
WHERE i.blockchainid = @blockchainID
GROUP BY i.Identity", new
                {
                    blockchainID
                })).ToDictionary(k => k.Identity, k => k);
//                NodeManagementWallet[] managementWallets = (await connection.QueryAsync<NodeManagementWallet>(
//                    @"SELECT I.Identity, PC.ManagementWallet as CreateWallet, IT.ManagementWallet TransferWallet FROM OTIdentity I
//LEFT JOIN OTContract_Profile_ProfileCreated PC ON PC.Profile = I.Identity AND PC.BlockchainID = I.BlockchainID
//LEFT JOIN OTContract_Profile_IdentityTransferred IT ON IT.NewIdentity = I.Identity AND IT.BlockchainID = I.BlockchainID
//WHERE I.Version > 0 AND I.BlockchainID = @blockchainID", new
//                    {
//                        blockchainID
//                    })).ToArray();


                foreach (OTIdentity currentIdentity in currentIdentities)
                {
                    bool     updateProfile    = true;
                    DateTime?lastActivityDate = null;

                    if (currentIdentity.Version != Constants.CurrentERCVersion)
                    {
                        if (currentIdentity.LastSyncedTimestamp.HasValue)
                        {
                            DateTime adjustedNowTime = DateTime.Now;

                            if ((adjustedNowTime - currentIdentity.LastSyncedTimestamp.Value).TotalDays <= 14)
                            {
                                updateProfile = false;
                            }
                        }
                    }
                    else if (currentIdentity.LastSyncedTimestamp.HasValue)
                    {
                        var dates = (await connection.QueryAsync <DateTime?>(@"
select MAX(Timestamp) from otcontract_profile_identitycreated r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.NewIdentity = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_identitytransferred r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.NewIdentity = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_profilecreated r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.Profile = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_tokensdeposited r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.Profile = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_tokensreleased r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.Profile = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_tokensreserved r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.Profile = @identity AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_tokenstransferred r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE (r.Sender = @identity OR r.Receiver = @identity) AND r.blockchainID = @blockchainID
union
select MAX(Timestamp) from otcontract_profile_tokenswithdrawn r
join ethblock b on r.BlockNumber = b.BlockNumber AND r.BlockchainID = b.BlockchainID
WHERE r.Profile = @identity AND r.blockchainID = @blockchainID
union
select MAX(b.Timestamp) from otoffer_holders h
join otoffer o on o.offerid = h.offerid and o.BlockchainID = h.BlockchainID
join ethblock b on b.blocknumber = o.finalizedblocknumber AND h.BlockchainID = b.BlockchainID
where h.Holder = @identity  AND h.blockchainID = @blockchainID
union
SELECT MAX(Timestamp)
FROM otcontract_litigation_litigationcompleted lc
WHERE lc.HolderIdentity = @identity AND lc.DHWasPenalized = 1 AND lc.blockchainID = @blockchainID
union
select MAX(b.Timestamp) from otcontract_holding_paidout p
join ethblock b on b.blocknumber = p.blocknumber and b.BlockchainID = p.BlockchainID
where p.holder = @identity AND p.blockchainID = @blockchainID
union
select MAX(b.Timestamp)  from otcontract_holding_offerfinalized of
join otcontract_holding_offercreated oc on oc.OfferId = of.OfferId and oc.BlockchainID = of.BlockchainID
join OTIdentity i on i.NodeId = oc.DCNodeId and i.BlockchainID = oc.BlockchainID
join ethblock b on of.BlockNumber = b.BlockNumber and b.BlockchainID = of.BlockchainID
where i.Identity = @identity AND of.blockchainID = @blockchainID", new
                        {
                            identity = currentIdentity.Identity,
                            blockchainID
                        })).ToArray().Where(d => d.HasValue).Select(d => d.Value).ToArray();



                        var adjustedNowTime = DateTime.Now;



                        if (dates.Any())
                        {
                            lastActivityDate = dates.Max();

                            if (lastActivityDate.Value <= currentIdentity.LastSyncedTimestamp)
                            {
                                if ((adjustedNowTime - currentIdentity.LastSyncedTimestamp.Value).TotalHours <= 16)
                                {
                                    updateProfile = false;
                                }
                            }
                        }
                        else
                        {
                            if ((adjustedNowTime - currentIdentity.LastSyncedTimestamp.Value).TotalHours <= 24)
                            {
                                updateProfile = false;
                            }
                        }
                    }

                    if (updateProfile || (currentIdentity.NodeId ?? "").Length > 40)
                    {
                        var output =
                            await profileFunction.CallDeserializingToObjectAsync <ProfileFunctionOutput>(
                                currentIdentity.Identity);

                        var stake               = Web3.Convert.FromWei(output.stake);
                        var stakeReserved       = Web3.Convert.FromWei(output.stakeReserved);
                        var nodeId              = HexHelper.ByteArrayToString(output.nodeId, false).Substring(0, 40);
                        var withdrawalAmount    = Web3.Convert.FromWei(output.withdrawalAmount);
                        var withdrawalTimestamp = (UInt64)output.withdrawalTimestamp;
                        var reputation          = (UInt64)output.reputation;

                        if (currentIdentity.Stake != stake ||
                            currentIdentity.StakeReserved != stakeReserved ||
                            currentIdentity.NodeId != nodeId ||
                            currentIdentity.WithdrawalAmount != withdrawalAmount ||
                            currentIdentity.WithdrawalPending != output.withdrawalPending ||
                            currentIdentity.WithdrawalTimestamp != withdrawalTimestamp ||
                            currentIdentity.Reputation != reputation)
                        {
                            currentIdentity.Stake               = stake;
                            currentIdentity.StakeReserved       = stakeReserved;
                            currentIdentity.NodeId              = nodeId;
                            currentIdentity.WithdrawalAmount    = withdrawalAmount;
                            currentIdentity.WithdrawalPending   = output.withdrawalPending;
                            currentIdentity.WithdrawalTimestamp = withdrawalTimestamp;
                            currentIdentity.Reputation          = reputation;
                            currentIdentity.LastSyncedTimestamp = DateTime.Now;

                            await OTIdentity.UpdateFromProfileFunction(connection, currentIdentity);
                        }
                        else
                        {
                            currentIdentity.LastSyncedTimestamp = DateTime.Now;
                            await OTIdentity.UpdateLastSyncedTimestamp(connection, currentIdentity);
                        }
                    }

                    if (!paidOutBalances.TryGetValue(currentIdentity.Identity, out var paidRow))
                    {
                        paidRow = 0;
                    }

                    offerTotals.TryGetValue(currentIdentity.Identity, out var offerRow);

                    if (currentIdentity.Paidout != paidRow ||
                        currentIdentity.TotalOffers != (offerRow?.OffersTotal ?? 0) ||
                        currentIdentity.OffersLast7Days != (offerRow?.OffersLast7Days ?? 0) ||
                        currentIdentity.ActiveOffers != 0 ||
                        (currentIdentity.LastActivityTimestamp != lastActivityDate && lastActivityDate.HasValue))
                    {
                        currentIdentity.Paidout               = paidRow;
                        currentIdentity.TotalOffers           = offerRow?.OffersTotal ?? 0;
                        currentIdentity.OffersLast7Days       = offerRow?.OffersLast7Days ?? 0;
                        currentIdentity.ActiveOffers          = 0;
                        currentIdentity.LastActivityTimestamp = lastActivityDate;

                        await OTIdentity.UpdateFromPaidoutAndApprovedCalculation(connection, currentIdentity);
                    }
                }
            }

            return(true);
        }
コード例 #9
0
        private async Task Sync(MySqlConnection connection, Event profileCreatedEvent, Event identityCreatedEvent,
                                Event identityTransferredEvent, Event tokensDepositedEvent, Event tokensReleasedEvent,
                                Event tokensWithdrawnEvent, Event tokensTransferredEvent, Event tokensReservedEvent, OTContract contract,
                                Source source, Function createProfileFunction, Function transferProfileFunction, ulong start, ulong end,
                                int blockchainID, Web3 cl)
        {
            Logger.WriteLine(source, "Syncing profile " + start + " to " + end);

            var toBlock = new BlockParameter(end);

            var identityCreatedEvents = await identityCreatedEvent.GetAllChangesDefault(
                identityCreatedEvent.CreateFilterInput(new BlockParameter(start),
                                                       toBlock));

            var identityTransferredEvents = await identityTransferredEvent.GetAllChangesDefault(
                identityTransferredEvent.CreateFilterInput(new BlockParameter(start),
                                                           toBlock));

            var profileCreatedEvents = await profileCreatedEvent.GetAllChangesDefault(
                profileCreatedEvent.CreateFilterInput(new BlockParameter(start),
                                                      toBlock));

            var tokensDepositedEvents = await tokensDepositedEvent.GetAllChangesDefault(
                tokensDepositedEvent.CreateFilterInput(new BlockParameter(start),
                                                       toBlock));


            var tokensReleasedEvents = await tokensReleasedEvent.GetAllChangesDefault(
                tokensReleasedEvent.CreateFilterInput(new BlockParameter(start),
                                                      toBlock));


            var tokensWithdrawnEvents = await tokensWithdrawnEvent.GetAllChangesDefault(
                tokensWithdrawnEvent.CreateFilterInput(new BlockParameter(start),
                                                       toBlock));


            var tokensTransferredEvents = await tokensTransferredEvent.GetAllChangesDefault(
                tokensTransferredEvent.CreateFilterInput(new BlockParameter(start),
                                                         toBlock));


            var tokensReservedEvents = await tokensReservedEvent.GetAllChangesDefault(
                tokensReservedEvent.CreateFilterInput(new BlockParameter(start),
                                                      toBlock));


            if (identityCreatedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + identityCreatedEvents.Count + " identity created events");
            }

            if (identityTransferredEvents.Any())
            {
                Logger.WriteLine(source, "Found " + identityTransferredEvents.Count + " identity transferred events");
            }

            if (profileCreatedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + profileCreatedEvents.Count + " profile created events");
            }

            if (tokensDepositedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + tokensDepositedEvents.Count + " tokens deposited events");
            }

            if (tokensReleasedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + tokensReleasedEvents.Count + " tokens released events");
            }

            if (tokensWithdrawnEvents.Any())
            {
                Logger.WriteLine(source, "Found " + tokensWithdrawnEvents.Count + " tokens withdrawn events");
            }

            if (tokensTransferredEvents.Any())
            {
                Logger.WriteLine(source, "Found " + tokensTransferredEvents.Count + " tokens transferred events");
            }

            if (tokensReservedEvents.Any())
            {
                Logger.WriteLine(source, "Found " + tokensReservedEvents.Count + " tokens reserved events");
            }

            var eth = new EthApiService(cl.Client);

            foreach (EventLog <List <ParameterOutput> > eventLog in identityCreatedEvents)
            {
                await ProcessIdentityCreated(connection, contract.Address, blockchainID, cl, eventLog, eth);
            }

            foreach (EventLog <List <ParameterOutput> > eventLog in profileCreatedEvents)
            {
                await ProcessProfileCreated(connection, contract.Address, createProfileFunction, blockchainID, cl, eventLog, eth);
            }


            foreach (EventLog <List <ParameterOutput> > eventLog in identityTransferredEvents)
            {
                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);

                var oldIdentity = (string)eventLog.Event
                                  .FirstOrDefault(p => p.Parameter.Name == "oldIdentity").Result;

                var newIdentity = (string)eventLog.Event
                                  .FirstOrDefault(p => p.Parameter.Name == "newIdentity").Result;

                var nodeId = HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                         .FirstOrDefault(p => p.Parameter.Name == "nodeId").Result, false);


                var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                var row = new OTContract_Profile_IdentityTransferred
                {
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contract.Address,
                    NewIdentity     = newIdentity,
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    OldIdentity     = oldIdentity,
                    NodeId          = nodeId,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    BlockchainID    = blockchainID
                };

                var transferProfileFunctionData = transferProfileFunction.DecodeInput(transaction.Result.Input);

                if (transferProfileFunctionData != null)
                {
                    row.ManagementWallet = (string)transferProfileFunctionData.FirstOrDefault(p => p.Parameter.Name == "managementWallet")?.Result;
                }


                OTContract_Profile_IdentityTransferred.InsertIfNotExist(connection, row);
            }


            foreach (var group in tokensDepositedEvents.GroupBy(t => t.Log.TransactionHash))
            {
                await ProcessTokensDeposited(connection, contract.Address, blockchainID, cl, @group, eth);
            }

            foreach (var group in tokensReleasedEvents.GroupBy(t => t.Log.TransactionHash))
            {
                await ProcessTokensReleased(connection, contract.Address, blockchainID, cl, @group, eth);
            }

            foreach (var group in tokensWithdrawnEvents.GroupBy(t => t.Log.TransactionHash))
            {
                await ProcessTokensWithdrawn(connection, contract.Address, blockchainID, cl, @group, eth);
            }

            foreach (var group in tokensTransferredEvents.GroupBy(t => t.Log.TransactionHash))
            {
                if (OTContract_Profile_TokensTransferred.TransactionExists(connection, group.Key, blockchainID))
                {
                    continue;
                }

                foreach (var eventLog in group)
                {
                    var sender = (string)eventLog.Event.FirstOrDefault(p => p.Parameter.Name == "sender")
                                 .Result;

                    var receiver = (string)eventLog.Event
                                   .FirstOrDefault(p => p.Parameter.Name == "receiver")
                                   .Result;
                    var amount = Web3.Convert.FromWei((BigInteger)eventLog.Event
                                                      .FirstOrDefault(p => p.Parameter.Name == "amount").Result);

                    var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                    var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                    await transaction;
                    await receipt;

                    var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash,
                                                           eventLog.Log.BlockNumber,
                                                           cl, blockchainID);

                    OTContract_Profile_TokensTransferred.Insert(connection,
                                                                new OTContract_Profile_TokensTransferred
                    {
                        BlockNumber     = block.BlockNumber,
                        TransactionHash = eventLog.Log.TransactionHash,
                        ContractAddress = contract.Address,
                        Amount          = amount,
                        Receiver        = receiver,
                        Sender          = sender,
                        GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                        GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                        BlockchainID    = blockchainID
                    });
                }
            }

            foreach (var group in tokensReservedEvents.GroupBy(t => t.Log.TransactionHash))
            {
                if (OTContract_Profile_TokensReserved.TransactionExists(connection, group.Key, blockchainID))
                {
                    continue;
                }

                foreach (var eventLog in group)
                {
                    var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash,
                                                           eventLog.Log.BlockNumber,
                                                           cl, blockchainID);

                    var profile = (string)eventLog.Event.FirstOrDefault(p => p.Parameter.Name == "profile")
                                  .Result;
                    var amountReserved = Web3.Convert.FromWei((BigInteger)eventLog.Event
                                                              .FirstOrDefault(p => p.Parameter.Name == "amountReserved").Result);

                    var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                    var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                    await transaction;
                    await receipt;

                    OTContract_Profile_TokensReserved.Insert(connection,
                                                             new OTContract_Profile_TokensReserved
                    {
                        TransactionHash = eventLog.Log.TransactionHash,
                        BlockNumber     = block.BlockNumber,
                        ContractAddress = contract.Address,
                        Profile         = profile,
                        AmountReserved  = amountReserved,
                        GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                        GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                        BlockchainID    = blockchainID
                    });
                }
            }

            contract.LastSyncedTimestamp = DateTime.Now;
            contract.SyncBlockNumber     = end;

            await OTContract.Update(connection, contract, false, false);
        }