예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task <object> GetAsset(UInt160 asset)
        {
            var assetInfo = AssetCache.GetAssetInfo(asset);

            if (assetInfo == null)
            {
                return(null);
            }
            var totalSupply = AssetCache.GetTotalSupply(asset);

            using var db = new TrackDB();
            var record = db.GetContract(asset);
            var trans  = db.QueryTransactions(new TransactionFilter()
            {
                Contracts = new List <UInt160>()
                {
                    asset
                }, PageSize = 0
            });

            return(new AssetInfoModel()
            {
                Asset = assetInfo.Asset,
                Decimals = assetInfo.Decimals,
                Name = assetInfo.Name,
                Symbol = assetInfo.Symbol,
                TotalSupply = totalSupply,
                CreateTime = record?.CreateTime,
                TransactionCount = trans.TotalCount,
            });
        }
예제 #2
0
        /// <summary>
        /// query relate my wallet balances
        /// </summary>
        /// <returns></returns>
        public async Task <object> GetMyTotalBalance(UInt160[] assets = null)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }

            var addresses = CurrentWallet.GetAccounts().Select(a => a.ScriptHash).ToList();

            using var db = new TrackDB();
            var balances = db.FindAssetBalance(new BalanceFilter()
            {
                Addresses = addresses, Assets = assets
            });

            var result = balances.GroupBy(b => new { b.Asset, b.AssetDecimals, b.AssetSymbol }).Select(g => new AssetBalanceModel
            {
                Asset   = g.Key.Asset,
                Symbol  = g.Key.AssetSymbol,
                Balance = new BigDecimal(g.Select(b => b.Balance).Sum(), g.Key.AssetDecimals)
            }).ToList();

            if (assets.IsEmpty())
            {
                AppendDefaultNeoAndGas(result);
            }
            return(result);
        }
예제 #3
0
        /// <summary>
        /// query transaction info
        /// </summary>
        /// <param name="txId"></param>
        /// <param name="showJson"></param>
        /// <returns></returns>
        public async Task <object> GetRawTransaction(UInt256 txId, bool showJson = false)
        {
            var snapshot    = Helpers.GetDefaultSnapshot();
            var transaction = snapshot.GetTransaction(txId);

            if (transaction == null)
            {
                return(Error(ErrorCode.TxIdNotFound));
            }
            if (showJson)
            {
                JObject          json    = transaction.ToJson(CliSettings.Default.Protocol);
                TransactionState txState = snapshot.GetTransactionState(txId);
                if (txState != null)
                {
                    Header header = snapshot.GetHeader(txState.BlockIndex);
                    json["blockhash"]     = header.Hash.ToString();
                    json["confirmations"] = snapshot.GetHeight() - header.Index + 1;
                    json["blocktime"]     = header.Timestamp;
                    using var db          = new TrackDB();
                    var executelog = db.GetExecuteLog(txId);
                    json["vm_state"] = executelog?.VMState;
                }
                return(json.ToString());
            }
            return(transaction.ToArray().ToHexString());
        }
예제 #4
0
 /// <summary>
 /// Constructor
 /// </summary>
 public DrawPath (TrackDB trackDB, TrackSectionsFile tsectionDat)
 {
     this.trackDB = trackDB;
     this.tsectionDat = tsectionDat;
     this.colorSchemeMain = DrawColors.colorsPathMain;
     this.colorSchemeSiding = DrawColors.colorsPathSiding;
 }
예제 #5
0
        private static void UpdateConsensusGas()
        {
            if (Blockchain.Singleton.Height > 0)
            {
                using var snapshot = Blockchain.Singleton.GetSnapshot();
                var validators = NativeContract.NEO.GetValidators(snapshot);
                var addresses  = new List <UInt160>();
                foreach (var ecPoint in validators)
                {
                    if (!_consensusMap.ContainsKey(ecPoint))
                    {
                        _consensusMap[ecPoint] = ecPoint.ToVerificationContract().ScriptHash;
                    }

                    addresses.Add(_consensusMap[ecPoint]);
                }
                using var db = new TrackDB();
                var gas      = AssetCache.GetAssetInfo(NativeContract.GAS.Hash);
                var balances = addresses.GetBalanceOf(NativeContract.GAS.Hash, snapshot);

                for (var index = 0; index < addresses.Count; index++)
                {
                    var address = addresses[index];
                    db.UpdateBalance(address, gas, balances[index].Value, snapshot.Height);
                }

                db.Commit();
            }
        }
        /// <summary>
        /// query all transactions(on chain)
        /// </summary>
        /// <returns></returns>
        public async Task <object> QueryTransactions(int pageIndex = 1, int limit = 100, uint?blockHeight = null)
        {
            using var db = new TrackDB();
            var trans = db.FindTransactions(new TransactionFilter()
            {
                BlockHeight = blockHeight, PageIndex = pageIndex, PageSize = limit
            });
            var transfers = new List <TransferInfo>();

            if (trans.List.NotEmpty())
            {
                transfers = db.FindTransfer(new TransferFilter()
                {
                    TxIds = trans.List.Select(tx => tx.TxId).ToList(), PageSize = int.MaxValue
                }).List;
            }
            var result = new PageList <TransactionPreviewModel>
            {
                TotalCount = trans.TotalCount,
                PageSize   = trans.PageSize,
                PageIndex  = pageIndex,
                List       = ConvertToTransactionPreviewModel(trans.List, transfers),
            };

            return(result);
        }
예제 #7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="routeData">The data needed for the route</param>
        public TrackItemManager(ORTS.TrackViewer.Drawing.RouteData routeData)
        {
            this.trackDB     = routeData.TrackDB;
            this.tsectionDat = routeData.TsectionDat;

            cachedItems = new Dictionary <TrackNode, IEnumerable <ChartableTrackItem> >();
        }
예제 #8
0
        /// <summary>
        /// query relate my wallet balances
        /// </summary>
        /// <returns></returns>
        public async Task <object> GetMyBalances(UInt160 address = null, UInt160[] assets = null)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }

            var addresses = CurrentWallet.GetAccounts().Select(a => a.ScriptHash).ToList();

            if (address != null)
            {
                if (!addresses.Contains(address))
                {
                    return(Error(ErrorCode.AddressNotFound));
                }
                addresses = new List <UInt160>()
                {
                    address
                };
            }

            using var db = new TrackDB();
            var balances = db.FindAssetBalance(new BalanceFilter()
            {
                Addresses = addresses, Assets = assets
            });

            var result = balances.ToLookup(b => b.Address).ToAddressBalanceModels();

            if (assets.IsEmpty())
            {
                AppendDefaultNeoAndGas(result, addresses);
            }
            return(result);
        }
        /// <summary>
        /// query transaction info
        /// </summary>
        /// <returns></returns>
        public async Task <PageList <TransferInfo> > QueryTransfers(TransferFilter filter)
        {
            using var db = new TrackDB();
            var result = db.FindTransfer(filter) as PageList <TransferInfo>;

            return(result);
        }
예제 #10
0
        int currentIndexUnmodified; // The index of the last saved path.

        #endregion

        /// <summary>
        /// Basic constructor creating an empty path, but storing track database and track section data
        /// </summary>
        /// <param name="trackDB"></param>
        /// <param name="tsectionDat"></param>
        public Trainpath(TrackDB trackDB, TrackSectionsFile tsectionDat)
        {
            this.trackDB     = trackDB;
            this.tsectionDat = tsectionDat;
            trainPaths       = new List <TrainPathData>();
            trainPaths.Add(new TrainPathData());
        }
예제 #11
0
        /// <summary>
        /// query relate my wallet transactions(on chain)
        /// </summary>
        /// <returns></returns>
        public async Task <object> GetMyTransactions(int pageIndex = 1, int limit = 100, UInt160 address = null)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }

            var addresses = address != null ? new List <UInt160>()
            {
                address
            } : CurrentWallet.GetAccounts().Select(a => a.ScriptHash).ToList();

            using var db = new TrackDB();
            var trans = db.FindNep5Transactions(new TransferFilter()
            {
                FromOrTo = addresses, PageIndex = pageIndex, PageSize = limit
            });
            var result = new PageList <TransactionPreviewModel>
            {
                TotalCount = trans.TotalCount,
                PageSize   = trans.PageSize,
                PageIndex  = pageIndex,
                List       = trans.List?.ToTransactionPreviewModel(),
            };

            return(result);
        }
예제 #12
0
        /// <summary>
        /// query all nep transactions(on chain)
        /// </summary>
        /// <returns></returns>
        public async Task <object> QueryNep5Transactions(int pageIndex = 1, int limit = 100, UInt160 address = null, UInt160 asset = null, uint?blockHeight = null)
        {
            using var db = new TrackDB();
            var filter = new TransactionFilter()
            {
                BlockHeight = blockHeight,
                PageIndex   = pageIndex,
                PageSize    = limit
            };

            if (address != null)
            {
                filter.FromOrTo = new List <UInt160>()
                {
                    address
                };
            }
            if (asset != null)
            {
                filter.Contracts = new List <UInt160>()
                {
                    asset
                };
            }
            var trans  = db.QueryTransactions(filter, true);
            var result = new PageList <TransactionPreviewModel>
            {
                TotalCount = trans.TotalCount,
                PageSize   = trans.PageSize,
                PageIndex  = pageIndex,
                List       = ConvertToTransactionPreviewModel(trans.List),
            };

            return(result);
        }
        /// <summary>
        /// GetTransactionLog
        /// </summary>
        /// <returns></returns>
        public async Task <object> GetApplicationLog(UInt256 txId)
        {
            var db     = new TrackDB();
            var result = db.GetExecuteLog(txId);

            return(result);
        }
예제 #14
0
        /// <summary>
        /// Creates an trainpath from PAT file information.
        /// First creates all the nodes and then links them together into a main list
        /// with optional parallel siding list.
        /// </summary>
        /// <param name="trackDB"></param>
        /// <param name="tsectionDat"></param>
        /// <param name="filePath">file name including path of the .pat file</param>
        public Trainpath(TrackDB trackDB, TrackSectionsFile tsectionDat, string filePath)
            : this(trackDB, tsectionDat)
        {
            this.FilePath = filePath;

            PathFile patFile = new PathFile(filePath);

            if (PatFileIsIncomplete(patFile))
            {
                MessageBox.Show("The .pat file is somehow incomplete. Cannot load the path.",
                                "Trackviewer Path Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            PathId    = patFile.PathID;
            PathName  = patFile.Name;
            PathStart = patFile.Start;
            PathEnd   = patFile.End;
            PathFlags = patFile.Flags;

            List <TrainpathNode> Nodes = new List <TrainpathNode>();

            CreateNodes(patFile, Nodes);

            LinkNodes(patFile, Nodes);
            SetFacingPoints(Nodes);

            FindSidingEnds();
            FindNodeOrientations();
            FindWronglyOrientedLinks();
            DetermineIfBroken();
        }
예제 #15
0
 /// <summary>
 /// Constructor from file
 /// </summary>
 /// <param name="filenamewithpath">Full file name of the .rdb file</param>
 public TrackDatabaseFile(string fileName)
 {
     using (STFReader stf = new STFReader(fileName, false))
         stf.ParseFile(new STFReader.TokenProcessor[] {
             new STFReader.TokenProcessor("trackdb", () => { TrackDB = new TrackDB(stf); }),
         });
 }
예제 #16
0
 public TrackContent(TrackDB trackDB, RoadTrackDB roadTrackDB, TrackSectionsFile trackSections, SignalConfigurationFile signalConfig, bool metricUnits)
 {
     this.trackDB      = trackDB;
     this.roadTrackDB  = roadTrackDB;
     trackSectionsFile = trackSections;
     UseMetricUnits    = metricUnits;
     SignalConfigFile  = signalConfig;
 }
예제 #17
0
 /// <summary>
 /// Constructor
 /// </summary>
 public DrawPath(TrackDB trackDB, TrackSectionsFile tsectionDat)
 {
     this.trackDB           = trackDB;
     this.tsectionDat       = tsectionDat;
     this.ColorSchemeMain   = DrawColors.colorsPathMain;
     this.ColorSchemeSiding = DrawColors.colorsPathSiding;
     this.ColorSchemeLast   = DrawColors.ShadeColor(DrawColors.otherPathsReferenceColor, 0, 1);
 }
예제 #18
0
 /// <summary>
 /// Creates a single trainpathNode and initializes everything that do not depend on other nodes.
 /// The trainpath constructor will initialize the rest.
 /// </summary>
 protected TrainpathNode(PathDataPoint pdp, TrackDB trackDB, TrackSectionsFile tsectionDat)
     : this(trackDB, tsectionDat)
 {
     Location = pdp.Location;
     if (pdp.IsInvalid) // not a valid point
     {
         this.SetBroken(NodeStatus.SetAsInvalid);
     }
 }
예제 #19
0
 /// <summary>
 /// basic constructor, in case node is not created from PAT file, and only some parts are needed
 /// </summary>
 protected TrainpathNode(TrackDB trackDB, TrackSectionsFile tsectionDat)
 {
     this.TrackDB       = trackDB;
     this.TsectionDat   = tsectionDat;
     HasSidingPath      = false;
     NextMainTvnIndex   = 0;
     NextSidingTvnIndex = 0;
     NodeType           = TrainpathNodeType.Other;
 }
예제 #20
0
 /// <summary>
 /// Creates a single trainpathNode and initializes everything that do not depend on other nodes.
 /// The trainpath constructor will initialize the rest.
 /// </summary>
 protected TrainpathNode(TrackPDP pdp, TrackDB trackDB, TrackSectionsFile tsectionDat)
     : this(trackDB, tsectionDat)
 {
     Location = new WorldLocation(pdp.TileX, pdp.TileZ, pdp.X, pdp.Y, pdp.Z);
     if (pdp.IsInvalid) // not a valid point
     {
         this.SetBroken(NodeStatus.SetAsInvalid);
     }
 }
예제 #21
0
 public void OnCommit(StoreView snapshot)
 {
     _db.Commit();
     if (_db.LiveTime.TotalSeconds > 15)
     {
         //release memory
         _db.Dispose();
         _db = new TrackDB();
     }
 }
예제 #22
0
        public bool IsVisited;              // true if the train has visited this node

        /// <summary>
        /// Creates a single AIPathNode and initializes everything that do not depend on other nodes.
        /// The AIPath constructor will initialize the rest.
        /// </summary>
        public AIPathNode(TrPathNode tpn, TrackPDP pdp, TrackDB trackDB, bool isTimetableMode)
        {
            ID = (int)tpn.fromPDP;
            InterpretPathNodeFlags(tpn, pdp, isTimetableMode);

            Location = new WorldLocation(pdp.TileX, pdp.TileZ, pdp.X, pdp.Y, pdp.Z);
            if (pdp.IsJunction)
            {
                JunctionIndex = FindJunctionOrEndIndex(Location, trackDB, true);
            }
        }
예제 #23
0
        public async Task <object> GetAddressBalance(UInt160[] addresses, UInt160[] assets)
        {
            using var db = new TrackDB();
            var balances = db.FindAssetBalance(new BalanceFilter()
            {
                Addresses = addresses,
                Assets    = assets,
            });

            return(balances.ToLookup(b => b.Address).ToAddressBalanceModels());
        }
예제 #24
0
        public bool IsVisited;              // true if the train has visited this node

        /// <summary>
        /// Creates a single AIPathNode and initializes everything that do not depend on other nodes.
        /// The AIPath constructor will initialize the rest.
        /// </summary>
        public AIPathNode(PathNode tpn, PathDataPoint pdp, TrackDB trackDB, bool isTimetableMode)
        {
            ID = (int)tpn.PathDataPoint;
            InterpretPathNodeFlags(tpn, pdp, isTimetableMode);

            Location = pdp.Location;
            if (pdp.IsJunction)
            {
                JunctionIndex = FindJunctionOrEndIndex(Location, trackDB, true);
            }
        }
예제 #25
0
 /// <summary>
 /// Sort of constructor. But it creates the right sub-class
 /// </summary>
 /// <returns>A sub-class object properly initialized</returns>
 public static TrainpathNode CreatePathNode(TrPathNode tpn, TrackPDP pdp, TrackDB trackDB, TrackSectionsFile tsectionDat)
 {
     if (pdp.IsJunction)
     {
         // we do not use tpn: this means we do not interpret the flags
         return(new TrainpathJunctionNode(pdp, trackDB, tsectionDat));
     }
     else
     {
         return(new TrainpathVectorNode(tpn, pdp, trackDB, tsectionDat));
     }
 }
예제 #26
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public async Task <object> GetAllAssets()
 {
     using var db = new TrackDB();
     return(db.GetAllAssets()?.Select(a => new AssetInfo()
     {
         Asset = UInt160.Parse(a.Asset),
         Decimals = a.Decimals,
         Name = a.Name,
         Symbol = a.Symbol,
         TotalSupply = new BigInteger(a.TotalSupply),
     }));
 }
예제 #27
0
        /// <summary>
        /// analysis block transaction execute result logs
        /// </summary>
        /// <param name="blockHeight"></param>
        /// <returns></returns>
        public async Task <bool> Sync(uint blockHeight)
        {
            if (blockHeight > Blockchain.Singleton.Height)
            {
                return(false);
            }

            if (_db.HasSyncIndex(blockHeight))
            {
                return(true);
            }

            var block = Blockchain.Singleton.GetBlock(blockHeight);

            if (block.Transactions.IsEmpty())
            {
                return(true);
            }
            using var snapshot = Blockchain.Singleton.GetSnapshot();
            foreach (var transaction in block.Transactions)
            {
                _db.AddTransaction(new TransactionInfo()
                {
                    TxId        = transaction.Hash,
                    BlockHeight = blockHeight,
                    Sender      = transaction.Sender,
                    Time        = block.Timestamp.FromTimestampMS(),
                });
                var executeResult = _db.GetExecuteLog(transaction.Hash);
                if (executeResult == null || executeResult.VMState.HasFlag(VMState.FAULT) || executeResult.Notifications.IsEmpty())
                {
                    continue;
                }

                foreach (var notification in executeResult.Notifications)
                {
                    HasTransfer(notification, transaction, block, snapshot);
                }

                //shouldCommit = executeResult.Notifications.Aggregate(shouldCommit, (current, notification) => current | HasTransfer(notification, transaction, block, snapshot));
            }

            _db.AddSyncIndex(blockHeight);
            _db.Commit();
            Console.WriteLine($"Syncing:{_scanHeight}");
            if (_db.LiveTime.TotalSeconds > 15)
            {
                //release memory
                _db.Dispose();
                _db = new TrackDB();
            }
            return(true);
        }
예제 #28
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="routeData">The data needed for the route</param>
        public TrackItemManager(ORTS.TrackViewer.Drawing.RouteData routeData)
        {
            this.trackDB     = routeData.TrackDB;
            this.tsectionDat = routeData.TsectionDat;

            cachedItems = new Dictionary <TrackNode, IEnumerable <ChartableTrackItem> >();

            supportedTrackTypes = new HashSet <TrItem.trItemType> {
                TrItem.trItemType.trPLATFORM,
                TrItem.trItemType.trSPEEDPOST,
            };
        }
예제 #29
0
 /// <summary>
 /// Find the angle that the signal needs to be drawn at
 /// </summary>
 /// <param name="tsectionDat">Database with track sections</param>
 /// <param name="trackDB">Database with tracks</param>
 /// <param name="tn">TrackNode on which the signal actually is</param>
 public void FindAngle(TrackSectionsFile tsectionDat, TrackDB trackDB, TrackNode tn)
 {
     this.angle = 0;
     try
     {
         Traveller signalTraveller = new Traveller(tsectionDat, trackDB.TrackNodes, tn,
                                                   this.WorldLocation.TileX, this.WorldLocation.TileZ,
                                                   this.WorldLocation.Location.X, this.WorldLocation.Location.Z,
                                                   this.direction);
         this.angle = signalTraveller.RotY;
     }
     catch { }
 }
예제 #30
0
        public async Task Initialize()
        {
            List <Task> initializer = new List <Task>
            {
                Task.Run(async() => await InitializeTrackSegments().ConfigureAwait(false))
            };

            await Task.WhenAll(initializer).ConfigureAwait(false);

            trackDB           = null;
            roadTrackDB       = null;
            trackSectionsFile = null;
        }