コード例 #1
0
 public Effects(ILyraAPI lyraClient,
                IConfiguration configuration,
                ILogger <Effects> logger)
 {
     client      = lyraClient;
     config      = configuration;
     this.logger = logger;
 }
コード例 #2
0
        public async Task UT_PoolFactory_SetupAsync()
        {
            //var aggClient = new LyraAggregatedClient(networkId);
            //await aggClient.InitAsync();
            //client = aggClient;
            client = LyraRestClient.Create(networkId, "Windows", "UnitTest", "1.0");

            var w1 = Restore(testPrivateKey);
            await w1.SyncAsync(client);

            var balances = w1.GetLastSyncBlock().Balances;

            Assert.IsTrue(balances[LyraGlobal.OFFICIALTICKERCODE].ToBalanceDecimal() > 100000m, "Insufficient funds: LYR");

            // make sure we have 2 test token
            var genResult = await client.GetTokenGenesisBlockAsync(testPublicKey, testTokenA, await SignAPIAsync());

            if (genResult.ResultCode == APIResultCodes.TokenGenesisBlockNotFound)
            {
                var secs   = testTokenA.Split('/');
                var result = await w1.CreateTokenAsync(secs[1], secs[0], "", 8, 50000000000, true, "", "", "", Lyra.Core.Blocks.ContractTypes.Cryptocurrency, null);

                Assert.IsTrue(result.Successful(), "Failed to create token: " + result.ResultCode);
                await w1.SyncAsync(client);
            }

            genResult = await client.GetTokenGenesisBlockAsync(testPublicKey, testTokenB, await SignAPIAsync());

            if (genResult.ResultCode == APIResultCodes.TokenGenesisBlockNotFound)
            {
                var secs   = testTokenB.Split('/');
                var result = await w1.CreateTokenAsync(secs[1], secs[0], "", 8, 50000000000, true, "", "", "", Lyra.Core.Blocks.ContractTypes.Cryptocurrency, null);

                Assert.IsTrue(result.Successful(), "Failed to create token: " + result.ResultCode);
                await w1.SyncAsync(client);
            }

            var pool = await client.GetPoolAsync(LyraGlobal.OFFICIALTICKERCODE, testTokenA);

            if (pool.PoolAccountId == null)
            {
                var token0 = LyraGlobal.OFFICIALTICKERCODE;
                var token1 = testTokenA;

                var poolCreateResult = await w1.CreateLiquidatePoolAsync(token0, token1);

                await Task.Delay(3000);     // give consens network time to create it.

                Assert.IsTrue(poolCreateResult.ResultCode == APIResultCodes.Success, "Can't create pool for " + token1);
            }

            await w1.SyncAsync(client);

            balances = w1.GetLastSyncBlock().Balances;
            Assert.IsTrue(balances[testTokenA].ToBalanceDecimal() > 100000m, "Insufficient funds: " + testTokenA);
        }
コード例 #3
0
        private async Task <Wallet> GetGenesisWalletAsync()
        {
            string lyra_folder = Wallet.GetFullFolderName(networkId, "wallets");
            var    storage     = new SecuredWalletStore(lyra_folder);
            var    wallet      = Wallet.Open(storage, "vault", "");

            client = LyraRestClient.Create(networkId, "windows", "unit test", "1.0");
            await wallet.SyncAsync(client);

            Assert.IsTrue(wallet.BaseBalance > 1000000m);
            return(wallet);
        }
コード例 #4
0
        public Wallet Restore(string privateKey)
        {
            client = LyraRestClient.Create(networkId, "Windows", "UnitTest", "1.0");

            var memStor = new AccountInMemoryStorage();

            try
            {
                Wallet.Create(memStor, "tmpAcct", "", networkId, privateKey);
                return(Wallet.Open(memStor, "tmpAcct", ""));
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #5
0
        //private async Task SyncManyBlocksAsync(LyraClientForNode client, ConsolidationBlock consBlock)
        //{
        //    _log.LogInformation($"Syncing Consolidations {consBlock.Height} / {consBlock.Hash.Shorten()} ");

        //    var blocksResult = await client.GetBlocksByConsolidation(consBlock.Hash);
        //    if (blocksResult.ResultCode == APIResultCodes.Success)
        //    {
        //        foreach (var block in blocksResult.GetBlocks())
        //        {
        //            var localBlock = await _sys.Storage.FindBlockByHashAsync(block.Hash);
        //            if (localBlock != null)
        //                await _sys.Storage.RemoveBlockAsync(block.Hash);

        //            await _sys.Storage.AddBlockAsync(block);
        //        }

        //        // save cons block itself
        //        var localCons = await _sys.Storage.FindBlockByHashAsync(consBlock.Hash);
        //        if (localCons != null)
        //            await _sys.Storage.RemoveBlockAsync(consBlock.Hash);

        //        await _sys.Storage.AddBlockAsync(consBlock);
        //    }
        //}

        //private async Task SyncManyBlocksAsync(LyraClientForNode client, List<string> hashes)
        //{
        //    _log.LogInformation($"Syncing {hashes.Count()} blocks...");

        //    foreach (var hash in hashes)
        //    {
        //        var blockResult = await client.GetBlockByHash(hash);
        //        if (blockResult.ResultCode == APIResultCodes.Success)
        //        {
        //            var localBlock = await _sys.Storage.FindBlockByHashAsync(hash);
        //            if (localBlock != null)
        //                await _sys.Storage.RemoveBlockAsync(hash);

        //            await _sys.Storage.AddBlockAsync(blockResult.GetBlock());
        //        }
        //    }
        //}

        private async Task <bool> SyncOneBlockAsync(ILyraAPI client, string hash)
        {
            if (null != await _sys.Storage.FindBlockByHashAsync(hash))
            {
                await _sys.Storage.RemoveBlockAsync(hash);
            }

            var remoteBlock = await client.GetBlockByHashAsync(_sys.PosWallet.AccountId, hash, null);

            if (remoteBlock.ResultCode == APIResultCodes.Success)
            {
                var block = remoteBlock.GetBlock();

                // when block stored into database, they lost their order. so it's hard to do verification style of authorizer.
                // and mixed with code change/logic upgrade, so just use hash verify to keep database integraty.
                //if(block is TransactionBlock tb)
                //{
                //    var authorizer = factory.Create(tb.BlockType);
                //    var authResult = await authorizer.AuthorizeAsync(GetDagSystem(), tb);
                //    if (authResult.Item1 != APIResultCodes.Success)
                //    {
                //        _log.LogWarning($"SyncOneBlockAsync: TX block {tb.Hash.Shorten()} failed to verify for {authResult.Item1}");
                //    }
                //}

                // non tx block just verify hash
                if (block != null && block.VerifyHash())
                {
                    return(await _sys.Storage.AddBlockAsync(block));
                }
                else
                {
                    _log.LogWarning($"Error SyncOneBlockAsync: block null? {block is null}");
                    if (!(block is null))
                    {
                        _log.LogWarning($"Error SyncOneBlockAsync: block VerifyHash? {block.VerifyHash()}");
                    }
                    return(false);
                }
            }
            else
            {
                _log.LogWarning($"Error SyncOneBlockAsync: remote return: {remoteBlock.ResultCode}");
                return(false);
            }
        }
コード例 #6
0
        private async Task <bool> SyncDatabaseAsync(ILyraAPI client)
        {
            var consensusClient = client;

            BlockAPIResult seedSvcGen = null;

            for (int i = 0; i < 10; i++)
            {
                seedSvcGen = await consensusClient.GetServiceGenesisBlockAsync();

                if (seedSvcGen.ResultCode == APIResultCodes.Success)
                {
                    break;
                }

                await Task.Delay(10 * 1000);

                _log.LogInformation("Recreate aggregated client...");
                //await client.InitAsync();
            }


            var localDbState = await GetNodeStatusAsync();

            if (localDbState.totalBlockCount == 0)
            {
                LocalDbSyncState.Remove();
            }
            else
            {
                var oldState = LocalDbSyncState.Load();

                if (oldState.svcGenHash != seedSvcGen.GetBlock().Hash)
                {
                    LocalDbSyncState.Remove();
                }

                //if(oldState.databaseVersion > 0 && oldState.databaseVersion < LyraGlobal.DatabaseVersion)
                //{
                //    // should upgrade database or resync completely
                //    _sys.Storage.Delete(true);
                //    LocalDbSyncState.Remove();
                //    localDbState = await GetNodeStatusAsync();
                //}
            }

            var localState = LocalDbSyncState.Load();

            if (localState.svcGenHash == null)
            {
                localState.svcGenHash      = seedSvcGen.GetBlock().Hash;
                localState.databaseVersion = LyraGlobal.DatabaseVersion;
            }

            var lastCons = (await consensusClient.GetLastConsolidationBlockAsync()).GetBlock() as ConsolidationBlock;

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

            bool IsSuccess    = true;
            var  _authorizers = new AuthorizersFactory();

            while (true)
            {
                try
                {
                    var remoteConsQuery = await consensusClient.GetConsolidationBlocksAsync(_sys.PosWallet.AccountId, null, localState.lastVerifiedConsHeight + 1, 1);

                    if (remoteConsQuery.ResultCode == APIResultCodes.Success)
                    {
                        var remoteConsBlocks = remoteConsQuery.GetBlocks();
                        if (remoteConsBlocks.Any())
                        {
                            foreach (var block in remoteConsBlocks)
                            {
                                var consTarget = block as ConsolidationBlock;
                                _log.LogInformation($"SyncDatabase: Sync consolidation block {consTarget.Height} of total {lastCons.Height}.");
                                if (await SyncAndVerifyConsolidationBlockAsync(consensusClient, consTarget))
                                {
                                    _log.LogInformation($"Consolidation block {consTarget.Height} is OK.");

                                    localState.lastVerifiedConsHeight = consTarget.Height;
                                    LocalDbSyncState.Save(localState);
                                }
                                else
                                {
                                    throw new Exception($"Consolidation block {consTarget.Height} is failure.");
                                }
                            }
                        }
                        else
                        {
                            IsSuccess = true;
                            break;
                        }
                    }
                    else if (remoteConsQuery.ResultCode == APIResultCodes.APIRouteFailed)
                    {
                        _log.LogWarning("Got inconsistant result from network. retry later.");
                        throw new Exception("Failed to sync. reason: " + remoteConsQuery.ResultCode);
                    }
                    else
                    {
                        _log.LogWarning($"Unexpected error {remoteConsQuery.ResultCode}: {remoteConsQuery.ResultMessage}. retry later.");
                        throw new Exception($"Failed to sync. reason: {remoteConsQuery.ResultCode}: {remoteConsQuery.ResultMessage}");
                    }
                }
                catch (Exception ex)
                {
                    _log.LogWarning("SyncDatabase Exception: " + ex.Message);
                    await Task.Delay(30000);

                    IsSuccess = false;
                    break;
                }
            }

            return(IsSuccess);
        }
コード例 #7
0
        private async Task <bool> SyncAndVerifyConsolidationBlockAsync(ILyraAPI client, ConsolidationBlock consBlock)
        {
            _log.LogInformation($"Sync and verify consolidation block height {consBlock.Height}");

            foreach (var hash in consBlock.blockHashes)
            {
                if (!await SyncOneBlockAsync(client, hash))
                {
                    return(false);
                }
            }

            if (null != await _sys.Storage.FindBlockByHashAsync(consBlock.Hash))
            {
                await _sys.Storage.RemoveBlockAsync(consBlock.Hash);
            }

            var mt = new MerkleTree();

            foreach (var hash1 in consBlock.blockHashes)
            {
                mt.AppendLeaf(MerkleHash.Create(hash1));
            }
            var merkelTreeHash = mt.BuildTree().ToString();

            if (consBlock.MerkelTreeHash != merkelTreeHash)
            {
                _log.LogWarning($"SyncAndVerifyConsolidationBlock: consMerkelTree: {consBlock.MerkelTreeHash} mine: {merkelTreeHash}");
                return(false);
            }

            // make sure no extra blocks here
            if (consBlock.Height > 1)
            {
                var prevConsHash   = consBlock.blockHashes.First();
                var prevConsResult = await client.GetBlockByHashAsync(_sys.PosWallet.AccountId, prevConsHash, null);

                if (prevConsResult.ResultCode != APIResultCodes.Success)
                {
                    _log.LogWarning($"SyncAndVerifyConsolidationBlock: prevConsResult.ResultCode: {prevConsResult.ResultCode}");
                    return(false);
                }

                var prevConsBlock = prevConsResult.GetBlock() as ConsolidationBlock;
                if (prevConsBlock == null)
                {
                    _log.LogWarning($"SyncAndVerifyConsolidationBlock: prevConsBlock: null");
                    return(false);
                }

                var blocksInTimeRange = await _sys.Storage.GetBlockHashesByTimeRangeAsync(prevConsBlock.TimeStamp, consBlock.TimeStamp);

                var q = blocksInTimeRange.Where(a => !consBlock.blockHashes.Contains(a));
                foreach (var extraBlock in q)
                {
                    await _sys.Storage.RemoveBlockAsync(extraBlock);
                }
            }

            return(await _sys.Storage.AddBlockAsync(consBlock));
        }
コード例 #8
0
 public FeesEffect(ILyraAPI lyraClient)
 {
     client = lyraClient;
 }
コード例 #9
0
 public StatsEffect(ILyraAPI lyraClient)
 {
     client = lyraClient;
 }
コード例 #10
0
 public NodeViewActionEffect(ILyraAPI lyraClient, IConfiguration configuration, INodeHistory history)
 {
     client = lyraClient;
     config = configuration;
     hist   = history;
 }
コード例 #11
0
 public BlockSearchEffect(ILyraAPI lyraClient)
 {
     client = lyraClient;
 }
コード例 #12
0
 protected BrokerWallet(IAccountDatabase storage, string name, ILyraAPI rpcClient = null)
     : base(storage, name, rpcClient)
 {
 }