Esempio n. 1
1
    /// <summary>
    /// Set value of property and add comment. It will create new property if absent.
    /// </summary>
    /// <param name="key">Name of property</param>
    /// <param name="value">New value</param>
    /// <param name="comment">Comment for property</param>
    public void set(string key, string value, string comment)
    {
        KeyPair outKeyPair=null;

        if (mKeysMap.TryGetValue(key, out outKeyPair))
        {
            outKeyPair.value   = value;
            outKeyPair.comment = comment;

            return;
        }

        outKeyPair=new KeyPair(key, value, comment);

        mKeysMap.Add(key, outKeyPair);
        mKeysList.Add(outKeyPair);
    }
Esempio n. 2
1
 public abstract void StoreKeyValuePair(KeyPair keypair);
Esempio n. 3
0
        /// <summary>
        /// Remix a Diffie-Hellman private key pair with another public key pair to form a shared secret
        /// </summary>
        /// <param name="mixture">Private key pair with another public key pair</param>
        /// <returns>Shared secret</returns>
        public string Remix(KeyPair mixture)
        {
            var agreement = AgreementUtilities.GetBasicAgreement("DiffieHellman");
            agreement.Init(new DHPrivateKeyParameters(new BigInteger(mixture.Private), new DHParameters(_common.P, _common.G, null)));

            return agreement.CalculateAgreement(new DHPublicKeyParameters(new BigInteger(mixture.Public), new DHParameters(_common.P, _common.G, null))).ToString();
        }
Esempio n. 4
0
 public static KeyPair CreateInstance(AWSModel.KeyPair awsKeyPair)
 {
     KeyPair keyPair = new KeyPair();
     keyPair.KeyFingerprint = awsKeyPair.KeyFingerprint;
     keyPair.KeyMaterial = awsKeyPair.KeyMaterial;
     keyPair.KeyName = awsKeyPair.KeyName;
     return keyPair;
 }
Esempio n. 5
0
 public OAuthLogin(KeyPair applicationInfo,
     Uri urlGetRequestToken,
     Uri urlAuthorizeToken,
     Uri urlGetAccessToken)
 {
     ApplicationInfo = applicationInfo;
     UrlGetRequestToken = urlGetRequestToken;
     UrlAuthorizeToken = urlAuthorizeToken;
     UrlGetAccessToken = urlGetAccessToken;
 }
Esempio n. 6
0
        /// <summary>
        /// Bundles edges of the graph.
        /// </summary>
        /// 
        /// <param name="graph">
        /// Graph whose edges should be bundled
        /// </param>
        /// 
        /// <param name="rectangle">
        /// Rectangle in which the graph is laid out.
        /// Control points of bundled edges should not fall outside of this rectangle.
        /// </param>
        public void BundleAllEdges(IGraph graph, Rectangle rectangle)
        {
            this.rectangle = rectangle;

            if (graph.Directedness != GraphDirectedness.Undirected)
                directed = true;
            else directed = false;

            AddDataForAllEdges(graph.Edges);

            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            FindCompatibleEdges(edgeGroupData);

            //sw.Stop();


            DivideAllEdges(subdivisionPoints);

            //sw = new Stopwatch();
            //sw.Start();

            for (int i = 0; i < iterations; i++)
                MoveControlPoints(edgeGroupData);

            //prevents oscillating movements
            for (int i = 0; i < 5; i++)
            {
                cooldown *= 0.5f;
                MoveControlPoints(edgeGroupData);
            }

            //sw.Stop();

            cooldown = 1f;

            if (straightening > 0)
                StraightenEdgesInternally(edgeGroupData, straightening);

            foreach (IEdge e in graph.Edges)
            {
                if (!e.IsSelfLoop)
                {
                    KeyPair key = new KeyPair(e.Vertices[0].ID, e.Vertices[1].ID);
                    e.SetValue(ReservedMetadataKeys.PerEdgeIntermediateCurvePoints, edgeGroupData[key].controlPoints);
                }
            }
        }
Esempio n. 7
0
 public static KeyPair Generate(int length)
 {
     KeyPair pair = new KeyPair();
     int byteLength = length / 8;
     BigInteger p = new BigInteger(Random(byteLength / 2));
     BigInteger q = new BigInteger(Random(byteLength / 2));
     pair.N = (q - 1) * (p - 1);
     pair.E = 3;
     while (BigInteger.GreatestCommonDivisor(pair.E, pair.N) > 1)
     {
         pair.E += 2;
     }
     pair.D = 12;
     return pair;
 }
Esempio n. 8
0
            public void should_decrypt()
            {
                LicenseActivationPayload payload = new LicenseActivationPayload();
                payload.LicenseKey = "999-999999-9999";
                payload.ServiceLicense = new ServiceLicense(servicesService.CreateTestClientLicense(service));

                string serializedPayload = objectSerializationProvider.Serialize(payload);
                string encryptedData = asymmetricEncryptionProvider.EncryptPrivate(serializedPayload, servicesService.CreateTestClientLicense(service).ServicesKeys);

                KeyPair kp = new KeyPair();
                kp.PrivateKey = service.OutboundKeyPair.PrivateKey;
                kp.PublicKey = service.InboundKeyPair.PublicKey;

                string unencryptedData = asymmetricEncryptionProvider.DecryptPublic(encryptedData, kp);

                Assert.IsNotNull(unencryptedData);
                Assert.AreEqual(serializedPayload, unencryptedData);
            }
Esempio n. 9
0
        private static async Task Test()
        {
            KeyPair orkutAppInfo = new KeyPair(
                key: "176102147108.apps.googleusercontent.com",
                secret: "glE2FgAVRf_VEl9etaOCfuDK");

            KeyPair twitterAppInfo = new KeyPair(
                key: "vS4UjhTai41mgJteeC3eQ",
                secret: "I2ATAsnTxrFC9UpTlRDuYKareUznje35vnoZXcayq4");

            try
            {
                using (var authenticator = new WinFormsAuthenticator())
                {
                    var orkutClient = await OrkutClient.Login(orkutAppInfo, authenticator);
                    Console.WriteLine("Orkut: " + orkutClient.OAuthClient.AccessToken);
                    //var user = await orkutClient.GetCurrentUser();

                    var friends = await orkutClient.GetFriends(UserIds.Me, 0, 20);

                    //Console.WriteLine("Orkut: {0} {1}", user.Name.GivenName, user.Name.FamilyName);

                    //var twitterClient = await TwitterClient.Login(twitterAppInfo, authenticator);
                    //Console.WriteLine("Twitter: " + twitterClient.OAuthClient.AccessToken);
                }
            }
            catch (Jv.Web.OAuth.WebException ex)
            {
                Console.WriteLine(((object)ex.ResponseData).ToJson());
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex.InnerException.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Sets a new key pair for this peer.
 /// </summary>
 /// <param name="keyPair">The new private and public key for this peer.</param>
 /// <returns>This class.</returns>
 public PeerBean SetKeyPair(KeyPair keyPair)
 {
     KeyPair = keyPair;
     return(this);
 }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(KeyPair.FromAccountId(reader.Value.ToString()));
 }
Esempio n. 12
0
        public void TestFolders()
        {
            byte[] seed = { 0, 0, 0, 0 };
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(seed);

            Console.WriteLine("preparing the authority block");

            KeyPair root = new KeyPair(rng);

            BiscuitBuilder builder = Biscuit.Token.Biscuit.Builder(rng, root);

            builder.AddRight("/folder1/file1", "read");
            builder.AddRight("/folder1/file1", "write");
            builder.AddRight("/folder1/file2", "read");
            builder.AddRight("/folder1/file2", "write");
            builder.AddRight("/folder2/file3", "read");

            Console.WriteLine(builder.Build());
            Biscuit.Token.Biscuit b = builder.Build().Right;

            Console.WriteLine(b.Print());

            BlockBuilder block2 = b.CreateBlock();

            block2.ResourcePrefix("/folder1/");
            block2.CheckRight("read");

            KeyPair keypair2 = new KeyPair(rng);

            Biscuit.Token.Biscuit b2 = b.Attenuate(rng, keypair2, block2.Build()).Right;

            Verifier v1 = b2.Verify(root.ToPublicKey()).Right;

            v1.AddResource("/folder1/file1");
            v1.AddOperation("read");
            v1.Allow();
            Either <Error, long> res = v1.Verify();

            Assert.IsTrue(res.IsRight);

            Verifier v2 = b2.Verify(root.ToPublicKey()).Right;

            v2.AddResource("/folder2/file3");
            v2.AddOperation("read");
            v2.Allow();
            res = v2.Verify();
            Assert.IsTrue(res.IsLeft);

            Verifier v3 = b2.Verify(root.ToPublicKey()).Right;

            v3.AddResource("/folder2/file1");
            v3.AddOperation("write");
            v3.Allow();
            res = v3.Verify();

            Error e = res.Left;

            Assert.IsTrue(res.IsLeft);

            Console.WriteLine(v3.PrintWorld());
            foreach (FailedCheck f in e.FailedCheck().Get())
            {
                Console.WriteLine(f.ToString());
            }
            Assert.AreEqual(
                new FailedLogic(new LogicError.FailedChecks(Arrays.AsList <FailedCheck>(
                                                                new FailedCheck.FailedBlock(1, 0, "check if resource(#ambient, $resource), $resource.starts_with(\"/folder1/\")"),
                                                                new FailedCheck.FailedBlock(1, 1, "check if resource(#ambient, $resource), operation(#ambient, #read), right(#authority, $resource, #read)")
                                                                ))),
                e);
        }
Esempio n. 13
0
        public void TestSealedTokens()
        {
            byte[] seed = { 0, 0, 0, 0 };
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(seed);

            Console.WriteLine("preparing the authority block");

            KeyPair root = new KeyPair(rng);

            SymbolTable  symbols           = Biscuit.Token.Biscuit.DefaultSymbolTable();
            BlockBuilder authority_builder = new BlockBuilder(0, symbols);

            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file1"), Utils.Symbol("read"))));
            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file2"), Utils.Symbol("read"))));
            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file1"), Utils.Symbol("write"))));

            Biscuit.Token.Biscuit b = Biscuit.Token.Biscuit.Make(rng, root, Biscuit.Token.Biscuit.DefaultSymbolTable(), authority_builder.Build()).Right;

            Console.WriteLine(b.Print());

            Console.WriteLine("serializing the first token");

            byte[] data = b.Serialize().Right;

            Console.Write("data len: ");
            Console.WriteLine(data.Length);
            //Console.WriteLine(hex(data));

            Console.WriteLine("deserializing the first token");
            Biscuit.Token.Biscuit deser = Biscuit.Token.Biscuit.FromBytes(data).Right;

            Console.WriteLine(deser.Print());

            // SECOND BLOCK
            Console.WriteLine("preparing the second block");

            KeyPair keypair2 = new KeyPair(rng);

            BlockBuilder builder = deser.CreateBlock();

            builder.AddCheck(Utils.Check(Utils.Rule(
                                             "caveat1",
                                             Arrays.AsList(Utils.Var("resource")),
                                             Arrays.AsList(
                                                 Utils.Pred("resource", Arrays.AsList(Utils.Symbol("ambient"), Utils.Var("resource"))),
                                                 Utils.Pred("operation", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("read"))),
                                                 Utils.Pred("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Var("resource"), Utils.Symbol("read")))
                                                 )
                                             )));

            Biscuit.Token.Biscuit b2 = deser.Attenuate(rng, keypair2, builder.Build()).Right;

            Console.WriteLine(b2.Print());

            Console.WriteLine("sealing the second token");

            byte[] testkey = Encoding.UTF8.GetBytes("testkey");

            var sealedd = b2.Seal(testkey).Right;

            Console.Write("sealed data len: ");
            Console.WriteLine(sealedd.Length);

            Console.WriteLine("deserializing the sealed token with an invalid key");
            Error e = Biscuit.Token.Biscuit.FromSealed(sealedd, Encoding.UTF8.GetBytes("not this key")).Left;

            Console.WriteLine(e);
            Assert.AreEqual(new SealedSignature(), e);

            Console.WriteLine("deserializing the sealed token with a valid key");
            Biscuit.Token.Biscuit deser2 = Biscuit.Token.Biscuit.FromSealed(sealedd, Encoding.UTF8.GetBytes("testkey")).Right;
            Console.WriteLine(deser2.Print());

            Console.WriteLine("trying to attenuate to a sealed token");
            _ = deser2.CreateBlock();
            _ = deser2.Attenuate(rng, keypair2, builder.Build()).Left;

            Verifier v = deser2.VerifySealed().Right;

            Console.WriteLine(v.PrintWorld());
        }
Esempio n. 14
0
        /// <summary>
        /// Collects data from the specified edge
        /// </summary>
        /// 
        /// <param name="e">
        /// Edge to collect data from
        /// </param>
        private void AddEdgeData(IEdge e)
        {
            EdgeGroupData ed;
            KeyPair key = new KeyPair(e.Vertices[0].ID, e.Vertices[1].ID);

            edgeGroupData.TryGetValue(key, out ed);

            if (ed == null)
            {
                PointF p1 = e.Vertices[0].Location;
                PointF p2 = e.Vertices[1].Location;
                ed = new EdgeGroupData();
                ed.v1 = p1;
                ed.v2 = p2;
                ed.id = key;
                PointF mid = VectorTools.MidPoint(p1, p2);
                ed.middle = mid;
                ed.length = VectorTools.Distance(p1, p2);
                ed.compatibleGroups = new Dictionary<KeyPair, GroupPairData>();
                //ed.edges = new HashSet<int>();
                ed.edgeCount = 0;
                edgeGroupData.Add(key, ed);
            }
            //ed.edges.Add(e.ID);
            ed.edgeCount++;
        }
Esempio n. 15
0
        public void TestSendReceive()
        {
            var test = CreateAPI();

            var simulator = test.simulator;
            var owner     = test.owner;
            var sender    = KeyPair.Generate();
            var receiver  = KeyPair.Generate();
            var node      = KeyPair.FromWIF(nodeWIF);
            var nexus     = simulator.Nexus;
            var api       = test.api;

            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000);
            simulator.EndBlock();

            var desiredChannelBalance = RelayFeePerMessage * 10;

            TopUpChannel(simulator, sender, desiredChannelBalance);

            var channelBalance = nexus.RootChain.InvokeContract("relay", "GetBalance", sender.Address).AsNumber();

            Assert.IsTrue(channelBalance == desiredChannelBalance);

            var messageCount = 5;
            var messages     = new RelayMessage[messageCount];

            var random = new Random();

            for (int i = 0; i < messageCount; i++)
            {
                var script = new byte[100];
                random.NextBytes(script);

                var message = new RelayMessage
                {
                    nexus     = nexus.Name,
                    index     = i,
                    receiver  = receiver.Address, //node.Address,
                    script    = script,
                    sender    = sender.Address,
                    timestamp = Timestamp.Now
                };
                messages[i] = message;

                var    receipt       = RelayReceipt.FromMessage(message, sender);
                string serializedHex = Base16.Encode(receipt.Serialize());

                api.RelaySend(serializedHex);
            }

            var receipts = (ArrayResult)api.RelayReceive(receiver.Address.Text);

            Assert.IsTrue(receipts.values.Length == messageCount);

            for (int i = 0; i < messageCount; i++)
            {
                var obj = receipts.values[i];
                Assert.IsTrue(obj is ReceiptResult);

                var receiptResult = (ReceiptResult)obj;
                Assert.IsTrue(receiptResult.nexus == messages[i].nexus);
                Assert.IsTrue(new BigInteger(receiptResult.index, 10) == messages[i].index);
                //Assert.IsTrue(receiptResult.receiver == messages[i].receiver);
                //Assert.IsTrue(receiptResult.script == messages[i].script);
                //Assert.IsTrue(receiptResult.sender == messages[i].sender);
                Assert.IsTrue(receiptResult.timestamp == messages[i].timestamp);
            }
        }
Esempio n. 16
0
 public Builder SetSourceAccount(KeyPair sourceAccount)
 {
     _sourceAccount = sourceAccount ?? throw new ArgumentNullException(nameof(sourceAccount), "sourceAccount cannot be null");
     return(this);
 }
Esempio n. 17
0
 public TERC1Account(TERC1Wallet wallet, UInt160 scriptHash, KeyPair key, string password)
     : this(wallet, scriptHash, key.Export(password, wallet.Scrypt.N, wallet.Scrypt.R, wallet.Scrypt.P))
 {
     this.key = key;
 }
Esempio n. 18
0
        public static bool IsValid(this Ed25519Signature signature, byte[] data)
        {
            var keypair = KeyPair.FromPublicKey(signature.Signer.ToArray());

            return(keypair.Verify(data, signature.Signature));
        }
Esempio n. 19
0
        public void TestCrypto_CheckMultiSig()
        {
            var         engine = GetEngine(true);
            IVerifiable iv     = engine.ScriptContainer;

            byte[] message = iv.GetSignData(ProtocolSettings.Default.Network);

            byte[]  privkey1 = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
                                 0x01,  0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
            KeyPair key1    = new KeyPair(privkey1);
            ECPoint pubkey1 = key1.PublicKey;

            byte[] signature1 = Crypto.Sign(message, privkey1, pubkey1.EncodePoint(false).Skip(1).ToArray());

            byte[]  privkey2 = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
                                 0x01,  0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02 };
            KeyPair key2    = new KeyPair(privkey2);
            ECPoint pubkey2 = key2.PublicKey;

            byte[] signature2 = Crypto.Sign(message, privkey2, pubkey2.EncodePoint(false).Skip(1).ToArray());

            var pubkeys = new[]
            {
                pubkey1.EncodePoint(false),
                pubkey2.EncodePoint(false)
            };
            var signatures = new[]
            {
                signature1,
                signature2
            };

            engine.CheckMultisig(pubkeys, signatures).Should().BeTrue();

            pubkeys = new byte[0][];
            Assert.ThrowsException <ArgumentException>(() => engine.CheckMultisig(pubkeys, signatures));

            pubkeys = new[]
            {
                pubkey1.EncodePoint(false),
                pubkey2.EncodePoint(false)
            };
            signatures = new byte[0][];
            Assert.ThrowsException <ArgumentException>(() => engine.CheckMultisig(pubkeys, signatures));

            pubkeys = new[]
            {
                pubkey1.EncodePoint(false),
                pubkey2.EncodePoint(false)
            };
            signatures = new[]
            {
                signature1,
                new byte[64]
            };
            engine.CheckMultisig(pubkeys, signatures).Should().BeFalse();

            pubkeys = new[]
            {
                pubkey1.EncodePoint(false),
                new byte[70]
            };
            signatures = new[]
            {
                signature1,
                signature2
            };
            Assert.ThrowsException <FormatException>(() => engine.CheckMultisig(pubkeys, signatures));
        }
Esempio n. 20
0
        private void AddNewValidator(KeyPair newValidator)
        {
            Timestamp startTime = simulator.CurrentTime;
            Timestamp endTime   = simulator.CurrentTime.AddDays(1);
            var       pollName  = SystemPoll + ValidatorPollTag;

            var validators = (ValidatorEntry[])simulator.Nexus.RootChain.InvokeContract(Nexus.ValidatorContractName,
                                                                                        nameof(ValidatorContract.GetValidators)).ToObject(typeof(ValidatorEntry[]));

            var activeValidators     = validators.Where(x => x.address != Address.Null);
            var activeValidatorCount = activeValidators.Count();

            var choices = new PollChoice[activeValidatorCount + 1];

            for (int i = 0; i < activeValidatorCount; i++)
            {
                choices[i] = new PollChoice()
                {
                    value = validators[i].address.PublicKey
                };
            }

            choices[activeValidatorCount] = new PollChoice()
            {
                value = newValidator.Address.PublicKey
            };

            var serializedChoices = choices.Serialize();

            //start vote for new validator
            simulator.BeginBlock();
            simulator.GenerateCustomTransaction(owner, ProofOfWork.None, () =>
                                                ScriptUtils.BeginScript().
                                                AllowGas(owner.Address, Address.Null, 1, 9999).
                                                CallContract(ConsensusContractName, nameof(ConsensusContract.InitPoll),
                                                             owner.Address, pollName, ConsensusKind.Validators, ConsensusMode.Majority, startTime, endTime, serializedChoices, 1).
                                                SpendGas(owner.Address).
                                                EndScript());
            simulator.EndBlock();

            for (int i = 0; i < activeValidatorCount; i++)
            {
                var validator = validatorKeyPairs[i];

                //have each already existing validator vote on themselves to preserve the validator order
                simulator.BeginBlock();
                simulator.GenerateCustomTransaction(validator, ProofOfWork.None, () =>
                                                    ScriptUtils.BeginScript().
                                                    AllowGas(validator.Address, Address.Null, 1, 9999).
                                                    CallContract(ConsensusContractName, nameof(ConsensusContract.SingleVote),
                                                                 validator.Address, pollName, i).
                                                    SpendGas(validator.Address).
                                                    EndScript());
                simulator.EndBlock();
            }

            //skip until the voting is over
            simulator.TimeSkipDays(1.5);

            var votingRank = simulator.Nexus.RootChain.InvokeContract(ConsensusContractName, nameof(ConsensusContract.GetRank), pollName,
                                                                      choices[activeValidatorCount].Serialize()).AsNumber();

            //call SetValidator for each set validator address
            for (int i = 0; i <= activeValidatorCount; i++)
            {
                var validatorChoice = choices[i].value;

                ValidatorType validatorType = i < 2 ? Primary : Secondary;

                votingRank = simulator.Nexus.RootChain.InvokeContract(ConsensusContractName, nameof(ConsensusContract.GetRank), pollName, validatorChoice).AsNumber();

                simulator.BeginBlock();
                var tx = simulator.GenerateCustomTransaction(owner, ProofOfWork.None, () =>
                                                             ScriptUtils.BeginScript().
                                                             AllowGas(owner.Address, Address.Null, 1, 9999).
                                                             CallContract(ValidatorContractName, nameof(ValidatorContract.SetValidator), validatorChoice, votingRank, validatorType).
                                                             SpendGas(owner.Address).
                                                             EndScript());
                simulator.EndBlock().First();
            }
        }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140830
            // X:\jsc.svn\examples\javascript\appengine\Test\TestCryptoKeyGenerate\TestCryptoKeyGenerate\ApplicationWebService.cs
            // X:\jsc.svn\examples\java\hybrid\JVMCLRRSA\JVMCLRRSA\Program.cs

            #region Do a release build to create a hybrid jvmclr program.
            if (typeof(object).FullName != "java.lang.Object")
            {
                System.Console.WriteLine("Do a release build to create a hybrid jvmclr program.");
                Debugger.Break();
                return;
            }
            #endregion


            System.Console.WriteLine("jvm ready! " + typeof(object).FullName);



#if JCE
            try
            {
                var sw = Stopwatch.StartNew();

                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

                keyGen.initialize(2048);

                KeyPair keyPair = keyGen.generateKeyPair();
                Console.WriteLine("after generateKeyPair " + new { sw.ElapsedMilliseconds });
                // after generateKeyPair { ElapsedMilliseconds = 1791 }

                PublicKey  publicKey  = keyPair.getPublic();
                PrivateKey privateKey = keyPair.getPrivate();
                //System.Console.WriteLine("Public Key - " + publicKey.ToString());
                //System.Console.WriteLine("Private Key - " + privateKey.ToString());

                var data = new sbyte[] { 0x02, 0x03, 0x04, 0x05 };
                System.Console.WriteLine(data.Length.ToString());


                Cipher rsaCipher = Cipher.getInstance("RSA");


                //Encrypt
                rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
                sbyte[] encByte = rsaCipher.doFinal(data);
                System.Console.WriteLine(encByte.Length.ToString());


                //Decrypt
                rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
                sbyte[] decByte = rsaCipher.doFinal(encByte);
                System.Console.WriteLine(decByte.Length.ToString());

                if (data.Length != decByte.Length)
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (data[i] != decByte[i])
                        {
                            System.Console.WriteLine("false");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
            }
#endif

            //jvm ready! java.lang.Object
            //4
            //256
            //4

            CLRProgram.CLRMain();

            System.Console.WriteLine("jvm exit!");
        }
Esempio n. 22
0
    /// <summary>
    /// Set value of property and add comment. It will create new property if absent.
    /// </summary>
    /// <param name="key">Name of property</param>
    /// <param name="value">New value</param>
    /// <param name="comment">Comment for property</param>
    public void Set(string key, string value, string comment)
    {
        if (!key.Contains("="))
        {
            KeyPair outKeyPair = null;

            if (mKeysMap.TryGetValue(mCurrentGroup + key, out outKeyPair))
            {
                outKeyPair.value   = value;
                outKeyPair.comment = comment;

                return;
            }

            outKeyPair = new KeyPair(mCurrentGroup + key, value, comment);

            mKeysMap.Add(mCurrentGroup + key, outKeyPair);
            mKeysList.Add(outKeyPair);
        }
        else
        {
            Debug.LogError("Invalid key name: " + key);
        }
    }
Esempio n. 23
0
        protected virtual Task<WebAuthenticationResult> GetUserAuthorization(KeyPair requestToken, IWebAuthenticator authorizer)
        {
            var authorizationUrlBuilder = new UriBuilder(UrlAuthorizeToken);
            authorizationUrlBuilder.AddToQuery("oauth_token", requestToken.Key);

            return authorizer.AuthorizeUser(authorizationUrlBuilder.Uri);
        }
Esempio n. 24
0
 public Data Sign(KeyPair keyPair)
 {
     return(Sign(keyPair, false));
 }
Esempio n. 25
0
        /// <summary>
        /// Bundles specified edges. Shapes of all the other edges remain the same,
        /// so this method is faster than the one for bundling all edges, but also produces less optimal layout.
        /// </summary>
        /// 
        /// <param name="graph">
        /// Parent graph of the edge set
        /// </param>
        /// 
        /// <param name="edges">
        /// Edges that should be bundled
        /// </param>
        /// 
        /// <param name="rectangle">
        /// Rectangle in which the graph is laid out.
        /// Control points of bundled edges should not fall outside of this rectangle.
        /// </param>
        public void BundleEdges(IGraph graph, IEnumerable<IEdge> edges, Rectangle rectangle)
        {
            this.rectangle = rectangle;
            if (graph.Directedness != GraphDirectedness.Undirected)
                directed = true;
            else directed = false;
            AddAllExistingData(graph.Edges);
            AddEdgeDataForMovedEdges(edges);
            FindCompatibleEdges(movedEdgeGroupData);
            ResetMovedEdges();

            for (int i = 0; i < iterations; i++)
                MoveControlPoints(movedEdgeGroupData);

            for (int i = 0; i < 5; i++)
            {
                cooldown *= 0.5f;
                MoveControlPoints(movedEdgeGroupData);
            }

            cooldown = 1f;

            if (straightening > 0)
                StraightenEdgesInternally(movedEdgeGroupData, straightening);

            foreach (IEdge e in edges)
            {
                EdgeGroupData ed;
                KeyPair key = new KeyPair(e.Vertices[0].ID, e.Vertices[1].ID);
                movedEdgeGroupData.TryGetValue(key, out ed);
                if (ed != null)
                    e.SetValue(ReservedMetadataKeys.PerEdgeIntermediateCurvePoints, ed.controlPoints);
            }
        }
Esempio n. 26
0
 public Data SignNow(KeyPair keyPair, ISignatureFactory signatureFactory)
 {
     return(SignNow(keyPair, signatureFactory, false));
 }
 protected override string DeriveAddress(KeyPair keys)
 {
     return(keys.Address.Text);
 }
Esempio n. 28
0
 public Data ProtectEntry(KeyPair keyPair, bool isProtectedEntry)
 {
     return(Sign(keyPair, true));
 }
Esempio n. 29
0
        // Creates a new OrgInfo instance from a JSON object
        private OrgInfo CreateOrg(string orgName, JToken jsonOrg, Dictionary <string, JToken> foundCertificateAuthorities)
        {
            string msgPrefix = $"Organization {orgName}";

            string mspId = jsonOrg["mspid"]?.Value <string>();

            OrgInfo org = new OrgInfo(orgName, mspId);

            // Peers
            JArray jsonPeers = jsonOrg["peers"] as JArray;

            if (jsonPeers != null)
            {
                foreach (JToken peer in jsonPeers)
                {
                    string peerName = peer.Value <string>();
                    if (!string.IsNullOrEmpty(peerName))
                    {
                        org.PeerName.Add(peerName);
                    }
                }
            }

            // CAs
            JArray jsonCertificateAuthorities = jsonOrg["certificateAuthorities"] as JArray;

            if (jsonCertificateAuthorities != null)
            {
                foreach (JToken jsonCA in jsonCertificateAuthorities)
                {
                    string caName = jsonCA.Value <string>();

                    if (!string.IsNullOrEmpty(caName))
                    {
                        JToken jsonObject = foundCertificateAuthorities[caName];
                        if (jsonObject != null)
                        {
                            org.CertificateAuthorities.Add(CreateCA(caName, jsonObject, org));
                        }
                        else
                        {
                            throw new NetworkConfigurationException($"{msgPrefix}: Certificate Authority {caName} is not defined");
                        }
                    }
                }
            }

            string adminPrivateKeyString = ExtractPemString(jsonOrg, "adminPrivateKey", msgPrefix);
            string signedCert            = ExtractPemString(jsonOrg, "signedCert", msgPrefix);

            if (!string.IsNullOrEmpty(adminPrivateKeyString) && !string.IsNullOrEmpty(signedCert))
            {
                KeyPair privateKey;

                try
                {
                    privateKey = KeyPair.Create(adminPrivateKeyString);
                }
                catch (IOException ioe)
                {
                    throw new NetworkConfigurationException($"{msgPrefix}: Invalid private key", ioe);
                }

                try
                {
                    org.PeerAdmin = new UserInfo(Factory.GetCryptoSuite(), mspId, "PeerAdmin_" + mspId + "_" + orgName, null);
                }
                catch (Exception e)
                {
                    throw new NetworkConfigurationException(e.Message, e);
                }

                org.PeerAdmin.Enrollment = new X509Enrollment(privateKey, signedCert);
            }

            return(org);
        }
Esempio n. 30
0
 public Data ProtectEntryNow(KeyPair keyPair, ISignatureFactory signatureFactory)
 {
     return(SignNow(keyPair, signatureFactory, true));
 }
Esempio n. 31
0
        public void TestBasic()
        {
            byte[] seed = { 0, 0, 0, 0 };
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(seed);

            Console.WriteLine("preparing the authority block");

            KeyPair root = new KeyPair(rng);

            SymbolTable  symbols           = Biscuit.Token.Biscuit.DefaultSymbolTable();
            BlockBuilder authority_builder = new BlockBuilder(0, symbols);

            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file1"), Utils.Symbol("read"))));
            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file2"), Utils.Symbol("read"))));
            authority_builder.AddFact(Utils.Fact("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Symbol("file1"), Utils.Symbol("write"))));

            Biscuit.Token.Biscuit b = Biscuit.Token.Biscuit.Make(rng, root, Biscuit.Token.Biscuit.DefaultSymbolTable(), authority_builder.Build()).Right;

            Console.WriteLine(b.Print());

            Console.WriteLine("serializing the first token");

            byte[] data = b.Serialize().Right;

            Console.Write("data len: ");
            Console.WriteLine(data.Length);
            //Console.WriteLine(hex(data));

            Console.WriteLine("deserializing the first token");
            Biscuit.Token.Biscuit deser = Biscuit.Token.Biscuit.FromBytes(data).Right;

            Console.WriteLine(deser.Print());

            // SECOND BLOCK
            Console.WriteLine("preparing the second block");

            KeyPair keypair2 = new KeyPair(rng);

            BlockBuilder builder = deser.CreateBlock();

            builder.AddCheck(Utils.Check(Utils.Rule(
                                             "caveat1",
                                             Arrays.AsList(Utils.Var("resource")),
                                             Arrays.AsList(
                                                 Utils.Pred("resource", Arrays.AsList(Utils.Symbol("ambient"), Utils.Var("resource"))),
                                                 Utils.Pred("operation", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("read"))),
                                                 Utils.Pred("right", Arrays.AsList(Utils.Symbol("authority"), Utils.Var("resource"), Utils.Symbol("read")))
                                                 )
                                             )));

            Biscuit.Token.Biscuit b2 = deser.Attenuate(rng, keypair2, builder.Build()).Right;

            Console.WriteLine(b2.Print());

            Console.WriteLine("serializing the second token");

            byte[] data2 = b2.Serialize().Right;

            Console.Write("data len: ");
            Console.WriteLine(data2.Length);
            //Console.WriteLine(hex(data2));

            Console.WriteLine("deserializing the second token");
            Biscuit.Token.Biscuit deser2 = Biscuit.Token.Biscuit.FromBytes(data2).Right;

            Console.WriteLine(deser2.Print());

            // THIRD BLOCK
            Console.WriteLine("preparing the third block");

            KeyPair keypair3 = new KeyPair(rng);

            BlockBuilder builder3 = deser2.CreateBlock();

            builder3.AddCheck(Utils.Check(Utils.Rule(
                                              "caveat2",
                                              Arrays.AsList(Utils.Symbol("file1")),
                                              Arrays.AsList(
                                                  Utils.Pred("resource", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("file1")))
                                                  )
                                              )));

            Biscuit.Token.Biscuit b3 = deser2.Attenuate(rng, keypair3, builder3.Build()).Right;

            Console.WriteLine(b3.Print());

            Console.WriteLine("serializing the third token");

            byte[] data3 = b3.Serialize().Right;

            Console.Write("data len: ");
            Console.WriteLine(data3.Length);
            //Console.WriteLine(hex(data3));

            Console.WriteLine("deserializing the third token");
            Biscuit.Token.Biscuit final_token = Biscuit.Token.Biscuit.FromBytes(data3).Right;

            Console.WriteLine(final_token.Print());

            // check
            Console.WriteLine("will check the token for resource=file1 and operation=read");

            SymbolTable check_symbols = new SymbolTable(final_token.Symbols);
            List <Fact> ambient_facts = Arrays.AsList(
                Utils.Fact("resource", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("file1"))).Convert(check_symbols),
                Utils.Fact("operation", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("read"))).Convert(check_symbols)
                );

            Either <Error, Dictionary <string, HashSet <Fact> > > res = final_token.Check(check_symbols, ambient_facts,
                                                                                          new List <Rule>(), new List <Check>(), new Dictionary <string, Rule>());

            Assert.IsTrue(res.IsRight);

            Console.WriteLine("will check the token for resource=file2 and operation=write");

            SymbolTable check_symbols2 = new SymbolTable(final_token.Symbols);
            List <Fact> ambient_facts2 = Arrays.AsList(
                Utils.Fact("resource", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("file2"))).Convert(check_symbols2),
                Utils.Fact("operation", Arrays.AsList(Utils.Symbol("ambient"), Utils.Symbol("write"))).Convert(check_symbols2)
                );

            Either <Error, Dictionary <string, HashSet <Fact> > > res2 = final_token.Check(check_symbols2, ambient_facts2,
                                                                                           new List <Rule>(), new List <Check>(), new Dictionary <string, Rule>());

            Assert.IsTrue(res2.IsLeft);
            Console.WriteLine(res2.Left);

            Assert.AreEqual(
                new FailedLogic(new LogicError.FailedChecks(Arrays.AsList <FailedCheck>(
                                                                new FailedCheck.FailedBlock(1, 0, "check if resource(#ambient, $resource), operation(#ambient, #read), right(#authority, $resource, #read)"),
                                                                new FailedCheck.FailedBlock(2, 0, "check if resource(#ambient, #file1)")
                                                                ))),
                res2.Left);
        }
Esempio n. 32
0
        /// <summary>
        /// Takes a KeyCollectionItem from elsewhere in the program for display.
        /// This gets called if someone doubleclicks an address in the Key Collection View, or chooses Details.
        /// Item may represent an AddressBase, PublicKey, KeyPair, MiniKey, or an EncryptedKeyPair
        /// </summary>
        public void DisplayKeyCollectionItem(KeyCollectionItem item)
        {
            try {
                ChangeFlag++;
                if (item.EncryptedKeyPair != null)
                {
                    SetText(txtPrivWIF, item.EncryptedKeyPair.EncryptedPrivateKey);
                    // blank out any validation info of the minikey
                    UpdateMinikeyDescription();
                    SetText(txtPassphrase, "");
                    if (item.EncryptedKeyPair.IsUnencryptedPrivateKeyAvailable())
                    {
                        SetText(txtPrivHex, item.EncryptedKeyPair.GetUnencryptedPrivateKey().PublicKeyHex);
                    }
                    else
                    {
                        SetText(txtPrivHex, "");
                    }
                    if (item.EncryptedKeyPair.IsPublicKeyAvailable())
                    {
                        SetText(txtPubHex, item.EncryptedKeyPair.GetPublicKey().PublicKeyHex);
                    }
                    else
                    {
                        SetText(txtPubHex, "");
                    }
                    if (item.EncryptedKeyPair.IsAddressAvailable())
                    {
                        AddressBase addr = item.EncryptedKeyPair.GetAddress();
                        SetText(txtPubHash, addr.Hash160Hex);
                        SetText(txtBtcAddr, addr.AddressBase58);
                    }
                    else
                    {
                        SetText(txtPubHash, "");
                        SetText(txtBtcAddr, "");
                    }
                    return;
                }

                // Handle whether the item is/isn't a minikey

                if (item.Address != null && item.Address is MiniKeyPair)
                {
                    SetText(txtMinikey, ((MiniKeyPair)item.Address).MiniKey);
                }
                else
                {
                    SetText(txtMinikey, "");
                }

                // update the label to indicate whether this is a valid minikey (or blank it out if n/a)
                UpdateMinikeyDescription();

                if (item.Address != null)
                {
                    // Handle whether item is/isn't a keypair (known private key)
                    if (item.Address is KeyPair)
                    {
                        KeyPair kp = (KeyPair)item.Address;
                        SetText(txtPrivWIF, kp.PrivateKeyBase58);
                        SetText(txtPrivHex, kp.PrivateKeyHex);
                    }
                    else
                    {
                        SetText(txtPrivWIF, "");
                        SetText(txtPrivHex, "");
                    }

                    // Handle whether item has/doesn't have known public key
                    if (item.Address is PublicKey)
                    {
                        PublicKey pub = ((PublicKey)item.Address);
                        SetText(txtPubHex, pub.PublicKeyHex);
                    }
                    else
                    {
                        SetText(txtPubHex, "");
                    }

                    // Handle address
                    SetText(txtPubHash, item.Address.Hash160Hex);
                    SetText(txtBtcAddr, item.Address.AddressBase58);
                }
            } finally {
                ChangeFlag--;
            }
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            var api = NeoRPC.ForPrivateNet();

            api.SetLogger(LocalLogger);

            var demoKeys = new KeyPair(demoPrivateKeyHex.HexToBytes());

            Console.WriteLine($"demoPrivateKeyHex.keys:\t{JsonConvert.SerializeObject(demoKeys)}");
            var balances = api.GetAssetBalancesOf(demoKeys.address);

            foreach (var entry in balances)
            {
                Console.WriteLine(entry.Key + "\t" + entry.Value);
            }

            var my0Keys = new KeyPair(my0PrivateKeyHex.HexToBytes());

            Console.WriteLine($"my0PrivateKeyHex.keys:\t{JsonConvert.SerializeObject(my0Keys)}");
            var my1Keys = new KeyPair(my1PrivateKeyHex.HexToBytes());

            Console.WriteLine($"my1PrivateKeyHex.keys:\t{JsonConvert.SerializeObject(my1Keys)}");

            Console.WriteLine();
            Console.WriteLine("Balances:");
            balances = api.GetAssetBalancesOf(my0Keys.address);
            foreach (var entry in balances)
            {
                Console.WriteLine(entry.Key + "\t" + entry.Value);
            }
            balances = api.GetAssetBalancesOf(my1Keys.address);
            foreach (var entry in balances)
            {
                Console.WriteLine(entry.Key + "\t" + entry.Value);
            }

            Console.WriteLine();
            Console.WriteLine("Unspent Balances:");
            var unspentBalances = api.GetUnspent(my0Keys.address);

            foreach (var entry in unspentBalances)
            {
                Console.WriteLine(entry.Key + "\t" + JsonConvert.SerializeObject(entry.Value));
            }
            unspentBalances = api.GetUnspent(my1Keys.address);
            foreach (var entry in unspentBalances)
            {
                Console.WriteLine(entry.Key + "\t" + JsonConvert.SerializeObject(entry.Value));
            }

            Console.WriteLine();
            Console.WriteLine("GetClaimable Balances:");
            decimal amount       = 0;
            var     claimableGas = api.GetClaimable(my0Keys.PublicKeyHash, out amount);

            Console.WriteLine($"GetClaimable:\t{amount}");
            foreach (var entry in claimableGas)
            {
                Console.WriteLine(JsonConvert.SerializeObject(entry));
            }
            claimableGas = api.GetClaimable(my1Keys.PublicKeyHash, out amount);
            Console.WriteLine($"GetClaimable:\t{amount}");
            foreach (var entry in claimableGas)
            {
                Console.WriteLine(JsonConvert.SerializeObject(entry));
            }

            Console.WriteLine();
            Console.WriteLine("AVM:");
            byte[] avmBytes = File.ReadAllBytes(avmFilename);
            Console.WriteLine($"Bytes:\t{avmFilename}\t{avmBytes.Length} bytes");
            Console.WriteLine($"Bytes:\t{avmFilename}\t'{avmBytes.ToHexString()}'");

            Console.WriteLine();
            Console.WriteLine("AVM Script Hash:");
            UInt160 avmScriptHash       = avmBytes.ToScriptHash();
            string  avmScriptHashString = avmBytes.ToScriptHash().ToString();
            string  avmAddress          = avmScriptHash.ToAddress();

            byte[] avmScriptHashBytes    = avmScriptHash.ToArray();
            string avmScriptHashBytesHex = avmScriptHashBytes.ToHexString();

            Console.WriteLine($"avmScriptHash:\t{JsonConvert.SerializeObject(avmScriptHash)}");
            Console.WriteLine($"avmScriptHashString:\t{avmScriptHashString}");
            Console.WriteLine($"avmAddress:\t{avmAddress}");
            Console.WriteLine($"avmScriptHashBytes:\t{JsonConvert.SerializeObject(avmScriptHashBytes)}");
            Console.WriteLine($"avmScriptHashBytesHex:\t{avmScriptHashBytesHex}");

            Console.WriteLine();
            Console.WriteLine("Press EXIT to exit...");
            Console.ReadLine();

            //byte[] parameterTypes = { (byte)ContractParameterType.String, (byte)ContractParameterType.Array };
            //byte returnType = (byte)ContractParameterType.Void;
            //ContractPropertyState properties = ContractPropertyState.NoProperty;
            //Transaction tDeploy = api.DeployContract(my0Keys, avmBytes, parameterTypes, returnType, properties, "Demo AVM", "1.0.0", "Able Baker", "*****@*****.**", "Demonstration AVM");
            //Console.WriteLine($"tDeploy:\t{JsonConvert.SerializeObject(tDeploy)}");
            //File.WriteAllText("tDeploy.json", JsonConvert.SerializeObject(tDeploy));

            //object[] testargs = { "a", "b", "c" };
            //InvokeResult response = api.InvokeScript(avmScriptHash, "testoperation", testargs);
            //Console.WriteLine($"response:\t{JsonConvert.SerializeObject(response)}");
            //Console.WriteLine($"state:\t{response.state}");
            //Console.WriteLine($"stack:\t{JsonConvert.SerializeObject(response.stack)}");
            //Console.WriteLine($"stack[0]:\t{response.stack[0]}");
            ////object obj = response.stack[1];
            ////byte[] stack1Bytes = (byte[])obj;
            ////string stack1String1 = stack1Bytes.ToHexString();
            ////Console.WriteLine($"stack1String1:\t{stack1String1}");
            ////string stack1String2 = stack1Bytes.ByteToHex();
            ////Console.WriteLine($"stack1String2:\t{stack1String2}");

            string testoperation = "testoperation2";

            Console.WriteLine($"{testoperation}\t{ToHex(testoperation)}");
            object[] testargs = new object[] { "a", "b", "c", "d" };
            Console.WriteLine($"{testargs[0]}\t{ToHex((string)testargs[0])}");
            Console.WriteLine($"{testargs[1]}\t{ToHex((string)testargs[1])}");
            Console.WriteLine($"{testargs[2]}\t{ToHex((string)testargs[2])}");
            Console.WriteLine($"{testargs[3]}\t{ToHex((string)testargs[3])}");
            Transaction tResult = api.CallContract(my0Keys, avmScriptHash, testoperation, testargs);

            Console.WriteLine($"tResult:\t{JsonConvert.SerializeObject(tResult)}");
            File.WriteAllText("tResult.json", JsonConvert.SerializeObject(tResult));

            Console.WriteLine();
            Console.WriteLine("Press EXIT to exit...");
            Console.ReadLine();
        }
Esempio n. 34
0
        // '"fromWallet()" returns a well-formed "RequestDidPowerUp" object.'
        public async Task WellFormedRequestDidPowerUpFromWallet()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            String        lcdUrl         = "http://localhost:1317";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: lcdUrl);
            String        mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            Wallet pairwaisedWallet = Wallet.derive(mnemonic, networkInfo, lastDerivationPathSegment: "1");

            List <StdCoin> amount = new List <StdCoin> {
                new StdCoin(denom: "denom", amount: "10")
            };

            // Here the mock server part...
            // Build the mockup server
            String localTestUrl1 = $"{lcdUrl}/government/tumbler";
            String localTestUrl2 = $"{lcdUrl}/identities/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";

            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <string, object> nodeResponse1 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerAddressJson);
            Dictionary <String, Object> nodeResponse2 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerIdentityJson);

            // Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", nodeResponse1);
            _server
            .WithService(localTestUrl2)
            .Api("", "GET", nodeResponse2);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;


            KeyPair keyPair = KeysHelper.generateRsaKeyPair();

            String powerUpProof  = "powerUpProof";
            String uuid          = Guid.NewGuid().ToString();
            String encryptionKey = "encryptionKey";

            RequestDidPowerUp expectedRequestDidPowerUp = new RequestDidPowerUp(
                claimantDid: wallet.bech32Address,
                amount: amount,
                powerUpProof: Convert.ToBase64String(Encoding.UTF8.GetBytes(powerUpProof)),
                uuid: uuid,
                encryptionKey: Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptionKey))
                );

            RequestDidPowerUp requestDidPowerUp = await RequestDidPowerUpHelper.fromWallet(
                wallet,
                pairwaisedWallet.bech32Address,
                amount,
                (RSAPrivateKey)keyPair.privateKey
                );

            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.claimantDid, expectedRequestDidPowerUp.claimantDid).AreEqual, true);
            Assert.AreEqual(requestDidPowerUp.amount.Count, expectedRequestDidPowerUp.amount.Count);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.amount[0].toJson(), expectedRequestDidPowerUp.amount[0].toJson()).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.uuid, expectedRequestDidPowerUp.uuid).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.powerUpProof, expectedRequestDidPowerUp.powerUpProof).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.encryptionKey, expectedRequestDidPowerUp.encryptionKey).AreEqual, false);
        }
Esempio n. 35
0
        /// <summary>
        /// Bundles edges of the graph.
        /// </summary>
        /// <param name="graph">
        ///     Graph whose edges should be bundled
        /// </param>
        /// <param name="cancellationToken"></param>
        public void BundleAllEdges(TGraph graph, CancellationToken cancellationToken)
        {
            EdgeRoutes.Clear();

            //this.rectangle = rectangle;
            _directed = true; // as we use bidirectional by default

            AddDataForAllEdges(graph.Edges, cancellationToken);

            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            FindCompatibleEdges(_edgeGroupData, cancellationToken);

            //sw.Stop();


            DivideAllEdges(_subdivisionPoints, cancellationToken);

            //sw = new Stopwatch();
            //sw.Start();

            for (var i = 0; i < _iterations; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                MoveControlPoints(_edgeGroupData);
            }

            //prevents oscillating movements
            for (var i = 0; i < 5; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                _cooldown *= 0.5f;
                MoveControlPoints(_edgeGroupData);
            }

            //sw.Stop();

            _cooldown = 1f;

            if (_straightening > 0)
            {
                StraightenEdgesInternally(_edgeGroupData, _straightening);
            }

            foreach (var e in graph.Edges)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (!e.IsSelfLoop)
                {
                    var key   = new KeyPair(e.Source.ID, e.Target.ID);
                    var list2 = _edgeGroupData[key].ControlPoints.ToList();

                    //Point p1 = GeometryHelper.GetEdgeEndpointOnRectangle(VertexPositions[e.Source], VertexSizes[e.Source], list2.First());
                    //Point p2 = GeometryHelper.GetEdgeEndpointOnRectangle(VertexPositions[e.Target], VertexSizes[e.Target], list2.Last());
                    //list2.Insert(0, p1); list2.Add(p2);
                    list2.Insert(0, list2.First()); list2.Add(list2.Last());

                    EdgeRoutes.Add(e, list2.ToArray());
                }
            }
        }
 ///<Summary>
 /// Builds request to <code>GET /accounts/{account}/effects</code>
 /// <a href="https://www.stellar.org/developers/horizon/reference/effects-for-account.html">Effects for Account</a>
 /// </Summary>
 /// <param name="account">Account for which to get effects</param>
 public EffectsRequestBuilder ForAccount(KeyPair account)
 {
     account = account ?? throw new ArgumentNullException(nameof(account), "account cannot be null");
     this.SetSegments("accounts", account.AccountId, "effects");
     return(this);
 }
Esempio n. 37
0
        public static async void Payout(decimal InflationAmount)
        {
            Network.UseTestNetwork();

            //Get the number of votes you have
            var votes = GetTotalVotes();
            //Get the accounts that voted for you and what you owe them
            var accounts = GetVoterAccounts(InflationAmount, votes);

            decimal sum        = 0;
            decimal percentage = 0;

            KeyPair PoolSource = KeyPair.FromSecretSeed(Configuration["INFLATION_POOL_SECRET"]);
            //KeyPair PoolSource = KeyPair.FromSecretSeed(Environment.GetEnvironmentVariable("INFLATION_POOL_SECRET"));

            AccountResponse sourceAccount = await server.Accounts.Account(PoolSource);

            var     sequenceNumber = sourceAccount.SequenceNumber;
            Account PoolAccount    = new Account(PoolSource, sequenceNumber);

            Transaction.Builder BatchTransaction = new Transaction.Builder(PoolAccount);
            List <Transaction>  Transactions     = new List <Transaction>();

            int batch = 0;

            foreach (var account in accounts)
            {
                //we can only have 100 operations per transaction, this means we need to split up our payouts every 100 people

                //Rounding down because we're greedy pigs that want to keep every last stroop
                var payout        = RoundDown(account.Payout, 7);
                var payoutPercent = RoundDown(account.Percentage, 7);
                //Create the payment operation, we are pulling the 100 stroop fee out of the receipients end.
                //The lowest amount a voting account could possibly contain is 1 lumen
                //1 lumen will earn 0.0001923 lumens per week, so we don't have to worry about the fee being larger than a potential earning!
                var operation = new PaymentOperation.Builder(KeyPair.FromAccountId(account.AccountId), new AssetTypeNative(), (payout - .0000100m).ToString())
                                .SetSourceAccount(PoolSource)
                                .Build();
                BatchTransaction.AddOperation(operation);

                Console.WriteLine($" Account: {account.AccountId} Earned: {payout}XLM (%{payoutPercent})");

                //totalling up our payout/percentages
                sum        += payout;
                percentage += payoutPercent;

                if (batch == 99 || account.Equals(accounts.LastOrDefault()))
                {
                    //This batch is full! we sign it with a memo and our private key and add it to the list of to be processed outgoing transactions.
                    var t = BatchTransaction.AddMemo(Memo.Text($"Sample Memo")).Build();
                    t.Sign(PoolSource);
                    Transactions.Add(t);
                    BatchTransaction = new Transaction.Builder(PoolAccount);
                }
                //Reset the batch
                batch = batch == 99 ? 0 : ++batch;
            }

            Console.WriteLine("Submitting batches to the stellar network...");
            foreach (var t in Transactions)
            {
                //Submit each transaction to the network
                Console.WriteLine($"Submitting batch: {Transactions.IndexOf(t) + 1}...");
                var response = await server.SubmitTransaction(t);

                Console.WriteLine($"Batch submitted.");
                //Console.WriteLine($"Envelope XDR is:");
                //Console.WriteLine($"{response.EnvelopeXdr}");
            }

            Console.WriteLine($"Payed out: {sum} (%{percentage})");
            //Exists the console app after it has found inflation and payed out.
            Console.WriteLine("Exiting");
            Environment.Exit(0);
        }
Esempio n. 38
0
 public SSH2UserAuthKey(KeyPair kp)
 {
     _keypair = kp;
 }
Esempio n. 39
0
 /// <summary>
 /// Creates a peer bean with a key pair.
 /// </summary>
 /// <param name="keyPair">The key pair that holds private and public key.</param>
 public PeerBean(KeyPair keyPair)
 {
     KeyPair             = keyPair;
     PeerStatusListeners = new List <IPeerStatusListener>(1);
     OpenPeerConnections = new ConcurrentDictionary <Number160, PeerConnection>();
 }
 /// <summary>
 /// Sends an amount in a specific asset to a destination account through a path of offers. This allows the asset sent (e.g., 450 XLM) to be different from the asset received (e.g, 6 BTC).
 /// </summary>
 /// <param name="amount">The amount of destination asset the destination account receives.</param>
 /// <param name="sourceMax">The amount of source asset deducted from senders account.</param>
 /// <param name="from">Account address that is sending the payment.</param>
 /// <param name="to">Account address that receives the payment.</param>
 /// <param name="assetType">Account address that receives the payment.</param>
 /// <param name="assetCode">The asset code (Alpha4, Alpha12, etc.)</param>
 /// <param name="assetIssuer">The account that created the asset</param>
 /// <param name="sendAssetType">The asset type (USD, BTC, etc.) to be sent.</param>
 /// <param name="sendAssetCode">The asset code (Alpha4, Alpha12, etc.) to be sent</param>
 /// <param name="sendAssetIssuer">The account that created the asset to be sent.</param>
 public PathPaymentOperationResponse(string amount, string sourceMax, KeyPair from, KeyPair to, string assetType, string assetCode,
                                     string assetIssuer, string sendAssetType, string sendAssetCode, string sendAssetIssuer)
 {
     Amount          = amount;
     SourceMax       = sourceMax;
     From            = from;
     To              = to;
     AssetType       = assetType;
     AssetCode       = assetCode;
     AssetIssuer     = assetIssuer;
     SendAssetType   = sendAssetType;
     SendAssetCode   = sendAssetCode;
     SendAssetIssuer = sendAssetIssuer;
 }
Esempio n. 41
0
        protected virtual async Task<KeyPair> GetAccessToken(KeyPair requestToken, string oAuthVerifier)
        {
            var oauthClient = new OAuthClient(ApplicationInfo, requestToken);

            var resp = await oauthClient.Ajax(UrlGetAccessToken,
                parameters: new HttpParameters { { "oauth_verifier", oAuthVerifier } },
                dataType: DataType.UrlEncoded);

            return new KeyPair(
                key: resp.oauth_token,
                secret: resp.oauth_token_secret
            );
        }
Esempio n. 42
0
 public void TestSetup()
 {
     keyPair1 = new KeyPair(Wallet.GetPrivateKeyFromWIF("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"));
     sender = Contract.CreateSignatureRedeemScript(keyPair1.PublicKey).ToScriptHash();
     rpcClientMock = UT_TransactionManager.MockRpcClient(sender, new byte[0]);
 }
Esempio n. 43
0
 /// <summary>
 /// Collects edge data from the specified edges
 /// </summary>
 /// 
 /// <param name="edges">
 /// Edges whose data should be added to the collection
 /// </param>
 private void AddEdgeDataForMovedEdges(IEnumerable<IEdge> edges)
 {
     foreach (IEdge e in edges)
         if (!e.IsSelfLoop)
         {
             KeyPair key = new KeyPair(e.Vertices[0].ID, e.Vertices[1].ID);
             if (!movedEdgeGroupData.ContainsKey(key))
                 movedEdgeGroupData.Add(key, edgeGroupData[key]);
         }
 }
Esempio n. 44
0
        public void TestAutoSendAddress()
        {
            var test = CreateAPI();

            var simulator  = test.simulator;
            var owner      = test.owner;
            var testUser   = KeyPair.Generate();
            var autoSender = KeyPair.Generate();
            var receiver   = KeyPair.Generate();
            var node       = KeyPair.FromWIF(nodeWIF);
            var nexus      = simulator.Nexus;
            var api        = test.api;

            var symbol = Nexus.StakingTokenSymbol;

            var senderAddressStr    = Base16.Encode(autoSender.Address.PublicKey);
            var receivingAddressStr = Base16.Encode(receiver.Address.PublicKey);

            string[] scriptString = new string[]
            {
                $"alias r1, $triggerReceive",
                $"alias r2, $currentTrigger",
                $"alias r3, $comparisonResult",

                $@"load $triggerReceive, ""{AccountContract.TriggerReceive}""",
                $"pop $currentTrigger",

                $"equal $triggerReceive, $currentTrigger, $comparisonResult",
                $"jmpif $comparisonResult, @receiveHandler",

                $"jmp @end",

                $"@receiveHandler: nop",

                $"alias r4, $tokenContract",
                $"alias r5, $sourceAddress",
                $"alias r6, $targetAddress",
                $"alias r7, $receivedAmount",
                $"alias r8, $symbol",
                $"alias r9, $methodName",

                $"pop $symbol",
                $"pop $sourceAddress",
                $"pop $receivedAmount",

                $"load r11 0x{receivingAddressStr}",
                $"push r11",
                $@"extcall ""Address()""",
                $"pop $targetAddress",

                $@"load $methodName, ""TransferTokens""",

                $"push $receivedAmount",
                $"push $symbol",
                $"push $targetAddress",
                $"push $sourceAddress",
                $@"push $methodName",

                //switch to token contract
                $@"load r12, ""token""",
                $"ctx r12, $tokenContract",
                $"switch $tokenContract",

                $"@end: ret"
            };

            var script = AssemblerUtils.BuildScript(scriptString);

            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, autoSender.Address, simulator.Nexus.RootChain, Nexus.FuelTokenSymbol, 100000);
            simulator.GenerateCustomTransaction(autoSender, ProofOfWork.None,
                                                () => ScriptUtils.BeginScript().AllowGas(autoSender.Address, Address.Null, 1, 9999)
                                                .CallContract("account", "RegisterScript", autoSender.Address, script).SpendGas(autoSender.Address)
                                                .EndScript());
            simulator.EndBlock();


            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, autoSender.Address, simulator.Nexus.RootChain, symbol, 30000);
            simulator.EndBlock();

            var balance = simulator.Nexus.RootChain.GetTokenBalance(symbol, receiver.Address);

            Assert.IsTrue(balance == 30000);
        }
Esempio n. 45
0
        /// <summary>
        /// Collects data from the specified edge.
        /// Used for edges that already have control points metadata.
        /// </summary>
        /// 
        /// <param name="e">
        /// Edge to collect data from
        /// </param>
        private void AddExistingData(IEdge e)
        {
            EdgeGroupData ed;
            KeyPair key = new KeyPair(e.Vertices[0].ID, e.Vertices[1].ID);

            edgeGroupData.TryGetValue(key, out ed);

            if (ed == null)
            {
                PointF p1 = e.Vertices[0].Location;
                PointF p2 = e.Vertices[1].Location;
                ed = new EdgeGroupData();
                ed.v1 = p1;
                ed.v2 = p2;
                ed.id = key;
                PointF mid = VectorTools.MidPoint(p1, p2);
                ed.middle = mid;
                ed.length = VectorTools.Distance(p1, p2);

                ed.controlPoints = (PointF[])e.GetValue(ReservedMetadataKeys.PerEdgeIntermediateCurvePoints);

                if (subdivisionPoints == 0) subdivisionPoints = ed.controlPoints.Length;
                ed.newControlPoints = new PointF[subdivisionPoints];
                ed.k = springConstant * (subdivisionPoints + 1) / ed.length;
                if (ed.k > 0.5f) ed.k = 0.5f;
                //ed.edges = new HashSet<int>();
                ed.edgeCount = 0;
                ed.compatibleGroups = new Dictionary<KeyPair, GroupPairData>();
                edgeGroupData.Add(key, ed);
            }
            //ed.edges.Add(e.ID);
            ed.edgeCount++;
        }
Esempio n. 46
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (cc != null && cc.Length > 0)
            {
                bool findState = false;
                string endState = null;
                string state = "none";
                char tile = '\0';
                int mapWidth = -1;
                Dictionary<string, float> values = new Dictionary<string, float>();
                int numAnimals = 0;
                int oldPercent = -1;

                for (int i = 0; i < cc.Length; i++)
                {
                    string line = cc[i];
                    if (line == "--")
                    {
                        findState = true;
                        continue;
                    }

                    int percent = (int)(((float)i / (float)cc.Length) * 100);
                    if (percent != oldPercent)
                    {
                        oldPercent = percent;
                        worker.ReportProgress(percent);
                    }

                    if (findState)
                    {
                        findState = false;
                        endState = line;
                    }

                    if (state == null || state.Equals("none", StringComparison.CurrentCultureIgnoreCase) ||
                        state.Equals("TileData", StringComparison.CurrentCultureIgnoreCase))
                    {

                    }
                    else if (state.Equals("tiles", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (mCharCount < mColors.Length)
                        {
                            if (tile == '\0')
                            {
                                tile = line[0];
                            }
                            else
                            {
                                int t = int.Parse(line);
                                if (!mColourMap.ContainsKey(tile))
                                {
                                    Console.WriteLine("Adding char {0} with colour {1}", tile, mColors[t].ToKnownColor().ToString());
                                    mColourMap[tile] = mColors[t];
                                    //addColour(mColors[t], tile, true);
                                    mCharCount++;
                                    tile = '\0';
                                }
                            }
                        }
                    }
                    else if (state.Equals("options", StringComparison.CurrentCultureIgnoreCase))
                    {
                        switch (line)
                        {
                            case "current_time":
                                mCurrentTime = float.Parse(cc[++i]);
                                break;
                            case "current_day":
                                mCurrentDay = int.Parse(cc[++i]);
                                break;
                            case "day_length":
                                mDayLength = float.Parse(cc[++i]);
                                break;
                            default:
                                break;
                        }
                    }
                    else if (state.Equals("map", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (endState != null)
                        {
                            renderImage(ref mMapTotal);
                        }
                        else
                        {
                            if (mMapList.Count == 0)
                            {
                                mapWidth = line.Length;
                            }
                            mMapList.Add(line);
                        }
                    }
                    else if (state.Equals("entities", StringComparison.CurrentCultureIgnoreCase) ||
                                state.Equals("RemovedEntities", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (line == "Animal")
                        {
                            i++;
                            Animal a = new Animal();
                            a.load(ref cc, ref i);
                            i--;

                            string identifier = a.graphic.ToString() + '_' + a.species;
                            if (!mPopulations.ContainsKey(identifier))
                            {
                                mPopulations[identifier] = new PopulationStat();
                            }

                            if (a.isDead)
                            {
                                mPopulations[identifier].dead++;
                            }
                            else
                            {
                                mPopulations[identifier].alive++;
                            }
                        }
                    }
                    else if (state.Equals("history", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (line.Equals("DayEvent", StringComparison.CurrentCultureIgnoreCase))
                        {
                            DayEvents day = new DayEvents();
                            day.load(ref cc, ref i);
                            mHistory.Add(day);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unknown state {0}", state);
                    }

                    if (endState != null)
                    {
                        state = endState;
                        endState = null;
                    }
                }
                mValues = new List<KeyPair>();
                foreach (KeyValuePair<string, float> pair in values)
                {
                    float value = pair.Value / numAnimals;
                    KeyPair p = new KeyPair(pair.Key, value);
                    if (pair.Key.Equals("diet", StringComparison.CurrentCultureIgnoreCase))
                    {
                        p.max = 1.0f;
                    }
                    mValues.Add(p);
                }
            }
        }
Esempio n. 47
0
        private void Mine()
        {
            MinerInfo.minerStillRunning = true;


            var fromBiginteger  = new Org.BouncyCastle.Math.BigInteger(Helper.ConvertBigintegerHexToDecimal(from, hex));
            var untilBiginteger = new Org.BouncyCastle.Math.BigInteger(Helper.ConvertBigintegerHexToDecimal(until, hex));
            var difference      = fromBiginteger.Subtract(untilBiginteger).Abs();

            if (Helper.CompareNumbers(difference.ToString(), long.MaxValue.ToString()) > 0)
            {
                System.Windows.Forms.MessageBox.Show($"The length of job cant be more than {long.MaxValue}! Please use a smaller job length!");
                MinerInfo.minerStillRunning = false;
                return;
            }
            MinerInfo.lengthOfJob = Math.Abs(untilBiginteger.LongValue - fromBiginteger.LongValue);
            Task.Factory.StartNew(() =>
            {
                MinerInfo.minerThreadInfo = "Lookup size determine,generating hashset...";

                lookupSet = new HashSet <string>(10000);

                using (StreamReader sr = new StreamReader(path))
                {
                    while (sr.Peek() != -1)
                    {
                        lookupSet.Add(sr.ReadLine());
                    }
                }
                stopwatch.Start();
                MinerInfo.minerThreadInfo = "";
                MinerInfo.minerThreadInfo = "Lookup size determine, generating hashset done, mining...";

                while (fromBiginteger.CompareTo(untilBiginteger) < 0 && increment || fromBiginteger.CompareTo(untilBiginteger) > 0 && !increment)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    var key = KeyPair.Create(fromBiginteger, compressed);
                    if (lookupSet.Contains(key.AddressBase58))
                    {
                        MinerInfo.minerThreadInfo = $"Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}";
                        foundKeyCount++;
                        if (form.InvokeRequired)
                        {
                            form.Invoke((MethodInvoker) delegate { textBox.Text += $"{Environment.NewLine}Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}, privatekey: {key.PrivateKey}{Environment.NewLine}"; });
                        }
                        else
                        {
                        }
                        StreamWriter streamWriter = new StreamWriter("keys.txt", true);
                        string keyline            = $"Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}, privatekey: {key.PrivateKey}";
                        streamWriter.WriteLine(keyline);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    if (increment)
                    {
                        fromBiginteger = fromBiginteger.Add(new Org.BouncyCastle.Math.BigInteger("1"));
                    }
                    else
                    {
                        fromBiginteger = fromBiginteger.Add(new Org.BouncyCastle.Math.BigInteger("-1"));
                    }
                    MinerInfo.currentlyProcessed++;
                    MinerInfo.countOfTriedKeys++;
                    if (MinerInfo.currentlyProcessed % 1000 == 0)
                    {
                        MinerInfo.minerThreadInfo = $"Currently Processed number: {fromBiginteger.ToString()}";
                    }
                }
                //int lengthOfOneJob = 0;
                //if (MinerInfo.lengthOfJob > 10000)
                //{
                //    lengthOfOneJob = 10000;
                //}
                //else
                //{
                //    lengthOfOneJob = (int)MinerInfo.lengthOfJob;
                //}
                //StringBuilder stringBuilder = new StringBuilder(chars.Length);
                //for (int i = 0; i < chars.Length; i++)
                //{
                //    stringBuilder.Append(chars[0]);
                //}
                //List<string> sequenceList = new List<string>(lengthOfOneJob);
                //var list = GetAllMatches(chars.ToCharArray(), lengthOfString);
                //foreach (var item in list)
                //{
                //    if (cancellationToken.IsCancellationRequested)
                //    {
                //        break;
                //    }
                //    sequenceList.Add(item);
                //    if (sequenceList.Count == lengthOfOneJob)
                //    {
                //        LookupKeys(sequenceList);
                //        sequenceList.Clear();
                //    }
                //    MinerInfo.currentlyProcessed++;
                //    if (MinerInfo.currentlyProcessed >= MinerInfo.lengthOfJob && MinerInfo.lengthOfJob > 10000)
                //    {
                //        LookupKeys(sequenceList);
                //        break;
                //    }
                //}
                //int count = list.Count();

                MinerInfo.minerThreadResults = $"{Environment.NewLine}Found keys: {foundKeyCount}, ckecked numbers: {MinerInfo.countOfTriedKeys} {Environment.NewLine}Additional data: - Combinations: {MinerInfo.lengthOfJob}, elapsed time: {stopwatch.Elapsed}, keys/second: {MinerInfo.countOfTriedKeys / stopwatch.Elapsed.TotalSeconds}";
                Dispose();
                MinerInfo.minerStillRunning = false;
            }, TaskCreationOptions.LongRunning);
        }
Esempio n. 48
0
        public void TestIndexGap()
        {
            var test = CreateAPI();

            var simulator = test.simulator;
            var owner     = test.owner;
            var sender    = KeyPair.Generate();
            var receiver  = KeyPair.Generate();
            var node      = KeyPair.FromWIF(nodeWIF);
            var nexus     = simulator.Nexus;
            var api       = test.api;

            var contractAddress = simulator.Nexus.FindContract("relay").Address;

            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000);
            simulator.EndBlock();

            TopUpChannel(simulator, sender, 1000000);

            var indexGap     = 5;
            var messageCount = 3;
            var messages     = new RelayMessage[messageCount];

            var random = new Random();

            for (int i = 0; i < messageCount; i++)
            {
                var script = new byte[100];
                random.NextBytes(script);

                var message = new RelayMessage
                {
                    nexus     = nexus.Name,
                    index     = i * indexGap,
                    receiver  = receiver.Address, //node.Address,
                    script    = script,
                    sender    = sender.Address,
                    timestamp = Timestamp.Now
                };
                messages[i] = message;

                var    receipt       = RelayReceipt.FromMessage(message, sender);
                string serializedHex = Base16.Encode(receipt.Serialize());

                api.RelaySend(serializedHex);
            }

            var receipts = (ArrayResult)api.RelayReceive(receiver.Address.Text);

            Assert.IsTrue(receipts.values.Length == messageCount);

            for (int i = 0; i < messageCount; i++)
            {
                var obj = receipts.values[i];
                Assert.IsTrue(obj is ReceiptResult);

                var receiptResult = (ReceiptResult)obj;
                Assert.IsTrue(receiptResult.nexus == messages[i].nexus);
                Assert.IsTrue(new BigInteger(receiptResult.index, 10) == messages[i].index);
                //Assert.IsTrue(receiptResult.receiver == messages[i].receiver);
                //Assert.IsTrue(receiptResult.script == messages[i].script);
                //Assert.IsTrue(receiptResult.sender == messages[i].sender);
                Assert.IsTrue(receiptResult.timestamp == messages[i].timestamp);
            }

            var lastMessage = messages[messageCount - 1];
            var lastReceipt = RelayReceipt.FromMessage(lastMessage, sender);

            var senderInitialBalance   = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, sender.Address);
            var chainInitialBalance    = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, contractAddress);
            var receiverInitialBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, node.Address);

            simulator.BeginBlock();
            var tx = simulator.GenerateCustomTransaction(sender, ProofOfWork.None, () =>
                                                         ScriptUtils.BeginScript().AllowGas(sender.Address, Address.Null, 1, 9999)
                                                         .CallContract("relay", "UpdateChannel", lastReceipt).
                                                         SpendGas(sender.Address).EndScript());

            simulator.EndBlock();

            var txCost = simulator.Nexus.RootChain.GetTransactionFee(tx);

            var senderFinalBalance   = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, sender.Address);
            var chainFinalBalance    = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, contractAddress);
            var receiverFinalBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, receiver.Address);

            var expectedFee = RelayFeePerMessage * (lastReceipt.message.index + 1);

            Assert.IsTrue(senderFinalBalance == senderInitialBalance - txCost);
            Assert.IsTrue(receiverFinalBalance == receiverInitialBalance + (expectedFee / 2));
            Assert.IsTrue(chainFinalBalance == chainInitialBalance - (expectedFee / 2));    //the sender's balance is escrowed in the chain address, so the chain just sends the other half of the fee away to the receiver
        }
Esempio n. 49
0
 public void Remove(KeyPair kp)
 {
     m_allkey.Remove(kp);
 }
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            // Remove any spaces or dashes from the encrypted key (in case they were typed)
            txtEncrypted.Text = txtEncrypted.Text.Replace("-", "").Replace(" ", "");

            if (txtEncrypted.Text == "" || txtPassphrase.Text == "") {
                MessageBox.Show("Enter an encrypted key and its passphrase.", "Entries Required", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // What were we given as encrypted text?

            object encrypted = StringInterpreter.Interpret(txtEncrypted.Text);

            if (encrypted == null) {
                if (txtEncrypted.Text.StartsWith("cfrm38")) {
                    var r = MessageBox.Show("This is not a private key.  This looks like a confirmation code.  " +
                        "Do you want to open the Confirmation Code Validator?", "Invalid private key", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                    if (r == DialogResult.Yes) {
                        Program.ShowConfValidator();
                    }
                    return;
                }

                string containsL = "";
                if (txtEncrypted.Text.Contains("l")) {
                    containsL = " Your entry contains the lowercase letter l.  Private keys are far " +
                        "more likely to contain the digit 1, and not the lowercase letter l.";
                }

                MessageBox.Show("The private key entry (top box) was invalid.  " +
                    "Please verify the private key was properly typed." + containsL, "Invalid private key", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;

            } if (encrypted is PassphraseKeyPair) {
                PassphraseKeyPair pkp = encrypted as PassphraseKeyPair;
                if (pkp.DecryptWithPassphrase(txtPassphrase.Text) == false) {
                    MessageBox.Show("The passphrase is incorrect.", "Could not decrypt", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                MessageBox.Show("Decryption successful.", "Decryption", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Program.ShowAddressUtility();
                Program.AddressUtility.DisplayKeyCollectionItem(new KeyCollectionItem(pkp.GetUnencryptedPrivateKey()));
                return;
            } else if (encrypted is KeyPair) {
                // it's unencrypted - perhaps we're doing an EC multiply and the passphrase is a private key.

                object encrypted2 = StringInterpreter.Interpret(txtPassphrase.Text);
                if (encrypted2 == null) {
                    var r = MessageBox.Show("Does the key you entered belong to the following address?: " + (encrypted as KeyPair).AddressBase58,
                        "Key appears unencrypted",
                        MessageBoxButtons.YesNo);

                    if (r == DialogResult.Yes) {
                        r = MessageBox.Show("Then this key is already unencrypted and you don't need to decrypt it.  " +
                            "Would you like to open it in the Address Utility screen to see its various forms?", "Key is not encrypted", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        if (r == DialogResult.Yes) {
                            Program.ShowAddressUtility();
                            Program.AddressUtility.DisplayKeyCollectionItem(new KeyCollectionItem(encrypted as KeyPair));
                        }
                    } else {
                        MessageBox.Show("The passphrase or secondary key is incorrect.  Please verify it was properly typed.", "Second entry is not a valid private key", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    return;
                }

                BigInteger n1 = new BigInteger(1, (encrypted as KeyPair).PrivateKeyBytes);
                BigInteger n2 = new BigInteger(1, (encrypted2 as KeyPair).PrivateKeyBytes);
                var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
                BigInteger privatekey = n1.Multiply(n2).Mod(ps.N);
                MessageBox.Show("Keys successfully combined using EC multiplication.", "EC multiplication successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (n1.Equals(n2)) {
                    MessageBox.Show("The two key entries have the same public hash.  The results you see might be wrong.", "Duplicate key hash", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // use private key
                KeyPair kp = new KeyPair(privatekey);
                Program.ShowAddressUtility();
                Program.AddressUtility.DisplayKeyCollectionItem(new KeyCollectionItem(kp));

            } else if (encrypted is AddressBase) {
                MessageBox.Show("This is not a private key.  It looks like an address or a public key.  Private keys usually start with 5, 6, or S.", "Not a private key", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            } else {
                MessageBox.Show("This is not a private key that this program can decrypt.", "Not a recognized private key", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Esempio n. 51
0
        private void btnGenerateSpecific_Click(object sender, EventArgs e)
        {
            KeyPair k = null;

            try {
                k = new KeyPair(txtPrivKey.Text);
                targetPrivKey = k.PrivateKeyBytes;

            } catch (Exception) {
                MessageBox.Show("Not a valid private key.");
            }

            btnGenerate_Click(sender, e);
            targetPrivKey = null;
        }
Esempio n. 52
0
 public void AddPair(Keys k1, Keys k2)
 {
     KeyPair kp = new KeyPair(k1, k2);
     //TODO: allow multiple identical keys (PropList)
     if (!this.m_slPairs.ContainsKey(k1))
         this.m_slPairs.Add(k1, kp);
     if (!this.m_slPairs.ContainsKey(k2))
         this.m_slPairs.Add(k2, kp);
 }
        private void btnCombine_Click(object sender, EventArgs e)
        {
            // What is input #1?

            string input1 = txtInput1.Text;
            string input2 = txtInput2.Text;
            PublicKey pub1 = null, pub2 = null;
            KeyPair kp1 = null, kp2 = null;

            if (KeyPair.IsValidPrivateKey(input1)) {
                pub1 = kp1 = new KeyPair(input1);
            } else if (PublicKey.IsValidPublicKey(input1)) {
                pub1 = new PublicKey(input1);
            } else {
                MessageBox.Show("Input key #1 is not a valid Public Key or Private Key Hex", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (KeyPair.IsValidPrivateKey(input2)) {
                pub2 = kp2 = new KeyPair(input2);
            } else if (PublicKey.IsValidPublicKey(input2)) {
                pub2 = new PublicKey(input2);
            } else {
                MessageBox.Show("Input key #2 is not a valid Public Key or Private Key Hex", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (kp1 == null && kp2 == null && rdoAdd.Checked == false) {
                MessageBox.Show("Can't multiply two public keys.  At least one of the keys must be a private key.",
                    "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (pub1.IsCompressedPoint != pub2.IsCompressedPoint) {
                MessageBox.Show("Can't combine a compressed key with an uncompressed key.", "Can't combine", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (pub1.AddressBase58 == pub2.AddressBase58) {
                if (MessageBox.Show("Both of the key inputs have the same public key hash.  You can continue, but " +
                   "the results are probably going to be wrong.  You might have provided the wrong " +
                   "information, such as two parts from the same side of the transaction, instead " +
                    "of one part from each side.  Continue anyway?", "Duplicate Key Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) {
                    return;
                }

            }

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");

            // Combining two private keys?
            if (kp1 != null && kp2 != null) {

                BigInteger e1 = new BigInteger(1, kp1.PrivateKeyBytes);
                BigInteger e2 = new BigInteger(1, kp2.PrivateKeyBytes);
                BigInteger ecombined = (rdoAdd.Checked ? e1.Add(e2) : e1.Multiply(e2)).Mod(ps.N);

                System.Diagnostics.Debug.WriteLine(kp1.PublicKeyHex);
                System.Diagnostics.Debug.WriteLine(kp2.PublicKeyHex);
                KeyPair kpcombined = new KeyPair(Util.Force32Bytes(ecombined.ToByteArrayUnsigned()), compressed: kp1.IsCompressedPoint);

                txtOutputAddress.Text = kpcombined.AddressBase58;
                txtOutputPubkey.Text = kpcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = kpcombined.PrivateKeyBase58;

            } else if (kp1 != null || kp2 != null) {
                // Combining one public and one private

                KeyPair priv = (kp1 == null) ? kp2 : kp1;
                PublicKey pub = (kp1 == null) ? pub1 : pub2;

                ECPoint point = pub.GetECPoint();

                ECPoint combined = rdoAdd.Checked ? point.Add(priv.GetECPoint()) : point.Multiply(new BigInteger(1, priv.PrivateKeyBytes));
                ECPoint combinedc = ps.Curve.CreatePoint(combined.X.ToBigInteger(), combined.Y.ToBigInteger(), priv.IsCompressedPoint);
                PublicKey pkcombined = new PublicKey(combinedc.GetEncoded());
                txtOutputAddress.Text = pkcombined.AddressBase58;
                txtOutputPubkey.Text = pkcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = "Only available when combining two private keys";
            } else {
                // Adding two public keys
                ECPoint combined = pub1.GetECPoint().Add(pub2.GetECPoint());
                ECPoint combinedc = ps.Curve.CreatePoint(combined.X.ToBigInteger(), combined.Y.ToBigInteger(), pub1.IsCompressedPoint);
                PublicKey pkcombined = new PublicKey(combinedc.GetEncoded());
                txtOutputAddress.Text = pkcombined.AddressBase58;
                txtOutputPubkey.Text = pkcombined.PublicKeyHex.Replace(" ", "");
                txtOutputPriv.Text = "Only available when combining two private keys";
            }
        }
Esempio n. 54
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Enabled)
            {
                int n = 0;

                if (Int32.TryParse(textBox2.Text, out n) == false) n = 0;
                if (n < 1 || n > 9999) {
                    MessageBox.Show("Please enter a number of addresses between 1 and 9999", "Invalid entry");
                    return;
                }

                if (txtPassphrase.Text.Length < 20)
                {

                    if (MessageBox.Show("Your passphrase is too short (< 20 characters). If you generate this wallet it may be easily compromised. Are you sure you'd like to use this passphrase?", "Passphrase too short", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }

                }

                if (Util.PassphraseTooSimple(txtPassphrase.Text))
                {

                    if (MessageBox.Show("Your passphrase is too simple. If you generate this wallet it may be easily compromised. Are you sure you'd like to use this passphrase?", "Passphrase too simple", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }

                }

                StringBuilder wallet = new StringBuilder();

                bool CSVmode = cboOutputType.Text.Contains("CSV");
                bool ScriptMode = cboOutputType.Text.Contains("Import script");
                bool ShowHelpText = cboOutputType.Text.Contains("Normal");

                if (ShowHelpText) {
                    wallet.AppendLine("Paper Bitcoin Wallet.  Keep private, do not lose, do not allow anyone to make a copy.  Anyone with the passphrase or private keys can steal your funds.\r\n");

                    wallet.AppendLine("Passphrase was:");
                    wallet.AppendLine(txtPassphrase.Text);
                    wallet.AppendLine("Freely give out the Bitcoin address.  The private key after each address is the key needed to unlock funds sent to the Bitcoin address.\r\n");

                }
                progressBar1.Maximum = n;
                progressBar1.Minimum = 0;
                progressBar1.Visible = true;
                label3.Text = "Progress:";
                button1.Enabled = false;

                for (int i = 1; i <= n; i++)
                {
                    Application.DoEvents();

                    string privatestring;
                    switch (GenerationFormula) {
                        case 1:
                            privatestring = txtPassphrase.Text + i.ToString();
                            break;
                        default:
                            privatestring = i.ToString() + "/" + txtPassphrase.Text + "/" + i.ToString() + "/BITCOIN";
                            break;
                    }
                    byte[] privatekey = Util.ComputeSha256(privatestring);

                    KeyPair kp = new KeyPair(privatekey);

                    string bytestring = kp.PrivateKeyHex;
                    string PrivWIF = kp.PrivateKeyBase58;
                    string PubHex = kp.PublicKeyHex;
                    string Address = kp.AddressBase58;

                    if (CSVmode) {
                        wallet.AppendFormat("{0},\"{1}\",\"{2}\"\r\n", i, Address, PrivWIF);
                    } else if (ScriptMode) {
                        wallet.AppendFormat("# {0}: {1}\"\r\n./bitcoind importprivkey {2}\r\n", i, Address, PrivWIF);
                    } else {
                        wallet.AppendFormat("Bitcoin Address #{0}: {1}\r\n", i, Address);
                        wallet.AppendFormat("Private Key: {0}\r\n\r\n", PrivWIF);
                    }

                    progressBar1.Value = i;
                }

                txtWallet.Text = wallet.ToString();

                progressBar1.Value = 0;
                progressBar1.Visible = false;
                label3.Text = "Passphrase:";
                button1.Enabled = true;
            }
        }
Esempio n. 55
0
        private static void OnReceiveServer(byte[] buffer, int size)
        {
            if (_keyPairClient == null && _keyPairServer == null)
            {
                var reader = new BinaryReader(new MemoryStream(buffer, 0, size));
                Debug.Assert(reader.ReadUInt32() == 8);

                var seed = reader.ReadInt32();
                _keyPairClient = new KeyPair(seed);
                _keyPairServer = new KeyPair(seed);
            }
            else
            {
                var newBuffer = new byte[buffer.Length];
                buffer.CopyTo(newBuffer, 0);

                _keyPairServer.Decrypt(ref newBuffer, 0, size);

                //Dump(newBuffer, size, "server.txt");
                DumpInfo(newBuffer);
            }

            _server.BeginSend(buffer, 0, size, SocketFlags.None, ar => _server.EndSend(ar), _server);
        }
Esempio n. 56
-1
 public KeyPair Add(string name, KeyType type)
 {
     KeyPair kp = new KeyPair();
     kp.name = name;
     kp.type = type;
     kp.index = m_allkey.Count;
     m_allkey.Add(kp);
     return kp;
 }
Esempio n. 57
-1
 public abstract void StoreKeyValuePairs(KeyPair[] keypairs);