Exemplo n.º 1
0
        public void TestGetTransactionsToApproveReturnsDataShouldMapToHashes()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <GetTransactionsToApproveResponse>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <GetTransactionsToApproveResponse>
                {
                    StatusCode = HttpStatusCode.OK,
                    Data       =
                        new GetTransactionsToApproveResponse
                    {
                        BranchTransaction =
                            "TKGDZ9GEI9CPNQGHEATIISAKYPPPSXVCXBSR9EIWCTHHSSEQCD9YLDPEXYERCNJVASRGWMAVKFQTC9999",
                        TrunkTransaction =
                            "ASDFZ9GEI9CPNQGHEATIISAKYPPPSXVCXBSR9EIWCTHHSSEQCD9YLDPEXYERCNJVASRGWMAVKFQTC9999",
                        Duration = 1000
                    }
                };
                return(restResponse);
            });

            var repository            = new RestIotaRepository(restClientMock.Object);
            var transactionsToApprove = repository.GetTransactionsToApprove();

            Assert.AreEqual(
                "TKGDZ9GEI9CPNQGHEATIISAKYPPPSXVCXBSR9EIWCTHHSSEQCD9YLDPEXYERCNJVASRGWMAVKFQTC9999",
                transactionsToApprove.BranchTransaction.Value);
            Assert.AreEqual(
                "ASDFZ9GEI9CPNQGHEATIISAKYPPPSXVCXBSR9EIWCTHHSSEQCD9YLDPEXYERCNJVASRGWMAVKFQTC9999",
                transactionsToApprove.TrunkTransaction.Value);
            Assert.AreEqual(1000, transactionsToApprove.Duration);
        }
        /// <summary>
        /// Uploads the object to the specified SendTo address inside the object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T Upload <T>(this T obj) where T : IDownloadable
        {
            if (!obj.IsFinalized)
            {
                throw new ArgumentException("object not finalized");
            }

            //prepare data
            var json = TangleNet::TryteString.FromUtf8String(Utils.ToJSON(obj));

            //send json to address
            var repository = new RestIotaRepository(new RestClient(obj.NodeAddress), new PoWService(new CpuPearlDiver()));

            var bundle = new TangleNet::Bundle();

            bundle.AddTransfer(
                new TangleNet::Transfer
            {
                Address   = new TangleNet::Address(obj.SendTo),
                Tag       = new TangleNet::Tag("TANGLECHAIN"),
                Message   = json,
                Timestamp = Timestamp.UnixSecondsTimestamp
            });

            bundle.Finalize();
            bundle.Sign();

            repository.SendTrytes(bundle.Transactions, 2, 14);

            return(obj);
        }
Exemplo n.º 3
0
        public void TestUsernameAndPasswordIsGivenShouldSetAuthenticator()
        {
            var client = new RestClient();
            var repo   = new RestIotaRepository(client, null, "test", "password");

            Assert.IsNotNull(client.Authenticator);
        }
Exemplo n.º 4
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            var repository = new RestIotaRepository(new RestClient("https://field.deviota.com:443"), new PoWSrvService());

            var bundle = new Bundle();

            bundle.AddTransfer(new Transfer
            {
                Address   = new Address(Hash.Empty.Value),
                Tag       = new Tag("MYCSHARPPI"),
                Timestamp = Timestamp.UnixSecondsTimestamp,
                Message   = TryteString.FromUtf8String("Hello from PiDiver #1!")
            });

            bundle.AddTransfer(new Transfer
            {
                Address   = new Address(Hash.Empty.Value),
                Tag       = new Tag("MYCSHARPPI"),
                Timestamp = Timestamp.UnixSecondsTimestamp,
                Message   = TryteString.FromUtf8String("Hello from PiDiver #2!")
            });

            bundle.Finalize();
            bundle.Sign();

            repository.SendTrytes(bundle.Transactions);


            Console.WriteLine("Done");
            Console.ReadKey();
        }
        public void TestGetBalancesShouldIncludeAllParameters()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <AddressBalances>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <AddressBalances>
                {
                    Data =
                        new AddressBalances
                    {
                        Balances = new List <long> {
                            10000
                        },
                        Duration       = 100,
                        MilestoneIndex = 38274234,
                        References     = new List <string> {
                            "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB"
                        }
                    }
                };
                return(restResponse);
            });

            var repository = new RestIotaRepository(restClientMock.Object);
            var balances   = repository.GetBalances(new List <string> {
                "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB"
            }, 100);

            Assert.AreEqual(10000, balances.Balances[0]);
            Assert.AreEqual(100, balances.Duration);
            Assert.AreEqual(38274234, balances.MilestoneIndex);
            Assert.AreEqual("RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB", balances.References[0]);
        }
Exemplo n.º 6
0
        public void TestFindTransactionsDoesNotContainParametersShouldThrowException()
        {
            var restClientMock = new Mock <IRestClient>();
            var repository     = new RestIotaRepository(restClientMock.Object);

            repository.FindTransactions(new Dictionary <string, IEnumerable <TryteString> >());
        }
        public void TestGetTransactionsByAddressesShouldIncludeAllParameters()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <Transactions>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <Transactions>
                {
                    Data =
                        new Transactions
                    {
                        Hashes = new List <string>
                        {
                            "EJEAOOZYSAWFPZQESYDHZCGYNSTWXUMVJOVDWUNZJXDGWCLUFGIMZRMGCAZGKNPLBRLGUNYWKLJTYEAQX"
                        }
                    }
                };
                return(restResponse);
            });

            var repository   = new RestIotaRepository(restClientMock.Object);
            var transactions = repository.GetTransactionsByAddresses(new List <string> {
                "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB"
            });

            Assert.AreEqual("EJEAOOZYSAWFPZQESYDHZCGYNSTWXUMVJOVDWUNZJXDGWCLUFGIMZRMGCAZGKNPLBRLGUNYWKLJTYEAQX", transactions.Hashes[0]);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            string basePath   = Path.Combine(Environment.CurrentDirectory, "..", "..");
            string resultText = File.ReadAllText(Path.Combine(basePath, "result.txt"));
            var    repository = new RestIotaRepository(new RestClient("https://nodes.testnet.iota.org:443"));

            string message = resultText;
            //string message = "blubber" + DateTime.Now.Ticks;
            //string message =
            //    "1These homomorphic encryption schemes are based on a hard computation problem known as Ring Learning with Errors. Here we will unpack what the Ring part of that title means. Essentially, data in these schemes is represented by polynomials both when it is encrypted (the ciphertext) and when it is unencrypted (the plaintext)." +
            //    "2These are almost the normal polynomials that everyone studies at school. Things like There are some differences, the first being that the coefficients are all whole numbers and are the remainder relative to some other whole number (that is ). Say , then this is like a 24 hour clock, where adding 6 hours to 21 takes you to 3. All the coefficients of the polynomials are treated like this." +
            //    "3Alternately, we can consider the numbers to range from -11 to 12, allowing us to negate numbers conveniently. Note that this is just a convenience factor - there is no difference between a \"remainder\" of -1 and a remainder of 23 (when dividing by 24)." +
            //    "4The second, and trickier, thing that is different about these polynomials is that this idea of using remainders applies not just to the coefficients of the polynomials, but also to the polynomials themselves." +
            //    "5We define a special polynomial called the polynomial modulus, and only consider the remainder of polynomials when they have been divided by this polynomial modulus. The specific form of this polynomial modulus in the FV scheme is where for some . For illustration here we will take , so the polynomial is ." +
            //    "6Because we are considering remainders with respect to , we only have to consider polynomials with powers from to . Any larger powers will be reduced by division by the polynomial modulus. This can also be understood by considering that , meaning that can be replaced by -1 to reduce the larger powers of into the range 0 to 15.";

            //const string address = "FHEBLOCKCHAINEDMOBILITYHACKATHONTHEBLOCKCHAINEDMOBILITYHACKATHONTHEBLOCKCHAINEDMO";
            //SendToChain(address, repository, message);

            const string address = "IOTAFFBLOCKCHAINEDMOBILITYHACKATHONTHEBLOCKCHAINEDMOBILITYHACKATHONTHEBLOCKCHAINE";

            SendToChain(address, repository, message);
            GetFromChain(address, repository);
            Console.ReadKey();
        }
Exemplo n.º 9
0
        public void TestGetInputsHasInvalidBoundShouldThrowException()
        {
            var restClientMock = new Mock <IRestClient>();
            var repository     = new RestIotaRepository(restClientMock.Object);

            repository.GetInputs(Seed.Random(), 100, SecurityLevel.Medium, 10, 5);
        }
Exemplo n.º 10
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            var repository = new RestIotaRepository(
                new FallbackIotaClient(
                    new List <string>
            {
                "https://invalid.node.com:443",
                "https://peanut.iotasalad.org:14265",
                "http://node04.iotatoken.nl:14265",
                "http://node05.iotatoken.nl:16265",
                "https://nodes.thetangle.org:443",
                "http://iota1.heidger.eu:14265",
                "https://nodes.iota.cafe:443",
                "https://potato.iotasalad.org:14265",
                "https://durian.iotasalad.org:14265",
                "https://turnip.iotasalad.org:14265",
                "https://nodes.iota.fm:443",
                "https://tuna.iotasalad.org:14265",
                "https://iotanode2.jlld.at:443",
                "https://node.iota.moe:443",
                "https://wallet1.iota.town:443",
                "https://wallet2.iota.town:443",
                "http://node03.iotatoken.nl:15265",
                "https://node.iota-tangle.io:14265",
                "https://pow4.iota.community:443",
                "https://dyn.tangle-nodes.com:443",
                "https://pow5.iota.community:443",
            },
                    5000),
                new PoWSrvService());

            var bundle = new Bundle();

            bundle.AddTransfer(
                new Transfer
            {
                Address   = new Address(Hash.Empty.Value),
                Tag       = new Tag("MYCSHARPPI"),
                Timestamp = Timestamp.UnixSecondsTimestamp,
                Message   = TryteString.FromUtf8String("Hello from PiDiver #1!")
            });

            bundle.AddTransfer(
                new Transfer
            {
                Address   = new Address(Hash.Empty.Value),
                Tag       = new Tag("MYCSHARPPI"),
                Timestamp = Timestamp.UnixSecondsTimestamp,
                Message   = TryteString.FromUtf8String("Hello from PiDiver #2!")
            });

            bundle.Finalize();
            bundle.Sign();

            repository.SendTrytes(bundle.Transactions, 1);

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 11
0
        public List <ChatEntry> GetChat(Connections conn)
        {
            List <ChatEntry> chatEntrys = new List <ChatEntry>();

            User User_A = _context.User.Single(m => m.Name.Equals(conn.UserA_.Name));
            User User_B = _context.User.Single(m => m.Name.Equals(conn.UserB_.Name));

            User local = HttpContext.Session.GetObjectFromJson <User>("User");

            var repository = new RestIotaRepository(new RestClient("https://field.carriota.com:443"), new PoWService(new CpuPowDiver()));

            //set refresh bools
            if (conn.UserA_.Name.Equals(local.Name))
            {
                conn.Refresh_A = false;
            }
            else
            {
                conn.Refresh_B = false;
            }

            //updating entry
            _context.Connections.Update(conn);
            _context.SaveChanges();

            //setting addresses to check for new messages
            List <Address> addresses = new List <Address>()
            {
                new Address(conn.AddressA),
                new Address(conn.AddressB)
            };

            //doing now tangle stuff
            var hashList = repository.FindTransactionsByAddresses(addresses);

            List <Bundle> bundles = repository.GetBundles(hashList.Hashes, true);

            foreach (Bundle b in bundles)
            {
                string entryName = "";

                if (b.Transactions[0].Address.ToString() == conn.AddressA)
                {
                    entryName = conn.UserB_.Name;
                }
                else
                {
                    entryName = conn.UserA_.Name;
                }

                ChatEntry entry = new ChatEntry(b, entryName, conn.EncryptionKey);
                chatEntrys.Add(entry);
            }

            List <ChatEntry> sortedList = chatEntrys.OrderBy(o => o.TimeStamp).ToList();

            return(sortedList);
        }
Exemplo n.º 12
0
        public void TestGetNodeInfoShouldIncludeAllParameters()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <NodeInfo>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <NodeInfo>
                {
                    StatusCode = HttpStatusCode.OK,
                    Data       =
                        new NodeInfo
                    {
                        AppName                = "IRI",
                        AppVersion             = "1.4.1.1",
                        Duration               = 0,
                        JreAvailableProcessors = 4,
                        JreFreeMemory          = 1433752216,
                        JreMaxMemory           = 4294967296,
                        JreTotalMemory         = 4294967296,
                        LatestMilestone        =
                            "MWBOADDZVATGJWCZSEQSPJSEEMGROZOGEERYBTIBZIKTJTXGNKMKWDFKIJOAKEPEJBGEMZLE9UVCA9999",
                        LatestMilestoneIndex          = 325116,
                        LatestSolidSubtangleMilestone =
                            "MWBOADDZVATGJWCZSEQSPJSEEMGROZOGEERYBTIBZIKTJTXGNKMKWDFKIJOAKEPEJBGEMZLE9UVCA9999",
                        LatestSolidSubtangleMilestoneIndex = 325116,
                        Neighbors             = 6,
                        PacketsQueueSize      = 0,
                        Time                  = 1515707837727,
                        Tips                  = 5946,
                        TransactionsToRequest = 550
                    }
                };
                return(restResponse);
            });

            var repository = new RestIotaRepository(restClientMock.Object);
            var nodeInfo   = repository.GetNodeInfo();

            Assert.AreEqual("IRI", nodeInfo.AppName);
            Assert.AreEqual("1.4.1.1", nodeInfo.AppVersion);
            Assert.AreEqual(0, nodeInfo.Duration);
            Assert.AreEqual(4, nodeInfo.JreAvailableProcessors);
            Assert.AreEqual(1433752216, nodeInfo.JreFreeMemory);
            Assert.AreEqual(4294967296, nodeInfo.JreMaxMemory);
            Assert.AreEqual(4294967296, nodeInfo.JreTotalMemory);
            Assert.AreEqual("MWBOADDZVATGJWCZSEQSPJSEEMGROZOGEERYBTIBZIKTJTXGNKMKWDFKIJOAKEPEJBGEMZLE9UVCA9999", nodeInfo.LatestMilestone);
            Assert.AreEqual(325116, nodeInfo.LatestMilestoneIndex);
            Assert.AreEqual("MWBOADDZVATGJWCZSEQSPJSEEMGROZOGEERYBTIBZIKTJTXGNKMKWDFKIJOAKEPEJBGEMZLE9UVCA9999", nodeInfo.LatestSolidSubtangleMilestone);
            Assert.AreEqual(325116, nodeInfo.LatestSolidSubtangleMilestoneIndex);
            Assert.AreEqual(6, nodeInfo.Neighbors);
            Assert.AreEqual(0, nodeInfo.PacketsQueueSize);
            Assert.AreEqual(1515707837727, nodeInfo.Time);
            Assert.AreEqual(5946, nodeInfo.Tips);
            Assert.AreEqual(550, nodeInfo.TransactionsToRequest);
        }
Exemplo n.º 13
0
        public void TestFindTransactionsParametersIncludeInvalidParameterNamesShouldThrowException()
        {
            var restClientMock = new Mock <IRestClient>();
            var repository     = new RestIotaRepository(restClientMock.Object);

            repository.FindTransactions(
                new Dictionary <string, IEnumerable <TryteString> > {
                { "invalid", new List <TryteString>() }
            });
        }
Exemplo n.º 14
0
        public ClaimsService(ILogger <ClaimsService> logger)
        {
            m_logger = logger;
            // Connect to a node on one of the main networks.
            var iotaRepositoryUrl = Environment.GetEnvironmentVariable("IOTA_REPOSITORY");

            m_logger.LogInformation($"Using IOTA_REPOSITORY={iotaRepositoryUrl}");
            m_restIotaRepository            = new RestIotaRepository(new RestClient(iotaRepositoryUrl));
            m_mamChannelFactory             = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, m_restIotaRepository);
            m_mamChannelSubscriptionFactory = new MamChannelSubscriptionFactory(m_restIotaRepository, CurlMamParser.Default, CurlMask.Default);
        }
Exemplo n.º 15
0
        public void TestGetTransactionsToApproveDoesNotReturnHttpStatusOkShouldWrapInException()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <GetTransactionsToApproveResponse>(It.IsAny <IRestRequest>()))
            .Returns(new RestResponse <GetTransactionsToApproveResponse> {
                StatusCode = HttpStatusCode.InternalServerError, Data = null
            });

            var repository = new RestIotaRepository(restClientMock.Object);

            repository.GetTransactionsToApprove();
        }
Exemplo n.º 16
0
        private static void GetFromChain(string address, RestIotaRepository repository)
        {
            int depth = 3;
            int minWeightMagnitude = 9;

            try
            {
                TransactionHashList transactionsByAdress =
                    repository.FindTransactionsByAddresses(new List <Address> {
                    new Address(address)
                });

                List <TransactionTrytes> transactionsTrytesList = repository.GetTrytes(transactionsByAdress.Hashes);

                Dictionary <int, Transaction> transactionPosition = new Dictionary <int, Transaction>();
                int lastIndex = 0;
                //foreach (Hash hash in transactionsByAdress.Hashes)
                //{
                foreach (TransactionTrytes transactionTrytes in transactionsTrytesList)
                {
                    Transaction transactionOne = Transaction.FromTrytes(transactionTrytes, transactionsByAdress.Hashes[0]);
                    transactionPosition.Add(transactionOne.CurrentIndex, transactionOne);
                    lastIndex = transactionOne.LastIndex;
                }
                //}

                string combined = string.Empty;
                for (int i = 0; i < lastIndex; i++)
                {
                    combined += transactionPosition[i].Fragment.Value;
                }

                string fertisch = TrytesToString(combined);
                Console.WriteLine(fertisch + " positiv");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                //throw;
            }

            //Hash hashAddress = new Hash(transactionsByAdress.Hashes[0].Value);
            //TransactionHashList bundleTransactions = repository.FindTransactionsByBundles(new List<Hash> {bundle.Hash});
            //foreach (Hash transactionsHash in bundleTransactions.Hashes)
            //{
            //    Hash hash = new Hash(transactionsHash.Value);
            //    var transactionsTrytes = repository.GetTrytes(bundleTransactions.Hashes);
            //    var transaction = Transaction.FromTrytes(transactionsTrytes[0], hash);
            //}
        }
Exemplo n.º 17
0
        public ActionResult SendMessage(string Message)
        {
            //connection to a iota node
            var repository = new RestIotaRepository(new RestClient("http://node04.iotatoken.nl:14265"), new PoWService(new CpuPowDiver()));

            User sender = HttpContext.Session.GetObjectFromJson <User>("User");

            Connections connection = HttpContext.Session.GetObjectFromJson <Connections>("SelectedConnection");

            //set refresh bools
            if (connection.UserA_.Name.Equals(sender.Name))
            {
                connection.Refresh_B = true;
            }
            else
            {
                connection.Refresh_A = true;
            }

            //updating entry
            _context.Connections.Update(connection);
            _context.SaveChanges();

            string sendingAddress = (connection.UserA_.UserID == sender.UserID) ? connection.AddressB : connection.AddressA;

            string encryptedMsg = Utility.EncryptString(Message, connection.EncryptionKey);

            Transfer trans = new Transfer()
            {
                Address = new Address(sendingAddress)
                {
                    Balance = 0
                },
                Message   = TryteString.FromAsciiString(encryptedMsg),
                Tag       = new Tag("CSHARP"),
                Timestamp = Timestamp.UnixSecondsTimestamp
            };

            Bundle bundle = new Bundle();

            bundle.AddTransfer(trans);

            bundle.Finalize();
            bundle.Sign();

            //sending the message to the tangle
            var resultTransactions = repository.SendTrytes(bundle.Transactions, 27, 14);

            return(RedirectToAction("ShowSpecificChat", new { connection = connection.ConnectionsID }));
        }
Exemplo n.º 18
0
        public void TestAttachToTangle()
        {
            var seed   = new Seed("QLWOWK9NBXOT9IJ9FXEAPGAHEQDDVMTQXL9DD9VOSTXKSFUABIO9AETEAJPZSNEEPQMJDLWTTMOFDVVBE");
            var bundle = new Bundle();

            bundle.AddTransfer(
                new Transfer
            {
                Address =
                    new Address("YTXCUUWTXIXVRQIDSECVFRTKAFOEZITGDPLWYVUVFURMNVDPIRXEIQN9JHNFNVKVJMQVMA9GDZJROTSFZHIVJOVAEC")
                {
                    Balance = 0, PrivateKey = new PrivateKeyStub()
                },
                Message   = TryteString.FromAsciiString("Hello world!"),
                Tag       = new Tag("CSHARP"),
                Timestamp = Timestamp.UnixSecondsTimestamp
            });

            bundle.Finalize();
            bundle.Sign();

            var branchTransaction = new Hash("QINJZUOQGRRIKZJIKWJRBHVLQPKKGKGRODPMJXZZVZKNNVIGTYELWSYWRESO9JNZYSJBVYANLFVIZ9999");
            var trunkTransaction  = new Hash("CXTEVCPNIEMITBQAVKWAQNZMVCHOZPTNQHGHQPSQDXEGWKLHDXLZUDEVOBONAEJJTFDGDRAXDVBUZ9999");

            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <AttachToTangleResponse>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <AttachToTangleResponse>
                {
                    StatusCode = HttpStatusCode.OK,
                    Data       =
                        new AttachToTangleResponse
                    {
                        Trytes =
                            new List <string>
                        {
                            TransactionTrytesWithPoWDone
                        }
                    }
                };
                return(restResponse);
            });

            var repository = new RestIotaRepository(restClientMock.Object);
            var result     = repository.AttachToTangle(branchTransaction, trunkTransaction, bundle.Transactions);

            Assert.AreEqual(TransactionTrytesWithPoWDone, result[0].Value);
        }
Exemplo n.º 19
0
        public void TestGetNeighborsShouldIncludeAllParameters()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <NeighborList>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <NeighborList>
                {
                    StatusCode = HttpStatusCode.OK,
                    Data       =
                        new NeighborList
                    {
                        Duration  = 1,
                        Neighbors =
                            new List <Neighbor>
                        {
                            new Neighbor
                            {
                                Address                 = "/8.8.8.8:14265",
                                ConnectionType          = "Remote",
                                NumberOfAllTransactions =
                                    45,
                                NumberOfInvalidTransactions
                                    = 0,
                                NumberOfNewTransactions = 5,
                                NumberOfRandomTransactionRequests
                                    = 3,
                                NumberOfSentTransactions =
                                    40
                            }
                        }
                    }
                };
                return(restResponse);
            });

            var repository = new RestIotaRepository(restClientMock.Object);
            var neighbors  = repository.GetNeighbors();

            Assert.AreEqual(1, neighbors.Duration);
            Assert.AreEqual("/8.8.8.8:14265", neighbors.Neighbors[0].Address);
            Assert.AreEqual("Remote", neighbors.Neighbors[0].ConnectionType);
            Assert.AreEqual(45, neighbors.Neighbors[0].NumberOfAllTransactions);
            Assert.AreEqual(0, neighbors.Neighbors[0].NumberOfInvalidTransactions);
            Assert.AreEqual(5, neighbors.Neighbors[0].NumberOfNewTransactions);
            Assert.AreEqual(3, neighbors.Neighbors[0].NumberOfRandomTransactionRequests);
            Assert.AreEqual(40, neighbors.Neighbors[0].NumberOfSentTransactions);
        }
Exemplo n.º 20
0
        private static void SendToChain(string address, RestIotaRepository repository, string message)
        {
            Seed     seed     = new Seed(address);
            Transfer transfer = new Transfer
            {
                Address         = new Address(address),
                Message         = TryteString.FromUtf8String(message),
                ValueToTransfer = 0
            };

            Bundle bundle = new Bundle();

            bundle.AddTransfer(transfer);


            int depth = 3;
            int minWeightMagnitude = 9;

            try
            {
                var sendTransfer = repository.SendTransfer(seed, bundle, SecurityLevel.Medium, depth, minWeightMagnitude);

                //TransactionHashList bundleTransactions = repository.FindTransactionsByBundles(new List<Hash> {bundle.Hash});
                //foreach (Hash transactionsHash in bundleTransactions.Hashes)
                //{
                //    Hash hash = new Hash(transactionsHash.Value);
                //    var transactionsTrytes = repository.GetTrytes(bundleTransactions.Hashes);
                //    var transaction = Transaction.FromTrytes(transactionsTrytes[0], hash);
                //}

                TransactionHashList transactionsByAdress =
                    repository.FindTransactionsByAddresses(new List <Address> {
                    new Address(address)
                });

                var  transactionsTrytesAddress = repository.GetTrytes(transactionsByAdress.Hashes).First();
                Hash hashAddress = new Hash(transactionsByAdress.Hashes[0].Value);

                Transaction       transactionOne    = Transaction.FromTrytes(transactionsTrytesAddress, hashAddress);
                TransactionTrytes transactionTrytes = new TransactionTrytes("");
                TransactionTrytes test = transactionOne.ToTrytes();
                var text = test.Value;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                //throw;
            }
        }
Exemplo n.º 21
0
        public void TestFindTransactionsWithGivenParametersButSomeAreEmptyShouldThrowException()
        {
            var restClientMock = new Mock <IRestClient>();

            var repository = new RestIotaRepository(restClientMock.Object);

            repository.FindTransactions(
                new Dictionary <string, IEnumerable <TryteString> >
            {
                { "bundles", new List <TryteString>() },
                { "addresses", new List <TryteString>() },
                { "tags", new List <TryteString>() },
                { "approvees", new List <TryteString>() }
            });
        }
Exemplo n.º 22
0
        public static List <Address> GetTangleAddressesFromNprId(RestIotaRepository repository, string nprId, int numberOfAddressesNeeded)
        {
            List <Address> addresses = new List <Address>();

            // Assert if patient id is in our hard-coded registry.
            if (!s_nationalPatientRegistrySeedVault.ContainsKey(nprId))
            {
                return(addresses);
            }

            // Get patient seed, request new addresses and return.
            var patientSeed = s_nationalPatientRegistrySeedVault[nprId];

            addresses.AddRange(repository.GetNewAddresses(patientSeed, 0, numberOfAddressesNeeded, SecurityLevel.Medium));
            return(addresses);
        }
Exemplo n.º 23
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // Get needed parameters from payload.
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  deviceId    = data?.device.deviceId;
            dynamic telemetry   = data?.device.measurements.telemetry;
            dynamic properties  = data?.device.properties;
            string  nprId       = properties.device.nprId_property.ToString();

            // Basic validation before proceeding.
            if (string.IsNullOrEmpty(nprId) || !(telemetry is JObject))
            {
                return(new BadRequestObjectResult("NprId not set on reporting device or reading invalid."));
            }

            // Connect to a node on one of the main networks.
            var repository = new RestIotaRepository(new RestClient("https://nodes.devnet.thetangle.org:443"));

            // Get addresses from the Tangle on behalf of the patient's wallet for generating new address for posting reading.
            // Would be an external trusted service.
            var tangleAddresses = NationalIdentityService.GetTangleAddressesFromNprId(repository, nprId, ((JObject)telemetry).Count);

            // Terminate if no addresses created.
            if (tangleAddresses.Count < 1)
            {
                return(new BadRequestObjectResult("NprId not found or no associated seed."));
            }

            // Create transactions for the Tangle for each type of reading in payload and bundle together.
            // Finalize and sign.
            var bundle = CreateTransaction(tangleAddresses, telemetry);

            // Send the complete transactions to the Tangle.
            repository.SendTrytes(bundle.Transactions, depth: 2, minWeightMagnitude: 9);

            string logMessage = $"NPRId: {nprId} - DeviceID: {deviceId} - reading: {telemetry.ToString()} - Bundle hash: {bundle.Hash.Value}";

            log.LogInformation(logMessage);

            return((ActionResult) new OkObjectResult(logMessage));
        }
        private void InitNodeIotaRepository()
        {
            var node = NodeManager.SelectNode();

            ActualNodeServer = node;

            if (ActualNodeServer is null)
            {
                IotaRepository = null;
            }
            else
            {
                IotaRepository = new RestIotaRepository(new RestClient(node)
                {
                    Timeout = 5000
                });
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            var repository = new RestIotaRepository(
                new FallbackIotaClient(
                    new List <string>
            {
                "https://nodes.devnet.thetangle.org:443",
                "http://node04.iotatoken.nl:14265",
                "http://node05.iotatoken.nl:16265",
                "https://nodes.thetangle.org:443",
                "http://iota1.heidger.eu:14265",
                "https://nodes.iota.cafe:443",
                "https://potato.iotasalad.org:14265",
                "https://durian.iotasalad.org:14265",
                "https://turnip.iotasalad.org:14265",
                "https://nodes.iota.fm:443",
                "https://tuna.iotasalad.org:14265",
                "https://iotanode2.jlld.at:443",
                "https://node.iota.moe:443",
                "https://wallet1.iota.town:443",
                "https://wallet2.iota.town:443",
                "http://node03.iotatoken.nl:15265",
                "https://node.iota-tangle.io:14265",
                "https://pow4.iota.community:443",
                "https://dyn.tangle-nodes.com:443",
                "https://pow5.iota.community:443",
            },
                    5000),
                new PoWSrvService());

            try
            {
                repository.AddNeighbors(new List <string> {
                    "udp://8.8.8.8:14265"
                });
            }
            catch (IotaApiException e)
            {
            }


            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 26
0
        public static Address GetNextAvailableAddress(RestIotaRepository repository)
        {
            if (repository == null)
            {
                repository = new RestIotaRepository(new RestClient(Static.currentNode));
            }

            Seed seed = new Seed(Static.seed);

            for (int i = 0; i < 50; i++)
            {
                List <Address> addresses = repository.GetNewAddresses(seed, i, 1, 2);

                if (addresses != null && addresses.Count > 0 && !addresses.First().SpentFrom)
                {
                    return(addresses.First());
                }
            }
            return(null);
        }
Exemplo n.º 27
0
        public RestIotaRepository Create()
        {
            var powService = new PoWService(new CpuPowDiver());
            var node       = new RestIotaRepository(new RestClient("https://field.carriota.com:443"), powService);

            if (NoteIsHealthy(node))
            {
                return(node);
            }

            foreach (var nodeUri in this.nodeUriList)
            {
                node = new RestIotaRepository(new RestClient(nodeUri), powService);
                if (NoteIsHealthy(node))
                {
                    break;
                }
            }

            return(node);
        }
Exemplo n.º 28
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            var repository   = new RestIotaRepository(new RestClient("https://localhost:14265"));
            var nodeInfo     = repository.GetNodeInfo();
            var neighbours   = repository.GetNeighbors();
            var transactions =
                repository.GetTransactionsByAddresses(
                    new List <string> {
                "GVZSJANZQULQICZFXJHHAFJTWEITWKQYJKU9TYFA9AFJLVIYOUCFQRYTLKRGCVY9KPOCCHK99TTKQGXA9"
            });
            var balances =
                repository.GetBalances(
                    new List <string>
            {
                "GVZSJANZQULQICZFXJHHAFJTWEITWKQYJKU9TYFA9AFJLVIYOUCFQRYTLKRGCVY9KPOCCHK99TTKQGXA9",
                "HBBYKAKTILIPVUKFOTSLHGENPTXYBNKXZFQFR9VQFWNBMTQNRVOUKPVPRNBSZVVILMAFBKOTBLGLWLOHQ999999999"
            },
                    100);

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 29
0
        /// <summary>
        /// The execute api example.
        /// </summary>
        private static void ExecuteApiExample()
        {
            var nodeUri = ConfigurationManager.AppSettings["nodeUri"]; // The node URI is saved in the projects App.config ... let's get it

            var iotaClient = new RestIotaClient(new RestClient(nodeUri));
            var powService = new PoWService(new CpuPearlDiver()); // the examples will use the CPU to do PoW for a transaction.

            // you could also use a remote node for PoW, if the node supports it. Uncomment this line and comment the line above to do so. Don't forget to change the node Uri in App.Config
            // var powService = new RestPoWService(iotaClient);

            var repository = new RestIotaRepository(
                iotaClient,
                powService); // compose the repository. all these steps would normally be done via DI container (ninject for example)

            // var factory = new RestIotaRepositoryFactory(); In an async context it is also possible to create a repository via factory as shown here.
            // var repository = await factory.CreateAsync(); This automatically picks a healthy node.

            var example = new GetAccountDataExample(repository); // get the example to execute. Change this to any example you want

            var result = example.Execute();

            Console.WriteLine(result); // print the example result to console. Set a breakpoint here if you want to see the result in debug mode.
        }
Exemplo n.º 30
0
        public void TestFindTransactionsWithValidParametersShouldReturnHashes()
        {
            var restClientMock = new Mock <IRestClient>();

            restClientMock.Setup(r => r.Execute <GetTransactionsResponse>(It.IsAny <IRestRequest>())).Returns(
                () =>
            {
                var restResponse = new RestResponse <GetTransactionsResponse>
                {
                    StatusCode = HttpStatusCode.OK,
                    Data       =
                        new GetTransactionsResponse
                    {
                        Hashes =
                            new List <string>
                        {
                            "EJEAOOZYSAWFPZQESYDHZCGYNSTWXUMVJOVDWUNZJXDGWCLUFGIMZRMGCAZGKNPLBRLGUNYWKLJTYEAQX"
                        }
                    }
                };
                return(restResponse);
            });

            var repository   = new RestIotaRepository(restClientMock.Object);
            var transactions =
                repository.FindTransactions(
                    new Dictionary <string, IEnumerable <TryteString> >
            {
                {
                    "bundles",
                    new List <TryteString>
                    {
                        new TryteString(
                            "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB")
                    }
                },
                {
                    "addresses",
                    new List <TryteString>
                    {
                        new TryteString(
                            "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB")
                    }
                },
                {
                    "tags",
                    new List <TryteString>
                    {
                        new TryteString(
                            "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB")
                    }
                },
                {
                    "approvees",
                    new List <TryteString>
                    {
                        new TryteString(
                            "RBTC9D9DCDEAUCFDCDADEAMBHAFAHKAJDHAODHADHDAD9KAHAJDADHJSGDJHSDGSDPODHAUDUAHDJAHAB")
                    }
                }
            });

            Assert.AreEqual("EJEAOOZYSAWFPZQESYDHZCGYNSTWXUMVJOVDWUNZJXDGWCLUFGIMZRMGCAZGKNPLBRLGUNYWKLJTYEAQX", transactions.Hashes[0].Value);
        }