Exemple #1
0
        public void TestGetBotWrestler()
        {
            var owner     = PhantasmaKeys.Generate();
            var simulator = new NexusSimulator(owner, 1234);
            var nexus     = simulator.Nexus;
            var api       = new NexusAPI(nexus);


            var callScript    = ScriptUtils.BeginScript().CallContract("nacho", "GetWrestler", new object[] { -1 }).EndScript();
            var apiResult     = (ScriptResult)api.InvokeRawScript("main", Base16.Encode(callScript));
            var bytes         = Base16.Decode(apiResult.results[0]);
            var objResult     = Serialization.Unserialize <VMObject>(bytes);
            var nachoWrestler = objResult.ToStruct <NachoWrestler>();
        }
        public void BlockSignerCannotAddHashAfterSignedTest(Ksi ksi)
        {
            BlockSigner blockSigner = new BlockSigner(GetHttpKsiService());

            blockSigner.Add(new DataHash(Base16.Decode("01580192B0D06E48884432DFFC26A67C6C685BEAF0252B9DD2A0B4B05D1724C5F2")));
            blockSigner.Sign();

            BlockSigningException ex = Assert.Throws <BlockSigningException>(delegate
            {
                blockSigner.Add(new DataHash(Base16.Decode("01580192B0D06E48884432DFFC26A67C6C685BEAF0252B9DD2A0B4B05D1724C5F2")));
            });

            Assert.That(ex.Message, Does.StartWith("Signing process is started. Cannot add new items."), "Unexpected exception message");
        }
        private VerificationResult SignHash(Ksi ksi)
        {
            DataHash      hash      = new DataHash(HashAlgorithm.Sha2256, Base16.Decode("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"));
            IKsiSignature signature = ksi.Sign(hash);

            VerificationContext verificationContext = new VerificationContext(signature)
            {
                DocumentHash     = hash,
                PublicationsFile = ksi.GetPublicationsFile()
            };
            KeyBasedVerificationPolicy policy = new KeyBasedVerificationPolicy();

            return(policy.Verify(verificationContext));
        }
Exemple #4
0
        public void EndSignWithoutSigningServiceProtocol()
        {
            IKsiService serviceBegin = GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)),
                                                           1584727637);
            IAsyncResult asyncResult = serviceBegin.BeginSign(new DataHash(Base16.Decode("0111A700B0C8066C47ECBA05ED37BC14DCADB238552D86C659342D1D7E87B8772D")), null, null);
            KsiService   serviceEnd  = new KsiService(null, null, null, null, null, null);

            KsiServiceException ex = Assert.Throws <KsiServiceException>(delegate
            {
                serviceEnd.EndSign(asyncResult);
            });

            Assert.That(ex.Message.StartsWith("Signing service protocol is missing from service"), "Unexpected exception message: " + ex.Message);
        }
Exemple #5
0
        public override byte[] Serialize()
        {
            var bytes            = new List <byte>();
            var versionBytes     = new byte[4];
            var hashBytes        = new byte[32];
            var timestampBytes   = new byte[8];
            var locktimeBytes    = new byte[8];
            var expiredTimeBytes = new byte[8];
            var totalInputBytes  = new byte[4];
            var totalOutputBytes = new byte[4];

            versionBytes     = BitConverter.GetBytes(Version);
            hashBytes        = Base16.Decode(Hash);
            timestampBytes   = BitConverter.GetBytes(Timestamp);
            locktimeBytes    = BitConverter.GetBytes(Locktime);
            expiredTimeBytes = BitConverter.GetBytes(Locktime);
            totalInputBytes  = BitConverter.GetBytes(InputCount);
            totalOutputBytes = BitConverter.GetBytes(OutputCount);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(versionBytes);
                Array.Reverse(timestampBytes);
                Array.Reverse(locktimeBytes);
                Array.Reverse(expiredTimeBytes);
                Array.Reverse(totalInputBytes);
                Array.Reverse(totalOutputBytes);
            }

            bytes.AddRange(versionBytes);
            bytes.AddRange(hashBytes);
            bytes.AddRange(timestampBytes);
            bytes.AddRange(locktimeBytes);
            bytes.AddRange(expiredTimeBytes);
            bytes.AddRange(totalInputBytes);

            foreach (var inputMsg in this.Inputs)
            {
                bytes.AddRange(inputMsg.Serialize());
            }

            bytes.AddRange(totalOutputBytes);

            foreach (var outputMsg in this.Outputs)
            {
                bytes.AddRange(outputMsg.Serialize());
            }

            return(bytes.ToArray());
        }
Exemple #6
0
        public void TestSignatureDataOk()
        {
            SignatureData signatureData = GetSignatureDataFromFile(Resources.SignatureData_Ok);

            Assert.AreEqual(4, signatureData.Count, "Invalid amount of child TLV objects");

            CollectionAssert.AreEqual(signatureData.GetCertificateId(), new byte[] { 0xc2, 0x46, 0xb1, 0x39 }, "Certificate Id should be equal");
            CollectionAssert.AreEqual(signatureData.GetSignatureValue(),
                                      Base16.Decode(
                                          "98D9A4D14722BB2C22425AC9112FBF6A2491B7051AD0CBFD8153E669BFCC6CDF20EEC80F7FCC7236985A4F83871DD6E245470BCA323A3902035B78764DDC4C6EB42416A3A7D7E5CEF6ED6AE8FADA668413758CF7DE1E9565EDF646170286D0F43CA30491DD3407B53DEEDDCBD2620057AB6580E3D3E938AE44EABAF3282357EEBB7B2325616755A1F20B3A78DE2F636DE10F7CCD75B6C5BB80EFEBA216F9BF1A302DCB93B9D3E3E9754620E6D8EC8672C5329CBBB00A9A4617242950D68B8A55CBA77E69DECDD49DD96F69FAA6BFBB0EF48A913F5F26AFA01FB08192D62123FC644BA2978CAF147229BD5702663494983A40ED77AA5016EAABC1FE8456DC17D4"),
                                      "Signature value should be correct");
            Assert.AreEqual(signatureData.SignatureType, "1.2.840.113549.1.1.11", "Signature type should be correct");
            Assert.AreEqual("https://www.guardtime.com", signatureData.CertificateRepositoryUri, "Unexpected certificate repository uri.");
        }
Exemple #7
0
        public string GetPayloadHash()
        {
            var hashsBytes = this.Transactions.Select(tx => Base16.Decode(tx.Hash)).ToList();

            this.Transactions.ForEach(x => { LogHelper.Warn(x.Hash); });
            LogHelper.Warn("\r\n");

            var bytes = MerkleTree.Hash(hashsBytes);

            return(Base16.Encode(
                       HashHelper.Hash(
                           bytes.ToArray()
                           )));
        }
        public void VerifyWithExtendingAndPublicationsFile1()
        {
            VerificationContext context = new VerificationContext()
            {
                Signature          = TestUtil.GetSignature(Resources.KsiSignature_Ok),
                DocumentHash       = new DataHash(Base16.Decode("0111A700B0C8066C47ECBA05ED37BC14DCADB238552D86C659342D1D7E87B8772D")),
                PublicationsFile   = TestUtil.GetPublicationsFile(),
                KsiService         = GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_ExtendResponsePdu_RequestId_1043101455)), 1043101455),
                IsExtendingAllowed = true
            };

            VerificationResult result = Policy.Verify(context);

            CheckResult(result, VerificationResultCode.Ok, null, 1, typeof(PublicationBasedVerificationPolicy));
        }
        public void SignInvalidPduFormatTest()
        {
            KsiService service = GetHttpKsiService(PduVersion.v2);

            // if new aggregator then no exception
            try
            {
                service.Sign(new DataHash(HashAlgorithm.Sha2256, Base16.Decode("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")));
            }
            catch (Exception ex)
            {
                Assert.That(ex.Message.StartsWith("Received PDU v1 response to PDU v2 request. Configure the SDK to use PDU v1 format for the given Aggregator"),
                            "Unexpected exception message: " + ex.Message);
            }
        }
        public void HttpSignSm3HashTest(Ksi ksi)
        {
            DataHash      hash      = new DataHash(HashAlgorithm.Sm3, Base16.Decode("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"));
            IKsiSignature signature = ksi.Sign(hash);

            VerificationContext verificationContext = new VerificationContext(signature)
            {
                DocumentHash     = hash,
                PublicationsFile = ksi.GetPublicationsFile()
            };
            KeyBasedVerificationPolicy policy             = new KeyBasedVerificationPolicy();
            VerificationResult         verificationResult = policy.Verify(verificationContext);

            Assert.AreEqual(VerificationResultCode.Ok, verificationResult.ResultCode, "Signature should verify with key based policy");
        }
        public void HASignWithSingleServiceTest()
        {
            IKsiService haService =
                new HAKsiService(
                    new List <IKsiService>()
            {
                GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1584727637)
            },
                    null, null);

            DataHash      inputHash = new DataHash(Base16.Decode("019f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"));
            IKsiSignature signature = haService.Sign(inputHash);

            Assert.AreEqual(inputHash, signature.InputHash, "Unexpected signature input hash.");
        }
Exemple #12
0
        public void NoTrustAnchorsTest()
        {
            string encodedSignedBytes = "3029020456C0D6A904210187EBC5594827DC2B3F87918DC7AFE8A528E844D65918CD525984D65981C2C79A";

            string encodedSignature =
                "308006092A864886F70D010702A0803080020101310F300D06096086480165030402010500308006092A864886F70D0107010000A080308201A730820110A003020102021000BAA25764984826073CEF1BEEAA7B6F300D06092A864886F70D01010B050030123110300E06035504030C0774657374696E67301E170D3136303130313030303030305A170D3236303130313030303030305A30123110300E06035504030C0774657374696E6730819F300D06092A864886F70D010101050003818D0030818902818100E66DC137E4F856EADB0D47C280BED297D70191287919FD6EBF1195DF5E821EA867F861E551A37762E3CAEBB32B1DE7E0143529F1678A87BCE2C8E5D5185F25EEC3ABC7E295EEBC64EFE4BC8ADB412A99D3F9125D30C45F887632DE4B95AA169B79D1A6FD4E735255632341ED41B5BFA828975A4F1501B02C2277CA15BD470DAB0203010001300D06092A864886F70D01010B05000381810057B6B2BED11E7DC06E7A7AD77D1922C33FE8BDEBDC48B20A9444F807AA6017890E10B21C6FA5C4795AF32B9A45E9C560580115C8DF09E4ACA8E69C2757F9CAAB3007B548A567DBE8FB228EFF4F3D7995B3B2F008F3D62BECB3D2E80827A17B42B9C8C8C0280565868D572BBE7E4916E4888D8F503BEC1561CF4A1495C43C642000003182013B30820137020101302630123110300E06035504030C0774657374696E67021000BAA25764984826073CEF1BEEAA7B6F300D06096086480165030402010500A069301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3137313130393133333235335A302F06092A864886F70D01090431220420F083925226E0D857E5320AB3544F754B2FA74B364268BC755987C518083D2940300D06092A864886F70D01010105000481809BC20BF93B9190207D585A4638AFBB3BCDB740E6030F1B56A922E7E1B25024F3DCE9F2B63B693281E5056D7BA4553814B1FF8E4A38955DAF0FA9B26D468B29D8137E1EE0FAF3A9D8FD1E5EBFF0560C51684B93735E3D1A2313484AF62EC2FD39BA7BA2781818BB38BFE2D33C2C23F74AB4F43824D4209E3DA211F1DB990DCD0D000000000000";

            ICryptoSignatureVerifier verifier = KsiProvider.CreatePkcs7CryptoSignatureVerifier();
            ArgumentException        ex       = Assert.Throws <ArgumentException>(delegate
            {
                verifier.Verify(Base16.Decode(encodedSignedBytes), Base16.Decode(encodedSignature), null);
            });

            Assert.That(ex.Message.StartsWith("No trust anchors given."), "Unexpected exception message: " + ex.Message);
        }
        public void CryptoSignatureVerificationDataNullTest()
        {
            string encodedSignedBytes = "3029020456C0D6A904210187EBC5594827DC2B3F87918DC7AFE8A528E844D65918CD525984D65981C2C79A";

            string encodedSignature =
                "4B08D8DE7AFB3390FD6F315877EBEB55DA4F259E57BC6A282EA00373D43FC32ECC462500CACD353DFE4916EBFD58B89D72F204668223177263DF1963934326EAABE70FDB70C9238C35C3BBAC842FE9BF205C5AD0AE5A691CC26306AAB20129FA5F9C8711E4D0ED3118FFE32B6C97572A8D6700A3471B90023A60FF71C9558E0C";

            ICryptoSignatureVerifier verifier = KsiProvider.CreateRsaCryptoSignatureVerifier("SHA256");
            ArgumentNullException    ex       = Assert.Throws <ArgumentNullException>(delegate
            {
                verifier.Verify(Base16.Decode(encodedSignedBytes), Base16.Decode(encodedSignature), null);
            });

            Assert.That(ex.ParamName == "data", "Unexpected exception message: " + ex.Message);
        }
Exemple #14
0
        /// <inheritdoc />
        public override void ReadData(PresentationReader reader)
        {
            KeyTag        = reader.ReadUInt16();
            Algorithm     = (SecurityAlgorithm)reader.ReadByte();
            HashAlgorithm = (DigestType)reader.ReadByte();

            // Whitespace is allowed within the hexadecimal text.
            var sb = new StringBuilder();

            while (!reader.IsEndOfLine())
            {
                sb.Append(reader.ReadString());
            }
            Digest = Base16.Decode(sb.ToString()).ToArray();
        }
Exemple #15
0
        public override byte[] Serialize()
        {
            var data       = new List <byte>();
            var indexBytes = BitConverter.GetBytes(Index);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(indexBytes);
            }

            data.AddRange(Base16.Decode(Id));
            data.AddRange(indexBytes);

            return(data.ToArray());
        }
        public void Base16Tests()
        {
            var bytes = new byte[Address.PublicKeyLength];
            var rnd   = new Random();

            rnd.NextBytes(bytes);

            var base16 = Base16.Encode(bytes);

            Assert.IsTrue(base16.Length == bytes.Length * 2);

            var output = Base16.Decode(base16);

            Assert.IsTrue(output.Length == bytes.Length);
            Assert.IsTrue(output.SequenceEqual(bytes));
        }
        public void SignByteArrayTest(Ksi ksi)
        {
            byte[]        data      = Encoding.UTF8.GetBytes("This is my document");
            IKsiSignature signature = ksi.Sign(data);

            VerificationContext verificationContext = new VerificationContext(signature)
            {
                DocumentHash = new DataHash(HashAlgorithm.Sha2256,
                                            Base16.Decode("D439459856BEF5ED25772646F73A70A841FC078D3CBBC24AB7F47C464683768D")),
                PublicationsFile = ksi.GetPublicationsFile()
            };
            KeyBasedVerificationPolicy policy             = new KeyBasedVerificationPolicy();
            VerificationResult         verificationResult = policy.Verify(verificationContext);

            Assert.AreEqual(VerificationResultCode.Ok, verificationResult.ResultCode, "Signature should verify with key based policy");
        }
        public void CreateFromAggregationResponsePayloadTest()
        {
            KsiSignatureFactory signatureFactory = new KsiSignatureFactory();

            AggregationResponsePayload aggregationResponsePayload =
                new AggregationResponsePayload(new RawTag(0x2, false, false,
                                                          Base16.Decode(
                                                              "0108AFE5A27DEF7743A1040005094E6F206572726F72008801006702045A6EF58C03010B03012503010D03010B03010305210196BFBF3488DC0485775A5A2B0F9870100009630F4783AAAC73C0D72E2C3343B4060101072A04287E01016105616E6F6E0062116B736967772D74657374757365723A3100630064070563E79A43A003880100AB02045A6EF58C03010B03012503010D03010B0521013C7A08C4C6F62C5E42FEA933EC5B7EB59FA522A1664BA4560E8DAF0FBD1A810E060101072404227E0201016103475400620B414C65322D312D323A360063010A64070563E79A44C9A0072601010102210155ECF6F1FDD26FE579D3D81A6ADF93987C6DFA02D3504F313B81DD2FB95F51C40823022101C3D0F6018F79DCA5D2FEC42EF89ECC805FD288BFDD56AEDDDBE0AFB77A488D6F880100A302045A6EF58C03010B03012503010D0521011B30143F49B30B251614B2BDB98C4606E6B92F17BD967B27C2F75161C54FE100060101072204207E02010161034754006209415365322D303A310063010164070563E79A4AC5400823022101FC9E9054C97CBCE13F65CB0B733A2A227B5CE5D23C0980C3B284B27BE5ABE63407230221010F87C8F8E53E3DA5840B545AC90219617A4FEAB9F76E7DFF336D7A14814F4C70880100E802045A6EF58C03010B0301250521016F946BC6CA37CBAB00A5DE378FD7C191ADC257C7E2E67EA2F933555F9C15292E0601010720041E7E02010161034754006207414E65323A300063011364070563E79A4AFAE508230221014C7D57F20776DC3CE07742B66B6527E5286D7CA9B03762C71DC935BB6888D62D0723022101E69A7B97BF8DA43685BA8AE8375BE287FDDB548F0F6820C26B35669365C2B4C608230221019F16DB50A02F8D92AA4599841F6316707B1A662A39518A489588504B554D1B7608230221010E288C96225D2179DEF90F28BE4FE62BF2C3AD28EFB8A8F600DCCF8F6A9676F7880100A402045A6EF58C03010B0521017F0D9AE236EBE7B56FEACA0B6AC53033A6993E437E495F6CE50DA46C1096E4E10601010726010144022101D474205F20C49D3BA8D144293E6D4FD2087260D25539328035E97BF792E8F6BD072601012C0221016D6210425AAB8257DE2F6E2FDC36DBDB9E7E7C976906579EAE68C8F440C891540823022101488F69C2C30F862FDCBC1BE79BB87C81D1E47BA621BE9B88076E1AA8D2D734BB880202A501045A6EF58C02045A6EF58C0521017657A2D6FD236E05B6FB45F189B5845FED615138D3782E5D4D1DA375D66E200708210142B20235775AAEF836F21B5A12D16535A401076FC0DD40DB1C5D6C62F3349B24082101B11A0A6D1B5415EE802A8C1F0E8ADC413D52283EBD91F801F1D16DAD3AE2642D082101ADEE14D2FA3F684727AE6802CD421C76BC965AEBFA2E2010691853E968643211082101E4C451E413358603EFE08066EEDA908FB6ECB609CE0DAE3A3F835B894AA3371F082101BEE31E35A4C47ED8A44BC46DEBAD7A14A259B8CA515E80A7493FB57AD862808F0821017724A0A2A8EB1F36C89F53C4BA5884AAFD10A8DD68673E6BCFF8C7A6B969D461082101D9D4620A29065A193015C1E15A15F392E133F0A2FA19464F3C06F1E8E320D074082101582522AEB80C092A3019ADA6B1AE0ED63D0BFB46CBFC75BB5ABC9E6E17F93F6308210141C699CC60229704B2B748ADCCBCD6760483607D3CEC93F3D84FA1E5B9ED3F600821018E886DD92F0A028B9680F971E189E47C474808B5CA020B8237ADCAF84A107335082101ED4F4C983F9425003ED5F3139ACECFA58BBC3356E6ED42D0EF32EFBBB0BBE27E082101468742111669F6E9C3FF6D6EF588D4CA2E83CB019BF8294058D18D6803386FF808210146DD0425199FC10F742F8FF8FC1A6EA2F9607AEC95EF0C9345EBB619E9EA634E082101CEC119E2F9EEDA49B7CABA0BD16F39FC68B9763260C4EAFBBFCE8757A8C129C108210148DEA5B1AFDBDA4B016A138B7F52F763E6826FCB935CEA9D8B8FF1AAA6B5A53B082101EBC3AB1D86641581130AC3C7077B71B67BBA4C915530E9FE49B98769FC8DCAEB082101496FC0120D854E7534B992AB32EC3045B20D4BEE1BFBE4564FD092CEAFA08B72082101BB44FD36A5F3CDEE7B5C6DF3A6098A09E353335B6029F1477502588A7E37BE0088050151302902045A6EF58C0421012EEE26A5F6FF57C8F24A0CF0546C107E6285FA0FE5962B0691EC5FDF5AF15D0C800B01220116312E322E3834302E3131333534392E312E312E3131008002010034BA0861EC8545A9ADC70F08FA82D8D16D678554320025EC2255C92996D6F19FF41F3F1FFC0D5B14152A6AD6EED9C017E460E9A9E97CE73BAB5B43672388DDDEDE524A134DB9A54770373993F706ECBBFBF249CEFB16A37F7593D4B54B4ECD84499F23D81CA6D8BF21E414F96EB7FE8CFD7863506937266EF8948E5B823E63F2025F0CFBA62D6144E37C756B23BF5DE5559BA0F358EC5E311232CC02E5D73832AEB7BBFFCE41390B4FA051051DFFB5F96710D348A97138ED97A5ACFD23CF78ED560EC509880B57CEA57580824BF849B163665C958DEB8FD3F715A7346BC89FDE9F250F67D107654945D42E62EFF452793ACFC4DC8AF9F77BC8C3A31968570B4E03048DEA135F")));
            IKsiSignature signature = signatureFactory.Create(aggregationResponsePayload,
                                                              new DataHash(Base16.Decode("0196BFBF3488DC0485775A5A2B0F9870100009630F4783AAAC73C0D72E2C3343B4")), 1);

            Assert.AreEqual(5, signature.GetAggregationHashChains().Count, "Unexpected aggregation hash chain count.");
            Assert.AreEqual(1, signature.GetAggregationHashChains()[0].GetChainLinks()[0].LevelCorrection, "Unexpected first aggregation hash chain first link level correction.");
            Assert.IsNotNull(signature.CalendarHashChain, "Unexpected calendar hash chain: null");
            Assert.IsNotNull(signature.CalendarAuthenticationRecord, "Unexpected calendar auth record: null");
        }
Exemple #19
0
        private object RouteConvertAddressETHHEX(HTTPRequest request)
        {
            var ethKey  = request.GetVariable("ethKey");
            var context = InitContext(request);

            EthereumKey ethKeys;

            var bytes = Base16.Decode(ethKey);
            var temp  = new PhantasmaKeys(bytes);

            ethKeys = EthereumKey.FromWIF(temp.ToWIF());

            var result = $"{ethKeys.ToString()}";

            return(result);
        }
        public void VerifyWithTimeTest()
        {
            string encodedSignedBytes = "3029020456C0D6A904210187EBC5594827DC2B3F87918DC7AFE8A528E844D65918CD525984D65981C2C79A";
            // valid from 2016.01.01 - 2026.01.01
            string encodedCert =
                "308201A730820110A00302010202100096577055BF04943952E580CD2DF257300D06092A864886F70D01010B050030123110300E06035504030C0774657374696E67301E170D3136303130313030303030305A170D3236303130313030303030305A30123110300E06035504030C0774657374696E6730819F300D06092A864886F70D010101050003818D0030818902818100E66DC137E4F856EADB0D47C280BED297D70191287919FD6EBF1195DF5E821EA867F861E551A37762E3CAEBB32B1DE7E0143529F1678A87BCE2C8E5D5185F25EEC3ABC7E295EEBC64EFE4BC8ADB412A99D3F9125D30C45F887632DE4B95AA169B79D1A6FD4E735255632341ED41B5BFA828975A4F1501B02C2277CA15BD470DAB0203010001300D06092A864886F70D01010B050003818100A7668A7341CC50F71045D80419AFC648FAA869DCDAD248C7BCA171EBDF54EA4FFE7D339B5A227402A2E23B554BF0E1570FFB6D0F47F3EE155984CCD3A3676C66A780560CE0A3B75B0F6D83D25FBE0B19B7491114529F208470060BFEAB1F91CA59940D53FCFA277B6E3BAE0057AD7CD2C9549B9CCF4FBF942E37B13ACC430302";

            string encodedSignature =
                "4B08D8DE7AFB3390FD6F315877EBEB55DA4F259E57BC6A282EA00373D43FC32ECC462500CACD353DFE4916EBFD58B89D72F204668223177263DF1963934326EAABE70FDB70C9238C35C3BBAC842FE9BF205C5AD0AE5A691CC26306AAB20129FA5F9C8711E4D0ED3118FFE32B6C97572A8D6700A3471B90023A60FF71C9558E0C";

            ICryptoSignatureVerifier verifier = KsiProvider.CreateRsaCryptoSignatureVerifier("SHA256");

            verifier.Verify(Base16.Decode(encodedSignedBytes),
                            Base16.Decode(encodedSignature),
                            new CryptoSignatureVerificationData(Base16.Decode(encodedCert), Util.ConvertDateTimeToUnixTime(new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc))));
        }
        public void SignedBytesNullTest()
        {
            string encodedCert =
                "308201A730820110A00302010202100096577055BF04943952E580CD2DF257300D06092A864886F70D01010B050030123110300E06035504030C0774657374696E67301E170D3136303130313030303030305A170D3236303130313030303030305A30123110300E06035504030C0774657374696E6730819F300D06092A864886F70D010101050003818D0030818902818100E66DC137E4F856EADB0D47C280BED297D70191287919FD6EBF1195DF5E821EA867F861E551A37762E3CAEBB32B1DE7E0143529F1678A87BCE2C8E5D5185F25EEC3ABC7E295EEBC64EFE4BC8ADB412A99D3F9125D30C45F887632DE4B95AA169B79D1A6FD4E735255632341ED41B5BFA828975A4F1501B02C2277CA15BD470DAB0203010001300D06092A864886F70D01010B050003818100A7668A7341CC50F71045D80419AFC648FAA869DCDAD248C7BCA171EBDF54EA4FFE7D339B5A227402A2E23B554BF0E1570FFB6D0F47F3EE155984CCD3A3676C66A780560CE0A3B75B0F6D83D25FBE0B19B7491114529F208470060BFEAB1F91CA59940D53FCFA277B6E3BAE0057AD7CD2C9549B9CCF4FBF942E37B13ACC430302";

            string encodedSignature =
                "4B08D8DE7AFB3390FD6F315877EBEB55DA4F259E57BC6A282EA00373D43FC32ECC462500CACD353DFE4916EBFD58B89D72F204668223177263DF1963934326EAABE70FDB70C9238C35C3BBAC842FE9BF205C5AD0AE5A691CC26306AAB20129FA5F9C8711E4D0ED3118FFE32B6C97572A8D6700A3471B90023A60FF71C9558E0C";

            ICryptoSignatureVerifier verifier = KsiProvider.CreateRsaCryptoSignatureVerifier("SHA256");
            ArgumentNullException    ex       = Assert.Throws <ArgumentNullException>(delegate
            {
                verifier.Verify(null, Base16.Decode(encodedSignature), new CryptoSignatureVerificationData(Base16.Decode(encodedCert)));
            });

            Assert.That(ex.ParamName == "signedBytes", "Unexpected exception message: " + ex.Message);
        }
Exemple #22
0
        public byte[] Serialize()
        {
            List <byte> bytes = new List <byte>();

            byte[] versionBytes     = new byte[4];
            byte[] hashBytes        = new byte[32];
            byte[] timestampBytes   = new byte[8];
            byte[] locktimeBytes    = new byte[8];
            byte[] totalInputBytes  = new byte[4];
            byte[] totalOutputBytes = new byte[4];

            versionBytes     = BitConverter.GetBytes(Version);
            hashBytes        = Base16.Decode(Hash);
            timestampBytes   = BitConverter.GetBytes(Timestamp);
            locktimeBytes    = BitConverter.GetBytes(Locktime);
            totalInputBytes  = BitConverter.GetBytes(InputCount);
            totalOutputBytes = BitConverter.GetBytes(OutputCount);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(versionBytes);
                Array.Reverse(timestampBytes);
                Array.Reverse(locktimeBytes);
                Array.Reverse(totalInputBytes);
                Array.Reverse(totalOutputBytes);
            }

            bytes.AddRange(versionBytes);
            bytes.AddRange(hashBytes);
            bytes.AddRange(timestampBytes);
            bytes.AddRange(locktimeBytes);
            bytes.AddRange(totalInputBytes);

            foreach (BlockTransactionInputsOM inputMsg in Inputs)
            {
                bytes.AddRange(inputMsg.Serialize());
            }

            bytes.AddRange(totalOutputBytes);

            foreach (BlockTransactionOutputsOM outputMsg in Outputs)
            {
                bytes.AddRange(outputMsg.Serialize());
            }

            return(bytes.ToArray());
        }
        /// <summary>
        ///   Read hex encoded RDATA.
        /// </summary>
        /// <returns>
        ///   A byte array containing the RDATA.
        /// </returns>
        /// <remarks>
        ///   See <see href="https://tools.ietf.org/html/rfc3597#section-5"/> for all
        ///   the details.
        /// </remarks>
        public byte[] ReadResourceData()
        {
            var leadin = ReadToken();

            if (leadin != "#")
            {
                throw new FormatException($"Expected RDATA leadin '\\#', not '{leadin}'.");
            }
            var length = ReadUInt32();

            if (length == 0)
            {
                return(new byte[0]);
            }

            // Get the hex string.
            var sb = new StringBuilder();

            while (sb.Length < length * 2)
            {
                var word = ReadToken();
                if (word.Length == 0)
                {
                    break;
                }
                if (word.Length % 2 != 0)
                {
                    throw new FormatException($"The hex word ('{word}') must have an even number of digits.");
                }
                sb.Append(word);
            }
            if (sb.Length != length * 2)
            {
                throw new FormatException("Wrong number of RDATA hex digits.");
            }

            // Convert hex string into byte array.
            try
            {
                return(Base16.Decode(sb.ToString()));
            }
            catch (InvalidOperationException e)
            {
                throw new FormatException(e.Message);
            }
        }
Exemple #24
0
        public static byte[] GetMiningWorkResult(BlockMsg block)
        {
            var listBytes = new List <Byte>();

            listBytes.AddRange(Base16.Decode(block.Header.PayloadHash));
            listBytes.AddRange(BitConverter.GetBytes(block.Header.Height));
            var         genHash         = Sha3Helper.Hash(listBytes.ToArray());
            var         scoopNumber     = POC.GetScoopNumber(block.Header.PayloadHash, block.Header.Height);
            var         scoopData       = POC.CalculateScoopData(block.Header.GeneratorId, block.Header.Nonce, scoopNumber);
            List <byte> targetByteLists = new List <byte>();

            targetByteLists.AddRange(scoopData);
            targetByteLists.AddRange(genHash);
            var baseTarget = Sha3Helper.Hash(targetByteLists.ToArray());

            return(baseTarget);
        }
        public IRpcMethodResult SubmitBlock(string blockData)
        {
            try
            {
                var bytes = Base16.Decode(blockData);
                var block = new BlockMsg();
                int index = 0;
                try
                {
                    block.Deserialize(bytes, ref index);
                }
                catch
                {
                    throw new CommonException(ErrorCode.Service.BlockChain.BLOCK_DESERIALIZE_FAILED);
                }

                var blockComponent = new BlockComponent();
                var blockInDB      = blockComponent.GetBlockMsgByHeight(block.Header.Height);
                if (blockInDB == null)
                {
                    var result = blockComponent.SaveBlockIntoDB(block);
                    if (result)
                    {
                        Startup.P2PBroadcastBlockHeaderAction(block.Header);
                    }
                    else
                    {
                        throw new CommonException(ErrorCode.Service.BlockChain.BLOCK_SAVE_FAILED);
                    }
                }
                else
                {
                    throw new CommonException(ErrorCode.Service.BlockChain.SAME_HEIGHT_BLOCK_HAS_BEEN_GENERATED);
                }

                return(Ok());
            }
            catch (CommonException ce)
            {
                return(Error(ce.ErrorCode, ce.Message, ce));
            }
            catch (Exception ex)
            {
                return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
            }
        }
Exemple #26
0
    /// <summary>
    /// Check if the creation of a new token on Phantasma Blockchain was successful
    /// </summary>
    public IEnumerator CheckTokenCreation(EBLOCKCHAIN_OPERATION operation, string result)
    {
        CanvasManager.Instance.ShowOperationPopup("Checking token creation...", true);

        yield return(CheckOperation(operation, result,
                                    (tx) =>
        {
            foreach (var evt in tx.events)
            {
                EventKind eKind;
                if (Enum.TryParse(evt.kind, out eKind))
                {
                    if (eKind == EventKind.TokenCreate)
                    {
                        var bytes = Base16.Decode(evt.data);
                        var tokenSymbol = Serialization.Unserialize <string>(bytes);

                        Debug.Log(evt.kind + " - " + tokenSymbol);

                        if (tokenSymbol.Equals(TOKEN_SYMBOL))
                        {
                            IsTokenCreated = true;
                            IsTokenOwner = true;

                            CheckTokens(() =>
                            {
                                CanvasManager.Instance.adminMenu.SetContent();
                            });

                            CanvasManager.Instance.ShowResultPopup(EOPERATION_RESULT.SUCCESS, "New token created with success.");
                        }

                        return;
                    }
                }
            }

            CanvasManager.Instance.HideOperationPopup();
            CanvasManager.Instance.ShowResultPopup(EOPERATION_RESULT.FAIL, "Something failed on the connection to the blockchain. Please try again.");
        },
                                    ((errorType, errorMessage) =>
        {
            CanvasManager.Instance.HideOperationPopup();
            CanvasManager.Instance.ShowResultPopup(EOPERATION_RESULT.FAIL, errorType + " - " + errorMessage);
        })));
    }
        public void AggregationRequestPayloadTest()
        {
            AggregationRequestPayload tag = new AggregationRequestPayload(new TlvTagBuilder(Constants.AggregationRequestPayload.TagType, false, false,
                                                                                            new ITlvTag[]
            {
                new IntegerTag(Constants.PduPayload.RequestIdTagType, false, false, 1),
                new ImprintTag(Constants.AggregationRequestPayload.RequestHashTagType, false, false,
                               new DataHash(HashAlgorithm.Sha2256,
                                            new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 })),
                new IntegerTag(Constants.AggregationRequestPayload.RequestLevelTagType, false, false, 2),
            }).BuildTag());

            Assert.AreEqual(1, tag.RequestId, "Unexpected request id");
            Assert.AreEqual(2, tag.RequestLevel, "Unexpected request level");
            Assert.AreEqual(new DataHash(HashAlgorithm.Sha2256, Base16.Decode("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20")), tag.RequestHash,
                            "Unexpected request hash");
        }
        public void PublicationDataContentTest()
        {
            IKsiSignature signature = TestUtil.GetSignature(Resources.KsiSignature_Ok_Extended);
            PublicationRecordInSignature publicationRecord = signature.PublicationRecord;

            string   code = publicationRecord.PublicationData.GetPublicationString();
            DateTime date = publicationRecord.PublicationData.GetPublicationDate();

            Assert.AreEqual("AAAAAA-CWYEKQ-AAIYPA-UJ4GRT-HXMFBE-OTB4AB-XH3PT3-KNIKGV-PYCJXU-HL2TN4-RG6SCC-3ZGSBM", code, "Publication string is invalid.");
            Assert.AreEqual(new DateTime(2016, 2, 15), date, "Publication date is invalid.");
            Assert.AreEqual(new DataHash(Base16.Decode("011878289E1A333DD85091D30F001B9F6F9ED4D428D57E049BD0EBD4DBC89BD210")), publicationRecord.PublicationData.PublicationHash,
                            "Unexpected publication hash.");
            Assert.AreEqual(3, publicationRecord.PublicationReferences.Count, "Invalid publication reference count.");
            Assert.AreEqual("Financial Times, ISSN: 0307-1766, 2016-02-17", publicationRecord.PublicationReferences[0], "Invalid first publication reference.");
            Assert.AreEqual("Äripäev, ISSN: 1406-2585, 17.02.2016", publicationRecord.PublicationReferences[1], "Invalid second publication reference.");
            Assert.AreEqual("https://twitter.com/Guardtime/status/699919571084558336", publicationRecord.PublicationReferences[2], "Invalid third publication reference.");
        }
 public IRpcMethodResult VerifyMessage(string publicKey, string signature, string message)
 {
     try
     {
         ECDsa dsa    = ECDsa.ImportPublicKey(Base16.Decode(publicKey));
         var   result = dsa.VerifyData(Encoding.UTF8.GetBytes(message), Base16.Decode(signature));
         return(Ok(result));
     }
     catch (CommonException ce)
     {
         return(Error(ce.ErrorCode, ce.Message, ce));
     }
     catch (Exception ex)
     {
         return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
     }
 }
        protected void OnWalletRelayCommand(string[] args)
        {
            var script = Base16.Decode(args[0]);
            var expire = Timestamp.Now + TimeSpan.FromMinutes(2);
            var tx     = new Phantasma.Blockchain.Transaction(_cli.Nexus.Name, _cli.Nexus.RootChain.Name, script, expire, Spook.TxIdentifier);

            tx.Sign(WalletModule.Keys);

            if (_cli.Mempool != null)
            {
                _cli.Mempool.Submit(tx);
            }
            else
            {
                throw new CommandException("no mempool available");
            }
        }