예제 #1
0
            public void HeaderCanBeBoxed()
            {
                var header1 = new Header("Header1", "Value");
                var header2 = new Header("Header1", "Value");

                Assert.True(header1.Equals((Object)header2));
            }
            public void ReturnHeaderValueIfSpecified()
            {
                var header = new Header(Header.Origin, "ServerName", checkReservedNames: false);
                var headers = new HeaderCollection(header.ToEnumerable());

                Assert.Equal("ServerName", headers.GetOrigin());
            }
예제 #3
0
 public Message Parse(Header header, byte[] data, uint crc)
 {
     return new BoatLocation
     {
         Version = data[0],
         Time = Utility.GetTime(data, 1),
         SourceId = (uint)Utility.GetLongLE(data, 7, 4),
         SequenceNum = (uint)Utility.GetLongLE(data, 11, 4),
         DeviceType = (DeviceType)data[15],
         Latitude = Utility.ToLatitude(Utility.GetLongLE(data, 16, 4)),
         Longitude = Utility.ToLongitude(Utility.GetLongLE(data, 20, 4)),
         Altitude = (int)Utility.GetLongLE(data, 24, 4), //cm relative to MSL (Mean sea level)
         Heading = Utility.GetHeading(Utility.GetLongLE(data, 28, 2)),
         Pitch = Utility.ToDegree(Utility.GetLongLE(data, 30, 2)),
         Roll = Utility.ToDegree(Utility.GetLongLE(data, 32, 2)),
         BoatSpeed = (uint)Utility.GetLongLE(data, 34, 2),
         COG = (uint)Utility.GetLongLE(data, 36, 2),
         SOG = (uint)Utility.GetLongLE(data, 38, 2),
         ApparentWindSpeed = (uint)Utility.GetLongLE(data, 40, 2), 
         ApparentWindAngle = Utility.ToDegree(Utility.GetLongLE(data, 42, 2)),
         TrueWindSpeed = (uint)Utility.GetLongLE(data, 44, 2),
         TrueWindDirection = (uint)Utility.GetLongLE(data, 46, 2),
         TrueWindAngle = Utility.ToDegree(Utility.GetLongLE(data, 48, 2)),
         CurrentDrift = (uint)Utility.GetLongLE(data, 50, 2),
         CurrentSet = (uint)Utility.GetLongLE(data, 52, 2),
         RudderAngle = Utility.ToDegree(Utility.GetLongLE(data, 54, 2)),
         Header = header,
         Crc = crc
     };
 }
예제 #4
0
            public void AlwaysReturnConsistentValue()
            {
                var header1 = new Header("Header1", "Value");
                var header2 = new Header("Header1", "Value");

                Assert.Equal(header1.GetHashCode(), header2.GetHashCode());
            }
        /// <summary>
        ///     *
        /// </summary>
        public override void ReadScaleFactor(Bitstream stream, Header header)
        {
            if (allocation != 0)
            {
                base.ReadScaleFactor(stream, header);
                switch (channel2_scfsi)
                {
                    case 0:
                        channel2_scalefactor1 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor2 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 1:
                        channel2_scalefactor1 = channel2_scalefactor2 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 2:
                        channel2_scalefactor1 =
                            channel2_scalefactor2 = channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 3:
                        channel2_scalefactor1 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor2 = channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Parses csv
        /// </summary>
        /// <param name="data">csv data</param>
        /// <returns>Header object</returns>
        public static Header Parse(List<List<string>> data)
        {
            var root = new Header
            {
                Name = "Root",
                Depth = -1,
                From = 0,
                To = data.ElementAt(0).Count - 1,
            };

            for (var i = 0; i < HeaderRowCount; i++)
            {
                var row = data.ElementAt(i);
                Header current = null;
                for (var j = 1; j < row.Count; j++)
                {
                    var value = row[j];
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        current = new Header { Name = value, Depth = i, From = j, To = j, Parent = Header.GetParent(root, i, j) };
                        current.Parent.Children.Add(current);
                    }
                    else if (current != null)
                    {
                        var parentOfCurrent = Header.GetParent(root, current.Depth, current.From);
                        if (current.To < parentOfCurrent.To)
                        {
                            current.To++;
                        }
                    }
                }
            }

            return root;
        }
예제 #7
0
        public int GetHeaderLength()
        {
            return 6;// todo: find why catch web crash and fix it

            Header header = new Header ();
            return Marshal.SizeOf (header);
        }
 public void TestSetCategories()
 {
     var test = new Header();
     test.SetCategories(new List<string>{"dogs","animals","pets","mammals"});
     var result = test.AsJson();
     Assert.AreEqual("{\"category\" : [\"dogs\", \"animals\", \"pets\", \"mammals\"]}", result);
 }
예제 #9
0
파일: Session.cs 프로젝트: Myvar/MyvarWeb
        public Session(Header header, Action<string> _WriteHeader)
        {
            this.header = header;
            this._WriteHeader = _WriteHeader;

            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }

            file = ".\\tmp\\";

            foreach (var i in header.Headers)
            {
                if (i is CookieHeader)
                {
                    var x = i as CookieHeader;
                    foreach (var cookie in x.Cookies.Split(';'))
                    {
                        var co = cookie.Trim().Split('=');
                        if (co[0] == "sid")
                        {
                            FoundCookie = true;
                            file += co[1] + ".json";
                        }
                    }

                    break;
                }
            }
        }
예제 #10
0
 public void TestAddUniqueIdentifier()
 {
     var test = new Header();
     test.AddUniqueIdentifier(new Dictionary<string, string>(){{"foo", "bar"}});
     var result = test.AsJson();
     Assert.AreEqual("{\"unique_args\" : {\"foo\" : \"bar\"}}", result);
 }
예제 #11
0
 public void TestEnable()
 {
     var test = new Header();
     test.Enable("foo");
     var result = test.AsJson();
     Assert.AreEqual("{\"filters\" : {\"foo\" : {\"settings\" : {\"enable\" : \"1\"}}}}", result);
 }
예제 #12
0
 public void TestAddFilterSetting()
 {
     var test = new Header();
     test.AddFilterSetting("foo", new List<string> { "a", "b" }, "bar");
     var result = test.AsJson();
     Assert.AreEqual("{\"filters\" : {\"foo\" : {\"settings\" : {\"a\" : {\"b\" : \"bar\"}}}}}", result);
 }
예제 #13
0
 public void TestAddSubVal()
 {
     var test = new Header();
     test.AddSubVal("foo", new List<string>{"bar", "raz"});
     var result = test.AsJson();
     Assert.AreEqual("{\"sub\" : {\"foo\" : [\"bar\", \"raz\"]}}", result);
 }
예제 #14
0
        public void TestParseWithEmptyData()
        {
            // Arrange
            var header = new Header { Name = "Root", Depth = -1, From = 0, To = 2, Children =
                new List<Header> {
                    new Header { Name = "Arrange", Depth = 0, From = 1, To = 1, Children =
                        new List<Header> {
                            new Header { Name = "HttpRequest Actual", Depth = 1, From = 1, To = 1, Children =
                                new List<Header> {
                                    new Header { Name = "BaseUri", Depth = 2, From = 1, To = 1, },
                                }
                            }
                        }
                    },
                    new Header { Name = "Assertion", Depth = 0, From = 2, To = 2, Children =
                        new List<Header> {
                            new Header { Name = "Uri", Depth = 1, From = 2, To = 2, },
                        }
                    }
                }
            };

            // Arrange
            var data = new List<List<string>>();

            // Act
            TestCaseParser.Parse(header, data, null);
        }
예제 #15
0
        public Message Parse(Header header, byte[] data, uint crc)
        {
            XmlMessage message = new XmlMessage()
            {
                Header = header,
                Version = data[0],
                TimeStamp = Utility.GetTime(data, 3),
                SubType = (XmlMessageSubType)data[9],
                SequenceNumber = (uint)Utility.GetLongLE(data, 10, 2),
                Crc = crc
            };

            int length = (int)Utility.GetLongLE(data, 12, 2);
            message.Text = Encoding.ASCII.GetString(data, 14, length);

            switch (message.SubType)
            {
                case XmlMessageSubType.Regatta:
                    message.Config = Utility.FromXml<RegattaConfig>(message.Text);
                    break;
                case XmlMessageSubType.Race:
                    message.Config = Utility.FromXml<Race>(message.Text);
                    break;
                case XmlMessageSubType.Boat:
                    string text = message.Text.Replace("\0", "");
                    message.Config = Utility.FromXml<BoatConfig>(text);
                    break;
            }

            return message;
        }
예제 #16
0
 public void TestSetAsmGroupId()
 {
     var test = new Header();
     test.SetAsmGroupId(123);
     string result = test.JsonString();
     Assert.AreEqual("{\"asm_group_id\" : 123}", result);
 }
예제 #17
0
        public void TestParse()
        {
            // Arrange
            var header = new Header { Name = "Root", Depth = -1, From = 0, To = 2, Children =
                new List<Header> {
                    new Header { Name = "Arrange", Depth = 0, From = 1, To = 1, Children =
                        new List<Header> {
                            new Header { Name = "HttpRequest Actual", Depth = 1, From = 1, To = 1, Children =
                                new List<Header> {
                                    new Header { Name = "BaseUri", Depth = 2, From = 1, To = 1, },
                                }
                            }
                        }
                    },
                    new Header { Name = "Assertion", Depth = 0, From = 2, To = 2, Children =
                        new List<Header> {
                            new Header { Name = "Uri", Depth = 1, From = 2, To = 2, },
                        }
                    }
                }
            };

            var data = new List<List<string>>
            {
                new List<string> { "test case 1", "BaseUri", "/local" }
            };

            // Act
            var result = TestCaseParser.Parse(header, data, null);

            // Assert
            Assert.AreEqual("test case 1", result.Name);
            Assert.AreEqual(1, result.Assertions.Count);
        }
예제 #18
0
 public void TestAddUniqueArgs()
 {
     var test = new Header();
     test.AddUniqueArgs(new Dictionary<string, string> {{"foo", "bar"}});
     string result = test.JsonString();
     Assert.AreEqual("{\"unique_args\" : {\"foo\" : \"bar\"}}", result);
 }
예제 #19
0
 public void TestDisable()
 {
     var test = new Header();
     test.DisableFilter("foo");
     string result = test.JsonString();
     Assert.AreEqual("{\"filters\" : {\"foo\" : {\"settings\" : {\"enable\" : \"0\"}}}}", result);
 }
        /// <summary>
        /// Validates the policy data items.
        /// </summary>
        /// <param name="header">The header.</param>
        /// <returns>Process Results Collection</returns>
        private ProcessResultsCollection ValidatePolicyDataItems(Header header)
        {
            var processResultsCollection = new ProcessResultsCollection();
            // Get the latest version of the UW Header
            var headerVersion = (HeaderVersion)header.GetLatestVersion();
            // Validate the Generic Data Items
            this.ValidateGenericDataItems(processResultsCollection, headerVersion, this.ExtractGenericDataItems(headerVersion), headerVersion);
            
            var sectionDetails = from s in header.Sections
                                 from sd in s.SectionDetails
                                 select sd;
            // Cycle through all Section Details on the Header
            foreach (var sectionDetail in sectionDetails)
            {
                // Get the latest version
                var sectionDetailVersion = (SectionDetailVersion)sectionDetail.GetLatestVersion();
                // Validate all the generic data items are correct on this Section detail.
                this.ValidateGenericDataItems(processResultsCollection, sectionDetailVersion, this.ExtractGenericDataItems(sectionDetailVersion), headerVersion);

                // Cycle through all the coverages on this Section Detail
                foreach (var coverage in sectionDetail.Coverages)
                {
                    // Get latest version and validate the Generic data items
                    var coverageVersion = (CoverageVersion)coverage.GetLatestVersion();
                    this.ValidateGenericDataItems(processResultsCollection, coverageVersion, this.ExtractGenericDataItems(coverageVersion), headerVersion);
                }
            }

            return processResultsCollection;
        }
예제 #21
0
 public void TestAddSection()
 {
     var test = new Header();
     test.AddSection("foo", "bar");
     string result = test.JsonString();
     Assert.AreEqual("{\"section\" : {\"foo\" : \"bar\"}}", result);
 }
예제 #22
0
		/*
		cd /tmp
		c->s REALPATH
		s->c NAME
		c->s STAT
		s->c ATTR
		*/
		public void cd(String path)
		{
			//throws SftpException{
			try
			{
				path = RemoteAbsolutePath(path);

				ArrayList v = glob_remote(path);
				if (v.Count != 1)
				{
					throw new SftpException(SSH_FX_FAILURE, v.ToString());
				}
				path = (String)(v[0]);
				sendREALPATH(path);

				Header _header = new Header();
				_header = ReadHeader(buf, _header);
				int length = _header.length;
				int type = _header.type;
				buf.Rewind();
				fill(buf.buffer, 0, length);

				if (type != 101 && type != 104)
				{
					throw new SftpException(SSH_FX_FAILURE, "");
				}
				int i;
				if (type == 101)
				{
					i = buf.ReadInt();
					throwStatusError(buf, i);
				}
				i = buf.ReadInt();
				byte[] str = buf.ReadString();
				if (str != null && str[0] != '/')
				{
					str = Encoding.UTF8.GetBytes(cwd + "/" + str);
				}
				str = buf.ReadString();         // logname
				i = buf.ReadInt();              // attrs

				String newpwd = Encoding.UTF8.GetString(str);
				SftpATTRS attr = _stat(newpwd);
				if ((attr.Flags & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0)
				{
					throw new SftpException(SSH_FX_FAILURE, "Can't change directory: " + path);
				}

				if (!attr.IsDirectory)
				{
					throw new SftpException(SSH_FX_FAILURE, "Can't change directory: " + path);
				}
				cwd = newpwd;
			}
			catch (Exception e)
			{
				if (e is SftpException) throw (SftpException)e;
				throw new SftpException(SSH_FX_FAILURE, "");
			}
		}
예제 #23
0
      static private void Test(Header header)
      {
         Debug.Assert(Program.IsApprox(header.GetMinX(), 635619.85, 0.01));
         Debug.Assert(Program.IsApprox(header.GetMinY(), 848899.70, 0.01));
         Debug.Assert(Program.IsApprox(header.GetMinZ(), 406.59, 0.01));
           
         Debug.Assert(Program.IsApprox(header.GetMaxX(), 638982.55, 0.01));
         Debug.Assert(Program.IsApprox(header.GetMaxY(), 853535.43, 0.01));
         Debug.Assert(Program.IsApprox(header.GetMaxZ(), 586.38, 0.01));

         Debug.Assert(Program.IsApprox(header.GetScaleX(), 0.01, 0.01));
         Debug.Assert(Program.IsApprox(header.GetScaleY(), 0.01, 0.01));
         Debug.Assert(Program.IsApprox(header.GetScaleZ(), 0.01, 0.01));

         Debug.Assert(Program.IsApprox(header.GetOffsetX(), 0.0, 0.001));
         Debug.Assert(Program.IsApprox(header.GetOffsetY(), 0.0, 0.001));
         Debug.Assert(Program.IsApprox(header.GetOffsetZ(), 0.0, 0.001));

         Debug.Assert(header.GetFileSignature() == "LASF");
         Debug.Assert(header.GetFileSourceId() == 0);
         Debug.Assert(header.GetVersionMajor() == 1);
         Debug.Assert(header.GetVersionMinor() == 2);
         Debug.Assert(header.GetDataFormatId() == PointFormatName.ePointFormat3);
         Debug.Assert(header.GetPointRecordsCount() == 1065);

         return;
      }
예제 #24
0
        /// <summary>
        ///     *
        /// </summary>
        public override void ReadScaleFactor(Bitstream stream, Header header)
        {
            base.ReadScaleFactor(stream, header);
            if (channel2_allocation != 0)
            {
                switch (channel2_scfsi)
                {
                    case 0:
                        channel2_scalefactor1 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor2 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 1:
                        channel2_scalefactor1 = channel2_scalefactor2 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 2:
                        channel2_scalefactor1 =
                            channel2_scalefactor2 = channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;

                    case 3:
                        channel2_scalefactor1 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        channel2_scalefactor2 = channel2_scalefactor3 = ScaleFactors[stream.GetBitsFromBuffer(6)];
                        break;
                }
                prepare_sample_reading(header, channel2_allocation, 1, channel2_factor, channel2_codelength,
                    channel2_c, channel2_d);
            }
        }
예제 #25
0
 /// <summary>
 ///     *
 /// </summary>
 public override void read_scalefactor(Bitstream stream, Header header)
 {
     if (allocation != 0)
         scalefactor = ScaleFactors[stream.GetBitsFromBuffer(6)];
     if (channel2_allocation != 0)
         channel2_scalefactor = ScaleFactors[stream.GetBitsFromBuffer(6)];
 }
예제 #26
0
 public static void SendHeader(Header header, Stream stream)
 {
     string sBuffer = "";
     sBuffer = header.ToString();
     stream.Write(Encoding.ASCII.GetBytes(sBuffer), 0, sBuffer.Length);
     stream.Flush();
 }
예제 #27
0
        public void TestParse()
        {
            // Arrange
            var data = new List<string> { null, "ExpectedSite", "TargetSite" };
            var header = new Header { Name = "Arrange", Depth = 0, From = 0, To = 2, Children =
                new List<Header> {
                    new Header { Name = "HttpRequest Expected", Depth = 1, From = 1, To = 1, Children =
                        new List<Header> {
                            new Header { Name = "BaseUri", Depth = 2, From = 1, To = 1, },
                        }
                    },
                    new Header { Name = "HttpRequest Actual", Depth = 1, From = 2, To = 2, Children =
                        new List<Header> {
                            new Header { Name = "BaseUri", Depth = 2, From = 2, To = 2, },
                        }
                    }
                }
            };

            // Act
            var result = ArrangesParser.Parse(header, data);

            // Assert
            Assert.IsTrue(result.Expected != null);
            Assert.IsTrue(result.Actual != null);
        }
예제 #28
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
            public void should_be_able_to_add_to_default_headers()
            {
                var header = new Header("name", "value");
                HeaderProvider.AddHeader(header);

                HeaderProvider.Headers.Contains(header).Should().BeTrue();
            }
예제 #30
0
 public void TestAllMessages()
 {
     while (Input.Position < (Input.Length - 1))
     {
         Header h = new Header(Input);
         switch (h.SystemType)
         {
             case SystemPacketType.EventId:
                 TestEventId(h);
                 break;
             case SystemPacketType.Copyright:
                 TestCopyright(h);
                 break;
             case SystemPacketType.Notice:
                 TestNotice(h);
                 break;
             case SystemPacketType.Unknown1:
                 TestUnknown1(h);
                 break;
             case SystemPacketType.RefreshRate:
                 TestUnknown2(h);
                 break;
             case SystemPacketType.KeyFrame:
                 TestKeyFrame(h);
                 break;
             default:
                 Assert.Fail();
                 break;
         }
     }
 }
예제 #31
0
 public ActionResult(Header header, GoalStatus status)
 {
     this.header = header;
     this.status = status;
 }
예제 #32
0
 public RelativeHumidity()
 {
     header = new Header();
 }
예제 #33
0
 public FibonacciActionFeedback(Header header, GoalStatus status, FibonacciFeedback feedback) : base(header, status)
 {
     this.feedback = feedback;
 }
예제 #34
0
        private HttpRequest GetRequest(Stream inputStream)
        {
            //Read Request Line
            string requestLine = StreamUtils.ReadLine(inputStream);

            string[] tokens = requestLine.Split(' ');

            while (tokens.Length != 3)
            {
                requestLine = StreamUtils.ReadLine(inputStream);
                tokens      = requestLine.Split(' ');
            }

            RequestMethod method          = (RequestMethod)Enum.Parse(typeof(RequestMethod), tokens[0].ToUpper());
            string        url             = tokens[1];
            string        protocolVersion = tokens[2];

            //Read Headers
            Header header = new Header(HeaderType.HttpRequest);
            string line;

            while ((line = StreamUtils.ReadLine(inputStream)) != null)
            {
                if (line.Equals(""))
                {
                    break;
                }

                int separator = line.IndexOf(':');
                if (separator == -1)
                {
                    throw new Exception("invalid http header line: " + line);
                }
                string name = line.Substring(0, separator);
                int    pos  = separator + 1;
                while ((pos < line.Length) && (line[pos] == ' '))
                {
                    pos++;
                }

                string value = line.Substring(pos, line.Length - pos);
                if (name == "Cookie")
                {
                    string[] cookieSaves = value.Split(';');
                    foreach (var cookieSave in cookieSaves)
                    {
                        string[] cookiePair = cookieSave.Split('=').Select(x => x.Trim()).ToArray();
                        var      cookie     = new Cookie(cookiePair[0], cookiePair[1]);
                        header.AddCookie(cookie);
                    }
                }
                else if (name == "Location")
                {
                    header.Location = value;
                }
                else if (name == "Content-Length")
                {
                    header.ContentLength = value;
                }
                else
                {
                    header.OtherParameters.Add(name, value);
                }
            }



            string content = null;

            if (header.ContentLength != null)
            {
                int    totalBytes = Convert.ToInt32(header.ContentLength);
                int    bytesLeft  = totalBytes;
                byte[] bytes      = new byte[totalBytes];

                while (bytesLeft > 0)
                {
                    byte[] buffer = new byte[bytesLeft > 1024 ? 1024 : bytesLeft];
                    int    n      = inputStream.Read(buffer, 0, buffer.Length);
                    buffer.CopyTo(bytes, totalBytes - bytesLeft);

                    bytesLeft -= n;
                }

                content = Encoding.ASCII.GetString(bytes);
            }



            var request = new HttpRequest()
            {
                Method  = method,
                Url     = url,
                Header  = header,
                Content = content
            };

            if (request.Header.Cookies.Contains("sessionId"))
            {
                var sessionId = request.Header.Cookies["sessionId"].Value;
                request.Session = new HttpSession(sessionId);
                if (!this.sessions.ContainsKey(sessionId))
                {
                    this.sessions.Add(sessionId, request.Session);
                }
            }

            Console.WriteLine("-REQUEST-----------------------------");
            Console.WriteLine(request);
            Console.WriteLine("------------------------------");

            return(request);
        }
예제 #35
0
 public Mid0077(Header header) : base(header)
 {
 }
예제 #36
0
 public InertiaStamped(Header header, Inertia inertia)
 {
     this.header  = header;
     this.inertia = inertia;
 }
예제 #37
0
 public InertiaStamped()
 {
     this.header  = new Header();
     this.inertia = new Inertia();
 }
예제 #38
0
        public void ConsensusService_SingleNodeActors_OnStart_PrepReq_PrepResponses_Commits()
        {
            var mockWallet = new Mock<Wallet>();
            mockWallet.Setup(p => p.GetAccount(It.IsAny<UInt160>())).Returns<UInt160>(p => new TestWalletAccount(p));
            Console.WriteLine($"\n(UT-Consensus) Wallet is: {mockWallet.Object.GetAccount(UInt160.Zero).GetKey().PublicKey}");

            var mockContext = new Mock<ConsensusContext>(mockWallet.Object, Blockchain.Singleton.Store);
            mockContext.Object.LastSeenMessage = new int[] { 0, 0, 0, 0, 0, 0, 0 };

            KeyPair[] kp_array = new KeyPair[7]
                {
                    UT_Crypto.generateKey(32), // not used, kept for index consistency, didactically
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32)
                };

            var timeValues = new[] {
              new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc),  // For tests, used below
              new DateTime(1980, 06, 01, 0, 0, 3, 001, DateTimeKind.Utc),  // For receiving block
              new DateTime(1980, 05, 01, 0, 0, 5, 001, DateTimeKind.Utc), // For Initialize
              new DateTime(1980, 06, 01, 0, 0, 15, 001, DateTimeKind.Utc), // unused
            };
            for (int i = 0; i < timeValues.Length; i++)
                Console.WriteLine($"time {i}: {timeValues[i].ToString()} ");
            ulong defaultTimestamp = 328665601001;   // GMT: Sunday, June 1, 1980 12:00:01.001 AM
                                                     // check basic ConsensusContext
                                                     // mockConsensusContext.Object.block_received_time.ToTimestamp().Should().Be(4244941697); //1968-06-01 00:00:01
                                                     // ============================================================================
                                                     //                      creating ConsensusService actor
                                                     // ============================================================================

            int timeIndex = 0;
            var timeMock = new Mock<TimeProvider>();
            timeMock.SetupGet(tp => tp.UtcNow).Returns(() => timeValues[timeIndex]);
            //.Callback(() => timeIndex = timeIndex + 1); //Comment while index is not fixed

            TimeProvider.Current = timeMock.Object;
            TimeProvider.Current.UtcNow.ToTimestampMS().Should().Be(defaultTimestamp); //1980-06-01 00:00:15:001

            //public void Log(string message, LogLevel level)
            //create ILogPlugin for Tests
            /*
            mockConsensusContext.Setup(mr => mr.Log(It.IsAny<string>(), It.IsAny<LogLevel>()))
                         .Callback((string message, LogLevel level) => {
                                         Console.WriteLine($"CONSENSUS LOG: {message}");
                                                                   }
                                  );
             */

            // Creating a test block
            Header header = new Header();
            TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal);
            header.Size.Should().Be(105);
            Console.WriteLine($"header {header} hash {header.Hash} {header.PrevHash} timestamp {timestampVal}");
            timestampVal.Should().Be(defaultTimestamp);
            TestProbe subscriber = CreateTestProbe();
            TestActorRef<ConsensusService> actorConsensus = ActorOfAsTestActorRef<ConsensusService>(
                                     Akka.Actor.Props.Create(() => (ConsensusService)Activator.CreateInstance(typeof(ConsensusService), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { subscriber, subscriber, mockContext.Object }, null))
                                     );

            var testPersistCompleted = new Blockchain.PersistCompleted
            {
                Block = new Block
                {
                    Version = header.Version,
                    PrevHash = header.PrevHash,
                    MerkleRoot = header.MerkleRoot,
                    Timestamp = header.Timestamp,
                    Index = header.Index,
                    NextConsensus = header.NextConsensus,
                    Transactions = new Transaction[0]
                }
            };
            Console.WriteLine("\n==========================");
            Console.WriteLine("Telling a new block to actor consensus...");
            Console.WriteLine("will trigger OnPersistCompleted without OnStart flag!");
            // OnPersist will not launch timer, we need OnStart
            actorConsensus.Tell(testPersistCompleted);
            Console.WriteLine("\n==========================");

            Console.WriteLine("\n==========================");
            Console.WriteLine("will start consensus!");
            actorConsensus.Tell(new ConsensusService.Start
            {
                IgnoreRecoveryLogs = true
            });

            Console.WriteLine("Waiting for subscriber recovery message...");
            // The next line force a waits, then, subscriber keeps running its thread
            // In the next case it waits for a Msg of type LocalNode.SendDirectly
            // As we may expect, as soon as consensus start it sends a RecoveryRequest of this aforementioned type
            var askingForInitialRecovery = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            Console.WriteLine($"Recovery Message I: {askingForInitialRecovery}");
            // Ensuring cast of type ConsensusPayload from the received message from subscriber
            ConsensusPayload initialRecoveryPayload = (ConsensusPayload)askingForInitialRecovery.Inventory;
            // Ensuring casting of type RecoveryRequest
            RecoveryRequest rrm = (RecoveryRequest)initialRecoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);

            Console.WriteLine("Waiting for backup ChangeView... ");
            var backupOnAskingChangeView = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var changeViewPayload = (ConsensusPayload)backupOnAskingChangeView.Inventory;
            ChangeView cvm = (ChangeView)changeViewPayload.ConsensusMessage;
            cvm.Timestamp.Should().Be(defaultTimestamp);
            cvm.ViewNumber.Should().Be(0);
            cvm.Reason.Should().Be(ChangeViewReason.Timeout);

            // Original Contract
            Contract originalContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators);
            Console.WriteLine($"\nORIGINAL Contract is: {originalContract.ScriptHash}");
            Console.WriteLine($"ORIGINAL NextConsensus: {mockContext.Object.Block.NextConsensus}\nENSURING values...");
            originalContract.ScriptHash.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));
            mockContext.Object.Block.NextConsensus.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));

            Console.WriteLine("\n==========================");
            Console.WriteLine("will trigger OnPersistCompleted again with OnStart flag!");
            actorConsensus.Tell(testPersistCompleted);
            Console.WriteLine("\n==========================");

            // Disabling flag ViewChanging by reverting cache of changeview that was sent
            mockContext.Object.ChangeViewPayloads[mockContext.Object.MyIndex] = null;
            Console.WriteLine("Forcing Failed nodes for recovery request... ");
            mockContext.Object.CountFailed.Should().Be(0);
            mockContext.Object.LastSeenMessage = new int[] { -1, -1, -1, -1, -1, -1, -1 };
            mockContext.Object.CountFailed.Should().Be(7);
            Console.WriteLine("\nWaiting for recovery due to failed nodes... ");
            var backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);

            Console.WriteLine("will create template MakePrepareRequest...");
            mockContext.Object.PrevHeader.Timestamp = defaultTimestamp;
            mockContext.Object.PrevHeader.NextConsensus.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));
            var prepReq = mockContext.Object.MakePrepareRequest();
            var ppToSend = (PrepareRequest)prepReq.ConsensusMessage;
            // Forcing hashes to 0 because mempool is currently shared
            ppToSend.TransactionHashes = new UInt256[0];
            ppToSend.TransactionHashes.Length.Should().Be(0);
            Console.WriteLine($"\nAsserting PreparationPayloads is 1 (After MakePrepareRequest)...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(1);
            mockContext.Object.PreparationPayloads[prepReq.ValidatorIndex] = null;

            Console.WriteLine("will tell prepare request!");
            actorConsensus.Tell(prepReq);
            Console.WriteLine("Waiting for something related to the PrepRequest...\nNothing happens...Recovery will come due to failed nodes");
            var backupOnRecoveryDueToFailedNodesII = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var recoveryPayloadII = (ConsensusPayload)backupOnRecoveryDueToFailedNodesII.Inventory;
            rrm = (RecoveryRequest)recoveryPayloadII.ConsensusMessage;
            Console.WriteLine($"\nAsserting PreparationPayloads is 0...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(0);
            Console.WriteLine($"\nAsserting CountFailed is 6...");
            mockContext.Object.CountFailed.Should().Be(6);

            Console.WriteLine("\nFailed because it is not primary and it created the prereq...Time to adjust");
            prepReq.ValidatorIndex = 1; //simulating primary as prepreq creator (signature is skip, no problem)
            // cleaning old try with Self ValidatorIndex
            mockContext.Object.PreparationPayloads[mockContext.Object.MyIndex] = null;

            actorConsensus.Tell(prepReq);
            var OnPrepResponse = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var prepResponsePayload = (ConsensusPayload)OnPrepResponse.Inventory;
            PrepareResponse prm = (PrepareResponse)prepResponsePayload.ConsensusMessage;
            prm.PreparationHash.Should().Be(prepReq.Hash);
            Console.WriteLine("\nAsserting PreparationPayloads count is 2...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(2);
            Console.WriteLine($"\nAsserting CountFailed is 5...");
            mockContext.Object.CountFailed.Should().Be(5);

            // Simulating CN 3
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 2));
            //Waiting for RecoveryRequest for a more deterministic UT
            backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);
            //Asserts
            Console.WriteLine("\nAsserting PreparationPayloads count is 3...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(3);
            Console.WriteLine($"\nAsserting CountFailed is 4...");
            mockContext.Object.CountFailed.Should().Be(4);

            // Simulating CN 5
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 4));
            //Waiting for RecoveryRequest for a more deterministic UT
            backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);
            //Asserts            
            Console.WriteLine("\nAsserting PreparationPayloads count is 4...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(4);
            Console.WriteLine($"\nAsserting CountFailed is 3...");
            mockContext.Object.CountFailed.Should().Be(3);

            // Simulating CN 4
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 3));
            var onCommitPayload = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var commitPayload = (ConsensusPayload)onCommitPayload.Inventory;
            Commit cm = (Commit)commitPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting PreparationPayloads count is 5...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(5);
            Console.WriteLine("\nAsserting CountCommitted is 1...");
            mockContext.Object.CountCommitted.Should().Be(1);
            Console.WriteLine($"\nAsserting CountFailed is 2...");
            mockContext.Object.CountFailed.Should().Be(2);

            Console.WriteLine($"ORIGINAL BlockHash: {mockContext.Object.Block.Hash}");
            Console.WriteLine($"ORIGINAL Block NextConsensus: {mockContext.Object.Block.NextConsensus}");

            for (int i = 0; i < mockContext.Object.Validators.Length; i++)
                Console.WriteLine($"{mockContext.Object.Validators[i]}/{Contract.CreateSignatureContract(mockContext.Object.Validators[i]).ScriptHash}");
            mockContext.Object.Validators = new ECPoint[7]
                {
                    kp_array[0].PublicKey,
                    kp_array[1].PublicKey,
                    kp_array[2].PublicKey,
                    kp_array[3].PublicKey,
                    kp_array[4].PublicKey,
                    kp_array[5].PublicKey,
                    kp_array[6].PublicKey
                };
            Console.WriteLine($"Generated keypairs PKey:");
            for (int i = 0; i < mockContext.Object.Validators.Length; i++)
                Console.WriteLine($"{mockContext.Object.Validators[i]}/{Contract.CreateSignatureContract(mockContext.Object.Validators[i]).ScriptHash}");
            var updatedContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators);
            Console.WriteLine($"\nContract updated: {updatedContract.ScriptHash}");

            // ===============================================================
            mockContext.Object.Snapshot.Storages.Add(CreateStorageKeyForNativeNeo(14), new StorageItem()
            {
                Value = mockContext.Object.Validators.ToByteArray()
            });
            mockContext.Object.Snapshot.Commit();
            // ===============================================================

            // Forcing next consensus
            var originalBlockHashData = mockContext.Object.Block.GetHashData();
            mockContext.Object.Block.NextConsensus = updatedContract.ScriptHash;
            mockContext.Object.Block.Header.NextConsensus = updatedContract.ScriptHash;
            var originalBlockMerkleRoot = mockContext.Object.Block.MerkleRoot;
            Console.WriteLine($"\noriginalBlockMerkleRoot: {originalBlockMerkleRoot}");
            var updatedBlockHashData = mockContext.Object.Block.GetHashData();
            Console.WriteLine($"originalBlockHashData: {originalBlockHashData.ToScriptHash()}");
            Console.WriteLine($"updatedBlockHashData: {updatedBlockHashData.ToScriptHash()}");

            Console.WriteLine("\n\n==========================");
            Console.WriteLine("\nBasic commits Signatures verification");
            // Basic tests for understanding signatures and ensuring signatures of commits are correct on tests
            var cmPayloadTemp = GetCommitPayloadModifiedAndSignedCopy(commitPayload, 6, kp_array[6], updatedBlockHashData);
            Crypto.VerifySignature(originalBlockHashData, cm.Signature, mockContext.Object.Validators[0]).Should().BeFalse();
            Crypto.VerifySignature(updatedBlockHashData, cm.Signature, mockContext.Object.Validators[0]).Should().BeFalse();
            Crypto.VerifySignature(originalBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[6]).Should().BeFalse();
            Crypto.VerifySignature(updatedBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[6]).Should().BeTrue();
            Console.WriteLine("\n==========================");

            Console.WriteLine("\n==========================");
            Console.WriteLine("\nCN7 simulation time");
            actorConsensus.Tell(cmPayloadTemp);
            var tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var rmPayload = (ConsensusPayload)tempPayloadToBlockAndWait.Inventory;
            RecoveryMessage rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 2...");
            mockContext.Object.CountCommitted.Should().Be(2);
            Console.WriteLine($"\nAsserting CountFailed is 1...");
            mockContext.Object.CountFailed.Should().Be(1);

            Console.WriteLine("\nCN6 simulation time");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 5, kp_array[5], updatedBlockHashData));
            tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            rmPayload = (ConsensusPayload)tempPayloadToBlockAndWait.Inventory;
            rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 3...");
            mockContext.Object.CountCommitted.Should().Be(3);
            Console.WriteLine($"\nAsserting CountFailed is 0...");
            mockContext.Object.CountFailed.Should().Be(0);

            Console.WriteLine("\nCN5 simulation time");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 4, kp_array[4], updatedBlockHashData));
            tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            Console.WriteLine("\nAsserting CountCommitted is 4...");
            mockContext.Object.CountCommitted.Should().Be(4);

            // =============================================
            // Testing commit with wrong signature not valid
            // It will be invalid signature because we did not change ECPoint
            Console.WriteLine("\nCN4 simulation time. Wrong signature, KeyPair is not known");
            actorConsensus.Tell(GetPayloadAndModifyValidator(commitPayload, 3));
            Console.WriteLine("\nWaiting for recovery due to failed nodes... ");
            var backupOnRecoveryMessageAfterCommit = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            rmPayload = (ConsensusPayload)backupOnRecoveryMessageAfterCommit.Inventory;
            rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 4 (Again)...");
            mockContext.Object.CountCommitted.Should().Be(4);
            Console.WriteLine("\nAsserting recovery message Preparation is 5...");
            rmm.PreparationMessages.Count().Should().Be(5);
            Console.WriteLine("\nAsserting recovery message CommitMessages is 4...");
            rmm.CommitMessages.Count().Should().Be(4);
            // =============================================

            Console.WriteLine($"\nForcing block {mockContext.Object.Block.GetHashData().ToScriptHash()} PrevHash to UInt256.Zero");
            // Another option would be to manipulate Blockchain.Singleton.GetSnapshot().Blocks.GetAndChange
            // We would need to get the PrevHash and change the NextConsensus field
            var oldPrevHash = mockContext.Object.Block.PrevHash;
            mockContext.Object.Block.PrevHash = UInt256.Zero;
            //Payload should also be forced, otherwise OnConsensus will not pass
            commitPayload.PrevHash = UInt256.Zero;
            Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}");
            Console.WriteLine($"\nForcing block VerificationScript to {updatedContract.Script.ToScriptHash()}");
            // The default behavior for BlockBase, when PrevHash = UInt256.Zero, is to use its own Witness
            mockContext.Object.Block.Witness = new Witness { };
            mockContext.Object.Block.Witness.VerificationScript = updatedContract.Script;
            Console.WriteLine($"\nUpdating BlockBase Witness scripthash to: {mockContext.Object.Block.Witness.ScriptHash}");
            Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}");

            Console.WriteLine("\nCN4 simulation time - Final needed signatures");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 3, kp_array[3], mockContext.Object.Block.GetHashData()));

            Console.WriteLine("\nWait for subscriber Local.Node Relay");
            var onBlockRelay = subscriber.ExpectMsg<LocalNode.Relay>();
            Console.WriteLine("\nAsserting time was Block...");
            var utBlock = (Block)onBlockRelay.Inventory;
            Console.WriteLine("\nAsserting CountCommitted is 5...");
            mockContext.Object.CountCommitted.Should().Be(5);

            Console.WriteLine($"\nAsserting block NextConsensus..{utBlock.NextConsensus}");
            utBlock.NextConsensus.Should().Be(updatedContract.ScriptHash);
            Console.WriteLine("\n==========================");

            // =============================================
            Console.WriteLine("\nRecovery simulation...");
            mockContext.Object.CommitPayloads = new ConsensusPayload[mockContext.Object.Validators.Length];
            // avoiding the BlockSent flag
            mockContext.Object.Block.Transactions = null;
            // ensuring same hash as snapshot
            mockContext.Object.Block.PrevHash = oldPrevHash;

            Console.WriteLine("\nAsserting CountCommitted is 0...");
            mockContext.Object.CountCommitted.Should().Be(0);
            Console.WriteLine($"\nAsserting CountFailed is 0...");
            mockContext.Object.CountFailed.Should().Be(0);
            Console.WriteLine($"\nModifying CountFailed and asserting 7...");
            // This will ensure a non-deterministic behavior after last recovery
            mockContext.Object.LastSeenMessage = new int[] { -1, -1, -1, -1, -1, -1, -1 };
            mockContext.Object.CountFailed.Should().Be(7);

            actorConsensus.Tell(rmPayload);

            Console.WriteLine("\nWaiting for RecoveryRequest before final asserts...");
            var onRecoveryRequestAfterRecovery = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var rrPayload = (ConsensusPayload)onRecoveryRequestAfterRecovery.Inventory;
            var rrMessage = (RecoveryRequest)rrPayload.ConsensusMessage;

            // It should be 3 because the commit generated by the default wallet is still invalid
            Console.WriteLine("\nAsserting CountCommitted is 3 (after recovery)...");
            mockContext.Object.CountCommitted.Should().Be(3);
            // =============================================

            // =============================================
            // ============================================================================
            //                      finalize ConsensusService actor
            // ============================================================================
            Console.WriteLine("Returning states.");
            // Updating context.Snapshot with the one that was committed
            Console.WriteLine("mockContext Reset for returning Blockchain.Singleton snapshot to original state.");
            mockContext.Object.Reset(0);
            mockContext.Object.Snapshot.Storages.Delete(CreateStorageKeyForNativeNeo(14));
            mockContext.Object.Snapshot.Commit();

            Console.WriteLine("mockContext Reset.");
            mockContext.Object.Reset(0);
            Console.WriteLine("TimeProvider Reset.");
            TimeProvider.ResetToDefault();

            Console.WriteLine("Finalizing consensus service actor.");
            Sys.Stop(actorConsensus);
            Console.WriteLine("Actor actorConsensus Stopped.\n");
        }
예제 #39
0
        private List <IFCData> SplitIFCFile(string filepath)
        {
            List <IFCData> allIFCRow        = new List <IFCData>();
            StreamReader   reader           = new StreamReader(filepath);
            string         lastString       = "";
            int            countOfStream    = 0; //行數計算
            int            countOfAllString = 0; //字元計算

            if (!reader.EndOfStream)
            {
                string headValue = reader.ReadLine();
            }
            while (!reader.EndOfStream)
            {
                string tmp = lastString + reader.ReadLine();
                //跳過/* */註解行
                if (tmp == "" || (tmp.Substring(0, 2) == "/*" || tmp[0] == '*' || tmp.Substring(tmp.Length - 2) == "*/"))
                {
                    continue;
                }
                if (tmp[tmp.Length - 1] != ';')
                {
                    lastString = tmp;
                    continue;           //跳下一行
                }

                countOfStream++;
                countOfAllString += tmp.Length;
                if (tmp.Contains('=') && tmp.Contains(')') && tmp.Contains('('))                                                 //表示完整的一行ifc資料
                {
                    string ifcHash    = tmp.Substring(0, tmp.IndexOf('=')).Trim();                                               //刪除空白
                    string ifcName    = tmp.Substring(tmp.IndexOf('=') + 1, tmp.IndexOf('(') - tmp.IndexOf('=') - 1).Trim();     //刪除空白
                    string ifcContent = tmp.Substring(tmp.IndexOf('(') + 1, tmp.LastIndexOf(')') - tmp.IndexOf('(') - 1).Trim(); //刪除空白
                    allIFCRow.Add(new IFCData(ifcHash, ifcName, ifcContent));
                }

                if (tmp.Contains("FILE_DESCRIPTION"))
                {
                    string        ifcContent = tmp.Substring(tmp.IndexOf('(') + 1, tmp.LastIndexOf(')') - tmp.IndexOf('(') - 1).Trim(); //刪除空白
                    List <string> prop       = SplitProperty(CutStringWithComma(ifcContent));
                    BsonDocument  file_des   = new BsonDocument();
                    file_des.Add("EntityName", "FILE_DESCRIPTION");
                    if (prop[0] == "()")
                    {
                        file_des.Add("description", "$");
                    }
                    else
                    {
                        file_des.Add("description", GetArray(prop[0]));
                    }
                    file_des.Add("implementation_level", GetValue(prop[1]));
                    Header.Add(new IFCHeader(file_des));
                }

                if (tmp.Contains("FILE_NAME"))
                {
                    string        ifcContent = tmp.Substring(tmp.IndexOf('(') + 1, tmp.LastIndexOf(')') - tmp.IndexOf('(') - 1).Trim(); //刪除空白
                    List <string> prop       = SplitProperty(CutStringWithComma(ifcContent));
                    BsonDocument  file_name  = new BsonDocument
                    {
                        { "EntityName", "FILE_NAME" }
                    };
                    List <string> itemName = new List <string>()
                    {
                        "name", "time_stamp", "author", "organization", "preprocessor_version", "originating_system", "authorization"
                    };
                    for (int i = 0; i < prop.Count(); i++)
                    {
                        if (prop[i] == "")
                        {
                            file_name.Add(itemName[i], "");
                            continue;
                        }
                        if (prop[i].Substring(0, 1) != "(")
                        {
                            file_name.Add(itemName[i], GetValue(prop[i]));
                            continue;
                        }
                        file_name.Add(itemName[i], GetArray(prop[i]));
                    }
                    Header.Add(new IFCHeader(file_name));
                }

                if (tmp.Contains("FILE_SCHEMA"))
                {
                    string       ifcContent  = tmp.Substring(tmp.IndexOf('(') + 1, tmp.LastIndexOf(')') - tmp.IndexOf('(') - 1).Trim(); //刪除空白
                    BsonDocument file_schema = new BsonDocument
                    {
                        { "EntityName", "FILE_SCHEMA" }
                    };
                    file_schema.Add("schema_identifiers", GetArray(ifcContent));
                    Header.Add(new IFCHeader(file_schema));
                    //ResultMessage += "使用" + schemaType + Environment.NewLine;
                }

                lastString = "";        //處理完畢,清空上一行
            }
            return(allIFCRow);
        }
예제 #40
0
 public ActionResult()
 {
     header = new Header();
     status = new GoalStatus();
 }
예제 #41
0
 public FmsFlightplan Build()
 {
     _header = new Header(_planItems.Count - 1);
     return(new FmsFlightplan(_header, _planItems));
 }
예제 #42
0
 /// <summary>
 ///     *
 /// </summary>
 public override void read_allocation(Bitstream stream, Header header, Crc16 crc)
 {
     base.read_allocation(stream, header, crc);
 }
예제 #43
0
        static public BemaniIFS Read(Stream source)
        {
            BemaniIFS result = new BemaniIFS();

            // read header
            Header header = Header.Read(source);

            byte[] propertyPageData = new byte[header.BodyStart - Header.Size];
            source.Read(propertyPageData, 0, propertyPageData.Length);

            // read property page



#if (false)
            List <byte[]>  dataList = new List <byte[]>();
            BinaryReaderEx reader   = new BinaryReaderEx(source);
            BemaniIFS      result   = new BemaniIFS();

            // header length is 0x28 bytes
            reader.ReadInt32S();                          // identifier
            Int16 headerMetaLength = reader.ReadInt16S(); // header meta amount?
            reader.ReadInt16S();                          // bitwise xor 0xFFFF of previously read value
            reader.ReadInt32S();
            reader.ReadInt32S();
            Int32 headerLength = reader.ReadInt32S();
            reader.ReadInt32S();

            for (int i = 1; i < headerMetaLength; i++)
            {
                reader.ReadInt32S();
                reader.ReadInt32S();
            }

            Console.WriteLine("Header length: " + headerLength.ToString());

            // read table A
            Int32 tableALength = reader.ReadInt32S();
            Console.WriteLine("Table A length: " + tableALength.ToString());
            MemoryStream tableAMem = new MemoryStream(reader.ReadBytes(tableALength));

            // read table B
            Int32 tableBLength = reader.ReadInt32S();
            Console.WriteLine("Table B length: " + tableBLength.ToString());
            MemoryStream tableBMem = new MemoryStream(reader.ReadBytes(tableBLength));

            // read padding
            int headerPadding = headerLength - (0x10 + (headerMetaLength * 8) + 4 + tableALength + 4 + tableBLength);
            if (headerPadding > 0)
            {
                reader.ReadBytes(headerPadding);
            }

            // a bit of a hack to get the info we need (it's probably not accurate)
            BinaryReaderEx tableAReader = new BinaryReaderEx(tableAMem);
            BinaryReaderEx tableBReader = new BinaryReaderEx(tableBMem);

            tableAReader.BaseStream.Position = 0x18;
            tableBReader.BaseStream.Position = 0x14;
            int            dataLength = tableBReader.ReadInt32S();
            MemoryStream   dataChunk  = new MemoryStream(reader.ReadBytes(dataLength));
            BinaryReaderEx dataReader = new BinaryReaderEx(dataChunk);

            // process tables
            int  chunkIndex   = 0;
            bool processTable = true;
            while (processTable)
            {
                Console.Write("A:" + Util.ConvertToHexString((int)tableAReader.BaseStream.Position, 8) + " B:" + Util.ConvertToHexString((int)tableBReader.BaseStream.Position, 8) + " ");
                byte chunkType = tableAReader.ReadByte();
                Console.Write("Op:" + Util.ConvertToHexString(chunkType, 2) + "  ");
                switch (chunkType)
                {
                case 0x06:     // directory
                {
                    byte subType = tableAReader.ReadByte();
                    switch (subType)
                    {
                    case 0x03:
                        tableAReader.ReadBytes(3);
                        break;

                    case 0x06:
                        break;

                    default:
                        break;
                    }
                    Int32 fileModified = tableBReader.ReadInt32S();         // modified date?
                    Console.WriteLine("*" + Util.ConvertToHexString(fileModified, 8));
                }
                    continue;

                case 0x1E:     // file
                    tableAReader.ReadByte();
                    {
                        Int32 fileOffset   = tableBReader.ReadInt32S();   // offset
                        Int32 fileLength   = tableBReader.ReadInt32S();   // length
                        Int32 fileModified = tableBReader.ReadInt32S();   // modified date?
                        Console.WriteLine(Util.ConvertToHexString(fileOffset, 8) + ":" + Util.ConvertToHexString(fileLength, 8) + ", *" + Util.ConvertToHexString(fileModified, 8));
                        dataReader.BaseStream.Position = fileOffset;
                        dataList.Add(dataReader.ReadBytes(fileLength));
                    }
                    break;

                case 0x94:     // filename
                    Console.WriteLine("FileID: " + Util.ConvertToHexString(tableAReader.ReadInt32S(), 8));
                    continue;

                case 0xFE:     // end of entry
                    Console.WriteLine("End of entry.");
                    break;

                case 0xFF:     // end of list
                    processTable = false;
                    Console.WriteLine("End of list.");
                    continue;

                default:
                    // for types we don't know, skip the whole line for now
                    Console.WriteLine("UNKNOWN.");
                    break;
                }
                while (chunkType != 0xFE)
                {
                    chunkType = tableAReader.ReadByte();
                }
                chunkIndex++;
            }

            result.files = dataList;
#endif

            return(result);
        }
예제 #44
0
 public GetMapActionFeedback(Header header, GoalStatus status, GetMapFeedback feedback)
 {
     this.header   = header;
     this.status   = status;
     this.feedback = feedback;
 }
예제 #45
0
 /// <summary>
 /// Initialize a new instance of the <see cref="ArcHeaderValidationResult"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="ArcHeaderValidationResult"/>.
 /// </remarks>
 /// <param name="header">The ARC header.</param>
 /// <param name="signature">The signature validation result.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="header"/> is <c>null</c>.
 /// </exception>
 public ArcHeaderValidationResult(Header header, ArcSignatureValidationResult signature) : this(header)
 {
     Signature = signature;
 }
예제 #46
0
        private void Awake()
        {
            m_Rigidbody = GetComponent <Rigidbody>();
            // Set the maximum angular velocity.
            GetComponent <Rigidbody>().maxAngularVelocity = m_MaxAngularVelocity;


            tr = GetComponent <Transform>();

            GetComponent <MeshRenderer>().enabled = false;

            //GameObject ob = GameObject.FindGameObjectWithTag("CONNECT");
            //socket = ob.GetComponent<ConnectServer>().getSocket();



            info = new Info();
            //        info.name = ID;

            //info.name = ob.GetComponent<ConnectServer>().getName();
            info.name = "Tester";
            info.pos  = tr.localPosition;
            info.rot  = tr.localRotation;



            othersID = new LinkedList <string>();

            // set Packet header
            header           = new Header();
            header.start     = "Start";
            header.startSize = (short)header.start.Length;
            header.nameSize  = (short)info.name.Length;
            header.posSize   = (short)Marshal.SizeOf(info.pos);
            header.rotSize   = (short)Marshal.SizeOf(info.rot);

            header.close  = "Close";
            header.ID     = ConnectServer.ID;
            header.single = ConnectServer.SINGLE;
            header.multi  = ConnectServer.MULTI;
            header.rank   = ConnectServer.RANK;
            header.exit   = ConnectServer.EXIT;

            // buffer for sending info
            otherNetBuffer = new byte[BUF_SIZE];

            startBuffer = new byte[header.startSize];
            nameBuffer  = new byte[header.nameSize];
            posBuffer   = new byte[header.posSize];
            rotBuffer   = new byte[header.rotSize];

            //socket.Blocking = false;   // make socket non-blocking mode

            Debug.Log("Awake() is done");


            byte[] sizeArr;  // size byte array

            // total data size to send
            // "Start" + menu sel(char) + totalSize(short) + name length(short) + "name"
            header.totalSize = (short)(header.startSize + 1 + 2 + header.nameSize);

            // start + total Data Size + (short)nameSize + name + (short)posSize + pos + (short)rotSize + rot
            byte[] result = new byte[header.totalSize];

            startBuffer = Encoding.UTF8.GetBytes(header.start);

            // set start string and menu sel size into result buffer
            Buffer.BlockCopy(Encoding.UTF8.GetBytes(header.start), 0, result, 0, header.startSize);
            result[header.startSize] = Convert.ToByte(header.single);
            // set (short)nameSize and nameBuffer into result buffer
            sizeArr = BitConverter.GetBytes(header.nameSize);

            Buffer.BlockCopy(sizeArr, 0, result, header.startSize + 1, 2);
            Buffer.BlockCopy(nameBuffer, 0, result, header.startSize + 1 + 2, nameBuffer.Length);

            //socket.Send(result);



            GameObject pos         = null;
            int        positionNum = (int)UnityEngine.Random.Range(1, 5);

            Debug.Log("PositionNum : " + positionNum);

            switch (positionNum)
            {
            case 1:
                pos = GameObject.FindGameObjectWithTag("POS1");
                break;

            case 2:
                pos = GameObject.FindGameObjectWithTag("POS2");
                break;

            case 3:
                pos = GameObject.FindGameObjectWithTag("POS3");
                break;

            case 4:
                pos = GameObject.FindGameObjectWithTag("POS4");
                break;
            }

            tr.localPosition = pos.GetComponent <Transform>().localPosition;
            mapSeq           = new int[8];
            for (int i = 0; i < 8; i++)
            {
                mapSeq [i] = UnityEngine.Random.Range(0, 9);
            }
        }
 public void Dispose()
 {
     Header?.Dispose();
     ModToggles?.DisposeAll();
 }
예제 #48
0
        async Task <bool> VerifyArcMessageSignatureAsync(FormatOptions options, MimeMessage message, Header arcSignature, Dictionary <string, string> parameters, bool doAsync, CancellationToken cancellationToken)
        {
            DkimCanonicalizationAlgorithm headerAlgorithm, bodyAlgorithm;
            DkimSignatureAlgorithm        signatureAlgorithm;
            AsymmetricKeyParameter        key;
            string d, s, q, bh, b;

            string[] headers;
            int      maxLength;

            ValidateArcMessageSignatureParameters(parameters, out signatureAlgorithm, out headerAlgorithm, out bodyAlgorithm,
                                                  out d, out s, out q, out headers, out bh, out b, out maxLength);

            if (!IsEnabled(signatureAlgorithm))
            {
                return(false);
            }

            if (doAsync)
            {
                key = await PublicKeyLocator.LocatePublicKeyAsync(q, d, s, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                key = PublicKeyLocator.LocatePublicKey(q, d, s, cancellationToken);
            }

            if ((key is RsaKeyParameters rsa) && rsa.Modulus.BitLength < MinimumRsaKeyLength)
            {
                return(false);
            }

            options = options.Clone();
            options.NewLineFormat = NewLineFormat.Dos;

            // first check the body hash (if that's invalid, then the entire signature is invalid)
            var hash = Convert.ToBase64String(message.HashBody(options, signatureAlgorithm, bodyAlgorithm, maxLength));

            if (hash != bh)
            {
                return(false);
            }

            using (var stream = new DkimSignatureStream(CreateVerifyContext(signatureAlgorithm, key))) {
                using (var filtered = new FilteredStream(stream)) {
                    filtered.Add(options.CreateNewLineFilter());

                    WriteHeaders(options, message, headers, headerAlgorithm, filtered);

                    // now include the ARC-Message-Signature header that we are verifying,
                    // but only after removing the "b=" signature value.
                    var header = GetSignedSignatureHeader(arcSignature);

                    switch (headerAlgorithm)
                    {
                    case DkimCanonicalizationAlgorithm.Relaxed:
                        WriteHeaderRelaxed(options, filtered, header, true);
                        break;

                    default:
                        WriteHeaderSimple(options, filtered, header, true);
                        break;
                    }

                    filtered.Flush();
                }

                return(stream.VerifySignature(b));
            }
        }
예제 #49
0
 public void Clear()
 {
     Header.Clear();
     Body.Clear();
 }
예제 #50
0
 public ChildLeftDomainEvent(Guid aggregateRootId, int version,
                             DateTime createdDate, Header header, Guid childId)
     : base(aggregateRootId, version, createdDate, header)
 {
     ChildId = childId;
 }
예제 #51
0
파일: Response.cs 프로젝트: saintym/GGM.Web
 public Response SetHeader(string key, string value)
 {
     Header.Add(key, value);
     return(this);
 }
예제 #52
0
 public void Parse(Header header, byte[] data)
 {
 }
예제 #53
0
 public override void Visit(Header head)
 {
     Console.WriteLine($"DIS: Head: {head.Date}");
 }
        // --------------------------------------------------------------
        #region SAVE
        // --------------------------------------------------------------

        /// <summary>
        /// Saves the uop file
        /// </summary>
        /// <param name="fileName">Name of the uop file (Destination).</param>
        public void Save(string fileName)
        {
            // make sure the file name is viable
            if (Path.GetFileName(fileName).IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                throw new Exception(string.Format("Invalid file name {0}!", Path.GetFileName(fileName)));
            }

            // update the location address inside the file of all blocks and files
            UpdateOffsets();

            // store the file name as a temporary file name to use
            string tempFile = fileName;

            // does the file specified already exist?
            bool exists = File.Exists(fileName);

            // if the file already exist, we create a temporary one with .temp extension (removed later)
            if (exists)
            {
                tempFile = fileName + ".temp";
            }

            // if we have the fileinfo, then this is a file we open before (not created from scratch)
            if (FileInfo != null)
            {
                // start writing the file
                using (FileStream source = new FileStream(FileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (FileStream destination = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                    {
                        // open the reader (for the original file), and writer (for the file we are saving)
                        using (BinaryReader reader = new BinaryReader(source))
                            using (BinaryWriter writer = new BinaryWriter(destination))
                            {
                                // save the uop header
                                Header.Save(writer);

                                // save all blocks and files
                                foreach (MythicPackageBlock b in Blocks)
                                {
                                    b.Save(writer, reader);
                                }
                            }
                    }
            }
            else // new file created from scratch
            {
                // create a new file
                using (FileStream destination = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                    using (BinaryWriter writer = new BinaryWriter(destination))
                    {
                        // save the header
                        Header.Save(writer);

                        // save all blocks and files
                        foreach (MythicPackageBlock b in Blocks)
                        {
                            b.Save(writer);
                        }
                    }
            }

            // if we are replacing an existing file, we also create a backup of the original one
            if (exists)
            {
                File.Replace(tempFile, fileName, string.Format("{0}.backup", FileInfo.FullName), true);
            }

            // update the file info
            FileInfo = new FileInfo(fileName);

            // remove the modified flag
            Modified = false;

            // remove the "is new" flag
            Added = false;
        }
예제 #55
0
        public CustomViewSequence(IStreamReader reader)
            : base(reader)
        {
            // CUSTOMVIEW = UserSViewBegin *Selection [HorizontalPageBreaks] [VerticalPageBreaks] [Header]
            //    [Footer] [HCenter] [VCenter] [LeftMargin] [RightMargin] [TopMargin] [BottomMargin]
            //    [Pls] [Setup] [PrintSize] [HeaderFooter] [AUTOFILTER] UserSViewEnd


            // NOTE: UserSViewBegin and UserSViewEnd seem to be optional to!


            // UserSViewBegin
            if (BiffRecord.GetNextRecordType(reader) == RecordType.UserSViewBegin)
            {
                this.UserSViewBegin = (UserSViewBegin)BiffRecord.ReadRecord(reader);
            }

            // *Selection
            this.Selections = new List <Selection>();
            while (BiffRecord.GetNextRecordType(reader) == RecordType.Selection)
            {
                this.Selections.Add((Selection)BiffRecord.ReadRecord(reader));
            }

            // [HorizontalPageBreaks]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.HorizontalPageBreaks)
            {
                this.HorizontalPageBreaks = (HorizontalPageBreaks)BiffRecord.ReadRecord(reader);
            }

            // [VerticalPageBreaks]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.VerticalPageBreaks)
            {
                this.VerticalPageBreaks = (VerticalPageBreaks)BiffRecord.ReadRecord(reader);
            }

            // [Header]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.Header)
            {
                this.Header = (Header)BiffRecord.ReadRecord(reader);
            }

            // [Footer]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.Footer)
            {
                this.Footer = (Footer)BiffRecord.ReadRecord(reader);
            }

            // [HCenter]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.HCenter)
            {
                this.HCenter = (HCenter)BiffRecord.ReadRecord(reader);
            }

            // [VCenter]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.VCenter)
            {
                this.VCenter = (VCenter)BiffRecord.ReadRecord(reader);
            }

            // [LeftMargin]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.LeftMargin)
            {
                this.LeftMargin = (LeftMargin)BiffRecord.ReadRecord(reader);
            }

            // [RightMargin]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.RightMargin)
            {
                this.RightMargin = (RightMargin)BiffRecord.ReadRecord(reader);
            }

            // [TopMargin]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.TopMargin)
            {
                this.TopMargin = (TopMargin)BiffRecord.ReadRecord(reader);
            }

            // [BottomMargin]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.BottomMargin)
            {
                this.BottomMargin = (BottomMargin)BiffRecord.ReadRecord(reader);
            }

            // [Pls]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.Pls)
            {
                this.Pls = (Pls)BiffRecord.ReadRecord(reader);
            }

            // [Setup]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.Setup)
            {
                this.Setup = (Setup)BiffRecord.ReadRecord(reader);
            }

            // [PrintSize]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.PrintSize)
            {
                this.PrintSize = (PrintSize)BiffRecord.ReadRecord(reader);
            }

            // [HeaderFooter]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.HeaderFooter)
            {
                this.HeaderFooter = (HeaderFooter)BiffRecord.ReadRecord(reader);
            }

            // [AUTOFILTER]
            if (BiffRecord.GetNextRecordType(reader) == RecordType.AutoFilterInfo)
            {
                this.AutoFilterSequence = new AutoFilterSequence(reader);
            }

            // UserSViewEnd
            if (BiffRecord.GetNextRecordType(reader) == RecordType.UserSViewEnd)
            {
                this.UserSViewEnd = (UserSViewEnd)BiffRecord.ReadRecord(reader);
            }
        }
예제 #56
0
파일: RpcServer.cs 프로젝트: ys8090/NEU
        protected virtual JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getaccountstate":
            {
                UInt160      script_hash = Wallet.ToScriptHash(_params[0].AsString());
                AccountState account     = Blockchain.Default.GetAccountState(script_hash) ?? new AccountState(script_hash);
                return(account.ToJson());
            }

            case "getassetstate":
            {
                UInt256    asset_id = UInt256.Parse(_params[0].AsString());
                AssetState asset    = Blockchain.Default.GetAssetState(asset_id);
                return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset"));
            }

            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Default.Height - block.Index + 1;
                    UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetBlockHash(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getblocksysfee":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetSysFeeAmount(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getconnectioncount":
                return(LocalNode.RemoteNodeCount);

            case "getcontractstate":
            {
                UInt160       script_hash = UInt160.Parse(_params[0].AsString());
                ContractState contract    = Blockchain.Default.GetContract(script_hash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                int         height  = -1;
                Transaction tx      = LocalNode.GetTransaction(hash);
                if (tx == null)
                {
                    tx = Blockchain.Default.GetTransaction(hash, out height);
                }
                if (tx == null)
                {
                    throw new RpcException(-100, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json = tx.ToJson();
                    if (height >= 0)
                    {
                        Header header = Blockchain.Default.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Default.Height - header.Index + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "getstorage":
            {
                UInt160     script_hash = UInt160.Parse(_params[0].AsString());
                byte[]      key         = _params[1].AsString().HexToBytes();
                StorageItem item        = Blockchain.Default.GetStorageItem(new StorageKey
                    {
                        ScriptHash = script_hash,
                        Key        = key
                    }) ?? new StorageItem();
                return(item.Value?.ToHexString());
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, parameters).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                byte[]              script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, operation, args).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(GetInvokeResult(script));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(LocalNode.Relay(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(LocalNode.Relay(block));
            }

            case "validateaddress":
            {
                JObject json = new JObject();
                UInt160 scriptHash;
                try
                {
                    scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                }
                catch
                {
                    scriptHash = null;
                }
                json["address"] = _params[0];
                json["isvalid"] = scriptHash != null;
                return(json);
            }

            case "getpeers":
            {
                JObject json = new JObject();

                {
                    JArray unconnectedPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetUnconnectedPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        unconnectedPeers.Add(peerJson);
                    }
                    json["unconnected"] = unconnectedPeers;
                }

                {
                    JArray badPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetBadPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        badPeers.Add(peerJson);
                    }
                    json["bad"] = badPeers;
                }

                {
                    JArray connectedPeers = new JArray();
                    foreach (RemoteNode node in LocalNode.GetRemoteNodes())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = node.RemoteEndpoint.Address.ToString();
                        peerJson["port"]    = node.ListenerEndpoint?.Port ?? 0;
                        connectedPeers.Add(peerJson);
                    }
                    json["connected"] = connectedPeers;
                }

                return(json);
            }

            case "getversion":
            {
                JObject json = new JObject();
                json["port"]      = LocalNode.Port;
                json["nonce"]     = LocalNode.Nonce;
                json["useragent"] = LocalNode.UserAgent;
                return(json);
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
예제 #57
0
 private bool NewModifiedFilesLoaderCanExecute() => Header.Equals(Properties.Resources.LoadNewModifiedFiles);
예제 #58
0
        private void Initialize()
        {
            DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle3 = new DataGridViewCellStyle();

            lpanel           = new XShadowPanel();
            linner_panel     = new Panel();
            chk_notactive    = new MCheckBox();
            txt_colours_name = new LookupBox();
            lbl_colours_name = new XLabel();
            btn_close        = new CloseButton();
            lbl_header       = new Header();
            btn_print        = new OfficeButton();
            btn_delete       = new OfficeButton();
            btn_edit         = new OfficeButton();
            btn_new          = new OfficeButton();
            btn_refresh      = new OfficeButton();
            listgrid         = new ListGridView();
            btn_search       = new OfficeButton();
            lpanel.SuspendLayout();
            linner_panel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(listgrid)).BeginInit();
            SuspendLayout();

            lpanel.Name      = "lpanel";
            lpanel.Dock      = DockStyle.Fill;
            lpanel.Size      = XSize.FPanel;
            lpanel.Location  = XLayout.FPanel;
            lpanel.BackColor = XTheme.FPanel;
            lpanel.Controls.Add(linner_panel);
            lpanel.Controls.Add(btn_close);
            lpanel.Controls.Add(lbl_header);

            linner_panel.Anchor    = XAnchor.LTRB;
            linner_panel.BackColor = XTheme.LInnerpanel;
            linner_panel.Controls.Add(btn_search);
            linner_panel.Controls.Add(chk_notactive);
            linner_panel.Controls.Add(txt_colours_name);
            linner_panel.Controls.Add(lbl_colours_name);
            linner_panel.Controls.Add(btn_print);
            linner_panel.Controls.Add(btn_delete);
            linner_panel.Controls.Add(btn_edit);
            linner_panel.Controls.Add(btn_new);
            linner_panel.Controls.Add(btn_refresh);
            linner_panel.Controls.Add(listgrid);
            linner_panel.Location = XLayout.LInnerPanel;
            linner_panel.Name     = "linner_panel";
            linner_panel.Size     = XSize.LInnerPanel;

            btn_close.Click += Btn_close_Click;

            lbl_header.Text = "Colours";

            chk_notactive.Anchor          = XAnchor.TR;
            chk_notactive.AutoSize        = true;
            chk_notactive.Font            = XFont.TxtFont;
            chk_notactive.Location        = XLayout.ListFirstBtn;
            chk_notactive.MouseLocation   = new Point(-1, -1);
            chk_notactive.Name            = "chk_notactive";
            chk_notactive.Size            = new Size(92, 30);
            chk_notactive.TabIndex        = 4;
            chk_notactive.Text            = "Not Active";
            chk_notactive.CheckedChanged += new System.EventHandler(Chk_notactive_CheckedChanged);

            txt_colours_name.Font              = XFont.TxtFont;
            txt_colours_name.ForeColor         = XFontColor.TxtFontColor;
            txt_colours_name.BackColor         = XTheme.TxtBackcolor;
            txt_colours_name.Name              = "txt_colours_name";
            txt_colours_name.ReadOnlyBackColor = XTheme.TxtReadonlyBackcolor;
            txt_colours_name.Size              = XSize.TwoText;
            txt_colours_name.Anchor            = XAnchor.LTR;
            txt_colours_name.Location          = XLayout.FirstText;
            txt_colours_name.TabIndex          = 5;

            lbl_colours_name.Font      = XFont.Font_10B;
            lbl_colours_name.Name      = "lbl_colours_name";
            lbl_colours_name.Text      = "Colours";
            lbl_colours_name.TextAlign = ContentAlignment.MiddleCenter;
            lbl_colours_name.ForeColor = XFontColor.Lbl_ForeColor;
            lbl_colours_name.Size      = XSize.OneLabel;
            lbl_colours_name.Location  = XLayout.FirstLabel;

            btn_search.Font     = XFont.BtnFont;
            btn_search.Location = new Point(txt_colours_name.Right + 10, txt_colours_name.Top);
            btn_search.Size     = new Size(75, 26);
            btn_search.TabIndex = 1;
            btn_search.Name     = "btn_search";
            btn_search.Text     = "&Search";
            btn_search.Themes   = XTheme.YellowBtn;
            btn_search.Anchor   = XAnchor.TR;
            btn_search.Click   += Btn_search_Click;

            #region [btn Properties]

            btn_refresh.Font     = XFont.BtnFont;
            btn_refresh.Location = XLayout.BtnLocation(chk_notactive.Location);
            btn_refresh.Size     = XSize.BtnOne;
            btn_refresh.TabIndex = 1;
            btn_refresh.Name     = "btn_refresh";
            btn_refresh.Text     = "&Refresh";
            btn_refresh.Themes   = XTheme.BlueBtn;
            btn_refresh.Anchor   = XAnchor.TR;
            btn_refresh.Click   += Btn_refresh_Click;

            btn_new.Font     = XFont.BtnFont;
            btn_new.Location = XLayout.BtnLocation(btn_refresh.Location);
            btn_new.Size     = XSize.BtnOne;
            btn_new.TabIndex = XTab.Index(btn_refresh.TabIndex);
            btn_new.Name     = "btn_new";
            btn_new.Text     = "&New";
            btn_new.Themes   = XTheme.BlueBtn;
            btn_new.Anchor   = XAnchor.TR;
            btn_new.Click   += Btn_new_Click;

            btn_edit.Font     = XFont.BtnFont;
            btn_edit.Location = XLayout.BtnLocation(btn_new.Location);
            btn_edit.Size     = XSize.BtnOne;
            btn_edit.TabIndex = XTab.Index(btn_new.TabIndex);
            btn_edit.Name     = "btn_edit";
            btn_edit.Text     = "&Edit";
            btn_edit.Themes   = XTheme.BlueBtn;
            btn_edit.Anchor   = XAnchor.TR;
            btn_edit.Click   += Btn_edit_Click;

            btn_delete.Font     = XFont.BtnFont;
            btn_delete.Location = XLayout.BtnLocation(btn_edit.Location);
            btn_delete.Size     = XSize.BtnOne;
            btn_delete.TabIndex = XTab.Index(btn_edit.TabIndex);
            btn_delete.Name     = "btn_delete";
            btn_delete.Text     = "&Delete";
            btn_delete.Themes   = XTheme.BlueBtn;
            btn_delete.Anchor   = XAnchor.TR;
            btn_delete.Click   += Btn_delete_Click;

            btn_print.Font     = XFont.BtnFont;
            btn_print.Location = XLayout.BtnLocation(btn_delete.Location);
            btn_print.Size     = XSize.BtnOne;
            btn_print.TabIndex = XTab.Index(btn_delete.TabIndex);
            btn_print.Name     = "btn_print";
            btn_print.Text     = "&Print";
            btn_print.Themes   = XTheme.BlueBtn;
            btn_print.Anchor   = XAnchor.TR;
            btn_print.Click   += Btn_print_Click;

            #endregion [btn Properties]

            #region [List Grid]

            listgrid.AllowUserToAddRows               = false;
            listgrid.AllowUserToDeleteRows            = false;
            listgrid.AllowUserToOrderColumns          = true;
            listgrid.AllowUserToResizeRows            = false;
            dataGridViewCellStyle1.BackColor          = Color.White;
            dataGridViewCellStyle1.Font               = XFont.Font_10R;
            dataGridViewCellStyle1.ForeColor          = Color.Black;
            dataGridViewCellStyle1.SelectionBackColor = Color.FromArgb(255, 255, 204);
            dataGridViewCellStyle1.SelectionForeColor = Color.FromArgb(252, 0, 11);
            dataGridViewCellStyle1.WrapMode           = DataGridViewTriState.True;
            listgrid.AlternatingRowsDefaultCellStyle  = dataGridViewCellStyle1;
            listgrid.Anchor = XAnchor.LTRB;
            listgrid.AutoSizeColumnsMode              = DataGridViewAutoSizeColumnsMode.Fill;
            listgrid.BackgroundColor                  = Color.White;
            listgrid.BorderStyle                      = BorderStyle.Fixed3D;
            listgrid.CellBorderStyle                  = DataGridViewCellBorderStyle.Custom;
            listgrid.ColumnHeadersBorderStyle         = DataGridViewHeaderBorderStyle.Custom;
            dataGridViewCellStyle2.Alignment          = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle2.BackColor          = Color.FromArgb(132, 192, 96);
            dataGridViewCellStyle2.Font               = new Font("Microsoft Sans Serif", 11.25F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle2.ForeColor          = Color.White;
            dataGridViewCellStyle2.Padding            = new Padding(3);
            dataGridViewCellStyle2.SelectionBackColor = SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = SystemColors.HighlightText;
            dataGridViewCellStyle2.WrapMode           = DataGridViewTriState.True;
            listgrid.ColumnHeadersDefaultCellStyle    = dataGridViewCellStyle2;
            listgrid.ColumnHeadersHeightSizeMode      = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            listgrid.Cursor = Cursors.Default;
            dataGridViewCellStyle3.Alignment          = DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle3.BackColor          = Color.White;
            dataGridViewCellStyle3.Font               = XFont.Font_10R;
            dataGridViewCellStyle3.ForeColor          = Color.Black;
            dataGridViewCellStyle3.SelectionBackColor = Color.FromArgb(255, 255, 204);
            dataGridViewCellStyle3.SelectionForeColor = Color.FromArgb(252, 0, 11);
            dataGridViewCellStyle3.WrapMode           = DataGridViewTriState.False;
            listgrid.DefaultCellStyle          = dataGridViewCellStyle3;
            listgrid.EnableHeadersVisualStyles = false;
            listgrid.GridColor         = Color.SeaGreen;
            listgrid.MultiSelect       = false;
            listgrid.Name              = "listgrid";
            listgrid.ReadOnly          = true;
            listgrid.RowHeadersVisible = false;
            listgrid.SelectionMode     = DataGridViewSelectionMode.FullRowSelect;
            listgrid.Location          = XLayout.ListView;
            listgrid.Size              = XSize.ListView;
            listgrid.StandardTab       = true;
            listgrid.TabIndex          = 0;

            #endregion [List Grid]

            AutoScaleDimensions = new SizeF(6F, 13F);
            AutoScaleMode       = AutoScaleMode.Font;
            Controls.Add(lpanel);
            Name = "LColours";
            Size = new Size(1000, 600);
            lpanel.ResumeLayout(false);
            linner_panel.ResumeLayout(false);
            linner_panel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(listgrid)).EndInit();
            ResumeLayout(false);
        }
예제 #59
0
 private bool AllPaksLoaderCanExecute() => Header.Equals(Properties.Resources.LoadAll);
예제 #60
0
 public override string[] Authenticate(UserAgent ua, Header header, SIPStack sipStack)
 {
     throw new NotImplementedException();
 }