Example #1
0
        private void Serialize()
        {
            // all mosaic definition bytes inclusive of properties
            _serializer.WriteBytes(MosaicDefinition.GetBytes());

            // add mosaic definition part length plus length of transaction part
            Length += MosaicDefinition.Length + 56;

            if (Levy != null)
            {
                // all levy bytes if not null
                _serializer.WriteBytes(Levy.GetBytes());

                // add levy structure length minus 4 bytes that would otherwise have been a place holder in lue of a levy
                Length += Levy.Length - 4;
            }
            else
            {
                // if no levy, serialize 0 placeholder
                _serializer.WriteInt(DefaultValues.ZeroValuePlaceHolder);
            }

            // fee sink address length
            _serializer.WriteInt(ByteLength.AddressLength);

            // fee sink address
            _serializer.WriteString(AddressEncoding.ToEncoded(Con.GetNetworkVersion(), new PublicKey(DefaultValues.MainNetCreationFeeSink)));

            // creation fee
            _serializer.WriteLong(Fee.Creation);
        }
Example #2
0
        public Task <PaginationResult <OnHold> > Get(string owner, IReadOnlyCollection <ulong>?collectionIds, PaginationParameter parameter)
        {
            // Ensure that seller is a proper base58 encoded address
            string base64Owner = "Invalid";

            try {
                var pk = AddressEncoding.AddressToPublicKey(owner);
                base64Owner = Convert.ToBase64String(pk);
            }
            catch (ArgumentNullException) {}
            catch (FormatException) {}
            catch (ArgumentOutOfRangeException) {}
            catch (ArgumentException) {}
            // Console.WriteLine($"Converted {seller} to base64: {base64Seller}");

            var incomings = IncomingWithoutOffer()
                            .Where(i => i.OwnerPublicKey == base64Owner);

            if (collectionIds?.Any() == true)
            {
                incomings = incomings.Where(i => collectionIds.Contains(i.CollectionId));
            }

            return(incomings.Select(MapOnHold()).PaginateAsync(parameter));
        }
Example #3
0
        public void TestHash()
        {
            var node         = new Node();
            var message      = "lalala";
            var messageBytes = Encoding.UTF8.GetBytes(message);

            var hashedByNodeMessage = node.SecureHash(message);
            var hashedMessage       = AddressEncoding.SecureHash(messageBytes, 0, messageBytes.Length);

            Assert.IsTrue(hashedByNodeMessage.SequenceEqual(hashedMessage));
            var fastHashedByNodeMessage = node.FastHash(message);
            var fasthashedMessage       = AddressEncoding.FastHash(messageBytes, 0, messageBytes.Length);

            Assert.IsTrue(fastHashedByNodeMessage.SequenceEqual(fasthashedMessage));
        }
        public async Task <PaginationResult <TradeDto> > Get(string address, IReadOnlyCollection <ulong>?collectionIds, PaginationParameter parameter)
        {
            // Ensure that address is a proper base58 encoded address
            string base64Address = "Invalid";

            try {
                var pk = AddressEncoding.AddressToPublicKey(address);
                base64Address = Convert.ToBase64String(pk);
            }
            catch (ArgumentNullException) {}
            catch (FormatException) {}
            catch (ArgumentOutOfRangeException) {}
            catch (ArgumentException) {}

            return(await
                   FilterByCollectionId(_marketplaceDbContext.Trades, collectionIds)
                   .Where(t => (t.Offer.Seller == base64Address) || (t.Buyer == base64Address))
                   .OrderByDescending(t => t.TradeDate)
                   .AsNoTrackingWithIdentityResolution()
                   .Select(MapTrade())
                   .PaginateAsync(parameter));
        }
        public static IQueryable <Offer> FilterBySeller(this IQueryable <Offer> offers, string?seller)
        {
            if (string.IsNullOrWhiteSpace(seller))
            {
                return(offers);
            }

            // Ensure that seller is a proper base58 encoded address
            string base64Seller = "Invalid";

            try {
                var pk = AddressEncoding.AddressToPublicKey(seller);
                base64Seller = Convert.ToBase64String(pk);
            }
            catch (ArgumentNullException) {}
            catch (FormatException) {}
            catch (ArgumentOutOfRangeException) {}
            catch (ArgumentException) {}
            // Console.WriteLine($"Converted {seller} to base64: {base64Seller}");

            return(offers.Where(o => o.Seller == base64Seller));
        }
Example #6
0
        private void Serialize()
        {
            TotalBytesLength += StructureLength.ProvisionNameSpace + LengthOfNewPart;
            _serializer.WriteInt(ByteLength.AddressLength);
            _serializer.WriteString(AddressEncoding.ToEncoded(Con.GetNetworkVersion(), new PublicKey(DefaultValues.MainNetRentalFeeSinkPublicKey)));

            _serializer.WriteLong(Data.Parent == DefaultValues.EmptyString ? Fee.Rental : Fee.SubSpaceRental);
            _serializer.WriteInt(LengthOfNewPart);
            _serializer.WriteBytes(Encoding.Default.GetBytes(Data.NewPart));

            if (string.Empty != Data.Parent)
            {
                TotalBytesLength += ByteLength.FourBytes + LengthOfParent;
                _serializer.WriteInt(LengthOfParent);
                _serializer.WriteBytes(Encoding.Default.GetBytes(Data.Parent));
            }
            else
            {
                TotalBytesLength += ByteLength.FourBytes;
                _serializer.WriteBytes(DefaultBytes.MaxByteValue);
            }

            ProvisionNamespaceBytes = ByteUtils.TruncateByteArray(_serializer.GetBytes(), TotalBytesLength);
        }
Example #7
0
        private void generate()
        {
            if ((!check_rawsk.Checked) && (!check_mobile.Checked))
            {
                MessageBox.Show("You need to include at least one private key format.", "Select private key format");
                return;
            }

            int voucher_amount = 1;

            if (check_bulk.Checked)
            {
                voucher_amount = Convert.ToInt32(numericUpDown_blk_amount.Value);
            }

            for (int icount = 0; icount < voucher_amount; icount++)
            {
                string sk;
                using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
                {
                    byte[] tokenData = new byte[32];
                    rng.GetBytes(tokenData);

                    sk = ByteArrayToString(tokenData);
                }

                if (check_ownKey.Checked)
                {
                    if (!String.IsNullOrEmpty(txt_customKey.Text) && txt_customKey.Text.Length.Equals(64) && System.Text.RegularExpressions.Regex.IsMatch(txt_customKey.Text, @"\A\b[0-9a-fA-F]+\b\Z"))
                    {
                        sk = txt_customKey.Text;
                    }
                    else
                    {
                        MessageBox.Show("Your custom private key is not compatible - it must be a HEX string with 64 characters.", "Please provide a valid private key", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }


                // Testdata
                //string privateKey = "abf4cf55a2b3f742d7543d9cc17f50447b969e6e06f5ea9195d428ab12b7318d";

                string address      = AddressEncoding.ToEncoded(0x68, new PublicKey(new PrivateKey(sk)));
                string splitaddress = address.Substring(0, 20) + Environment.NewLine + address.Substring(20, address.Length - 20);
                string walletname   = "";

                lbl_Address.Text = splitaddress;

                if (check_mobile.Checked)
                {
                    string password = txt_password.Text;
                    if (check_rnd_password.Checked)
                    {
                        string        dictionaryString    = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ23456789";
                        StringBuilder resultStringBuilder = new StringBuilder();
                        Random        rd = new Random();
                        for (int i = 0; i < 8; i++)
                        {
                            resultStringBuilder.Append(dictionaryString[rd.Next(dictionaryString.Length)]);
                        }
                        password = resultStringBuilder.ToString();
                    }
                    if ((password.Equals("")) | (password.Length < 6))
                    {
                        MessageBox.Show("For mobile wallet support you need to provide a password with at least 6 characters.", "Provide password", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    walletname = txt_walletname.Text;
                    if ((walletname.Equals("")) | (walletname.Length < 1))
                    {
                        MessageBox.Show("For mobile wallet support you need to provide a wallet name.", "Provide name", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    if ((!Regex.IsMatch(walletname, @"^[a-zA-Z0-9]+$")) || (!Regex.IsMatch(password, @"^[a-zA-Z0-9]+$")))
                    {
                        MessageBox.Show("Your password or walletname contains special or country specific characters, this is not fully tested, please assure you can import the wallet before sending XEM to it!", "Special characters in use", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    // Generate salt
                    string salt;
                    using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
                    {
                        byte[] tokenData = new byte[32];
                        rng.GetBytes(tokenData);

                        salt = ByteArrayToString(tokenData);
                    }

                    String sk_encoded = voucher.GenEncsk(txt_walletname.Text, password, sk, salt);

                    //generate secret encoded key qrcode
                    IBarcodeWriter writerskencoded = new BarcodeWriter
                    {
                        Format  = BarcodeFormat.QR_CODE,
                        Options = new ZXing.Common.EncodingOptions
                        {
                            Width  = 200,
                            Height = 200,
                        }
                    };
                    var codesk          = writerskencoded.Write(sk_encoded);
                    var barcodeBitmapsk = new Bitmap(codesk);
                    picbox_sk_mobile.Image = barcodeBitmapsk;

                    picbox_sk_mobile.Visible = true;
                    lbl_mob_format.Visible   = true;
                    if (check_showPW.Checked)
                    {
                        lbl_password.Text    = "Import password: "******"";
                    for (int i = 0; i < 64; i += 8)
                    {
                        lbl_sk.Text = lbl_sk.Text + (sk.Substring(i, 8).ToUpper() + Environment.NewLine);
                    }

                    //lbl_sk.Text = sk;
                    lbl_sk.Visible         = true;
                    lbl_raw_format.Visible = true;
                }

                //generate NEM address qrcode
                string         address_qr   = "{\"v\":2,\"type\":1,\"data\":{\"addr\":\"" + address + "\",\"name\":\"" + walletname + "\"}}";
                IBarcodeWriter writeradress = new BarcodeWriter
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new ZXing.Common.EncodingOptions
                    {
                        Width  = 150,
                        Height = 150
                    }
                };

                var codeadress           = writeradress.Write(address_qr);
                var barcodeBitmapAddress = new Bitmap(codeadress);
                picbox_Address.Image   = barcodeBitmapAddress;
                picbox_Address.Visible = true;
                lbl_Address.Visible    = true;


                if (check_bulk.Checked)
                {
                    string file = address + ".jpg";
                    save(file);
                }
                //string expected = "NAZQOWGZJ5PKR3QJEUZEMS6MXQX3WZZZAKKTLPZT";
            }
        }
Example #8
0
        private static async void ScanTransactions(Account userAccount)
        {
            try
            {
                var tClient = new TransactionDataClient(Con);

                var request = tClient.BeginGetAllTransactions(ar =>
                {
                    try
                    {
                        var txs = ar.Content.data.Where(e => e.transaction?.otherTrans?.type == 257 || e.transaction?.type == 257).ToList();


                        foreach (var t in txs)
                        {
                            if (userAccount.LastTransactionHash == txs?[0]?.meta.innerHash?.data || userAccount.LastTransactionHash == txs?[0]?.meta?.hash?.data)
                            {
                                userAccount.LastTransactionHash = txs?[0].transaction.type == 4100 ? txs?[0]?.meta.innerHash?.data : txs?[0]?.meta?.hash?.data;

                                break;
                            }


                            if (userAccount.LastTransactionHash == t.meta?.hash?.data || userAccount.LastTransactionHash == t.meta.innerHash.data)
                            {
                                userAccount.LastTransactionHash = txs?[0].transaction.type == 4100 ? txs?[0]?.meta.innerHash?.data : txs?[0]?.meta?.hash?.data;
                                AccountUtils.UpdateAccount(usrAcc: userAccount);

                                break;
                            }

                            if (!userAccount.CheckTxs)
                            {
                                continue;
                            }

                            try
                            {
                                var summary = new AccountTxSummary
                                {
                                    AmountIn         = t.transaction.recipient == userAccount.EncodedAddress ? t.transaction.amount : 0,
                                    AmountOut        = t.transaction.recipient != userAccount.EncodedAddress ? t.transaction.amount : 0,
                                    MonitoredAccount = userAccount.EncodedAddress,
                                    Recipient        = t.transaction.type == 257 ? t.transaction.recipient : t.transaction.otherTrans.recipient,
                                    Sender           = AddressEncoding.ToEncoded(network: 0x68, publicKey: new PublicKey(key: t.transaction.type == 257 ? t.transaction.signer : t.transaction.otherTrans.signer)),
                                    DateOfInput      = DateTime.Now,
                                    OwnedByUser      = userAccount.OwnedByUser
                                };

                                Notify(a: userAccount, t: t);

                                SummaryUtils.AddTxSummary(s: summary);
                            }
                            catch (Exception e)
                            {
                                if (e.Message.Contains("blocked"))
                                {
                                    AccountUtils.DeleteAccountsByUser(userAccount.OwnedByUser);

                                    NodeUtils.DeleteUserNodes(userAccount.OwnedByUser);

                                    UserUtils.DeleteUser(userAccount.OwnedByUser);
                                }
                                else
                                {
                                    Console.WriteLine("Trans scanner line 112: " + e.StackTrace);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(value: e);

                        if (e.Message.Contains("blocked"))
                        {
                            AccountUtils.DeleteAccountsByUser(userAccount.OwnedByUser);

                            NodeUtils.DeleteUserNodes(userAccount.OwnedByUser);

                            UserUtils.DeleteUser(userAccount.OwnedByUser);
                        }
                    }
                }, userAccount.EncodedAddress);

                request.AsyncWaitHandle.WaitOne();
            }
            catch (Exception e)
            {
                Console.WriteLine("Transaction scanner line 136: " + e.StackTrace);
            }
        }
        internal bool ScanTxAgainstRuleSet(Transactions.TransactionData t)
        {
            var multisigAccInfo = new AccountClient(Con);

            var valid = true;

            multisigAccInfo.BeginGetAccountInfoFromPublicKey(ar => {
                if (_black.Count > 0 && _black.Contains(StringUtils.GetResultsWithoutHyphen(t.transaction.otherTrans.recipient)))
                {
                    Console.WriteLine("failed on blacklist");
                    valid = false;
                }

                if (_white.Count > 0 && !_white.Contains(StringUtils.GetResultsWithoutHyphen(t.transaction.otherTrans.recipient)))
                {
                    Console.WriteLine("failed on white list");
                    valid = false;
                }


                if (long.Parse(ConfigurationManager.AppSettings["maxTx"]) != 0 && t.transaction.otherTrans.amount >= long.Parse(ConfigurationManager.AppSettings["maxTx"]) * 1000000)
                {
                    Console.WriteLine("failed max transaction size");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["minTx"]) != 0 && t.transaction.otherTrans.amount <= long.Parse(ConfigurationManager.AppSettings["minTx"]) * 1000000)
                {
                    Console.WriteLine("failed on min transaction size");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["maxBal"]) != 0 && ar.Content.Account.Balance >= long.Parse(ConfigurationManager.AppSettings["maxBal"]) * 1000000)
                {
                    Console.WriteLine("failed on max balance");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["minBal"]) != 0 && ar.Content.Account.Balance <= long.Parse(ConfigurationManager.AppSettings["minBal"]) * 1000000)
                {
                    Console.WriteLine("failed on min balance");
                    valid = false;
                }

                if (ConfigurationManager.AppSettings["secretCode"] != "" && t.transaction.otherTrans.message.payload != ConfigurationManager.AppSettings["secretCode"])
                {
                    Console.WriteLine("failed on secret code");
                    valid = false;
                }

                var sum1 = TxSummaryController.GetSummaryForAccount(ar.Content.Account.Address, 1);

                if (int.Parse(ConfigurationManager.AppSettings["maxDayTx"]) != 0 && sum1 != null && sum1.Count >= int.Parse(ConfigurationManager.AppSettings["maxDayTx"]))
                {
                    Console.WriteLine("failed on daily max transactions");
                    valid = false;
                }

                var sum7 = TxSummaryController.GetSummaryForAccount(ar.Content.Account.Address, 7);

                if (int.Parse(ConfigurationManager.AppSettings["maxWeekTx"]) != 0 && sum7 != null && sum7.Count >= int.Parse(ConfigurationManager.AppSettings["maxWeekTx"]))
                {
                    Console.WriteLine("failed on weekly max transactions");
                    valid = false;
                }

                var sum31 = TxSummaryController.GetSummaryForAccount(ar.Content.Account.Address, 31);

                if (int.Parse(ConfigurationManager.AppSettings["maxMonthTx"]) != 0 && sum31 != null && sum31.Count >= int.Parse(ConfigurationManager.AppSettings["maxMonthTx"]))
                {
                    Console.WriteLine("failed on monthly max transactions");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["maxDayAmount"]) != 0 && sum1 != null && sum1.Sum(tx => tx.Amount) >= long.Parse(ConfigurationManager.AppSettings["maxDayAmount"]) * 1000000)
                {
                    Console.WriteLine("failed on daily max transactions");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["maxWeekAmount"]) != 0 && sum7 != null && sum7.Sum(tx => tx.Amount) >= long.Parse(ConfigurationManager.AppSettings["maxWeekAmount"]) * 1000000)
                {
                    Console.WriteLine("failed on weekly max transactions");
                    valid = false;
                }

                if (long.Parse(ConfigurationManager.AppSettings["maxMonthAmount"]) != 0 && sum31 != null && sum31.Sum(tx => tx.Amount) >= long.Parse(ConfigurationManager.AppSettings["maxMonthAmount"]) * 1000000)
                {
                    Console.WriteLine("failed on monthly max transactions");
                    valid = false;
                }

                if (ConfigurationManager.AppSettings["ICOAccountPubKey"] != "")
                {
                    valid = false;

                    // get all incoming transactions to the ICO deposit account
                    var txs = GetTransactions(AddressEncoding.ToEncoded(Con.GetNetworkVersion(), new CSharp2nem.Model.AccountSetup.PublicKey(ConfigurationManager.AppSettings["ICOAccountPubKey"])), null);

                    if ((t.transaction.type == 257 ? t.transaction.message?.payload : t.transaction.otherTrans?.message?.payload) != null)
                    {
                        while (!txs.Exists(e => e.meta.hash.data == Encoding.UTF8.GetString(CryptoBytes.FromHexString((t.transaction.type == 257 ? t.transaction.message?.payload : t.transaction.otherTrans?.message?.payload)))))
                        {
                            var tx = GetTransactions(AddressEncoding.ToEncoded(Con.GetNetworkVersion(), new CSharp2nem.Model.AccountSetup.PublicKey(ConfigurationManager.AppSettings["ICOAccountPubKey"])), txs[txs.Count - 1].meta.hash.data);

                            txs.AddRange(tx);
                        }
                    }
                    else
                    {
                        valid = false;
                        Console.WriteLine("failed on transaction verification: missing message hash");
                    }

                    // fail if deposit hash not present in payout transaction
                    if ((t.transaction.otherTrans == null ? t.transaction.message?.payload : t.transaction.otherTrans.message?.payload) != null)
                    {
                        // find deposit transaction based on hash in message
                        var tx = txs.Single(x => x.meta.hash.data == Encoding.UTF8.GetString(CryptoBytes.FromHexString((t.transaction.type == 257 ? t.transaction.message.payload : t.transaction.otherTrans.message.payload))));

                        // initiate mosaic client
                        var mosaicClient = new NamespaceMosaicClient(Con);

                        var mosaicDivisibility = 0;

                        var mosaics = ConfigurationManager.GetSection("MosaicConfigElement") as MyMosaicConfigSection;

                        foreach (MosaicConfigElement m in mosaics.Mosaics)
                        {
                            // retrieve mosaic definition for rate calculation
                            mosaicClient.BeginGetMosaicsByNameSpace(ar3 =>
                            {
                                foreach (var m2 in t.transaction.otherTrans.mosaics)
                                {
                                    if (!(m2.mosaicId.namespaceId == m.MosaicNameSpace && m2.mosaicId.name == m.MosaicID))
                                    {
                                        continue;
                                    }

                                    if (ar3.Ex != null)
                                    {
                                        Console.WriteLine(ar3.Ex);
                                    } // if no error, set mosaic divisibility
                                    else
                                    {
                                        mosaicDivisibility = int.Parse(ar3.Content.Data[0].Mosaic.Properties[0].Value);
                                    }

                                    var depositedAmount = Calculations.GetDepositedAmount(tx);

                                    // calculate based on pre-set currency denomination
                                    if (m.CostDenomination == "USD")
                                    {
                                        // fail if no mosaics present in ico payout transaction
                                        if (t.transaction.otherTrans.mosaics != null)
                                        {
                                            // check if the mosaic quantity paid out is correct for the deposit
                                            var amountValid = Calculations.RateCalculation(depositedAmount, mosaicDivisibility, m) == m2.quantity;

                                            // check the recipient of the payout is the signer of the deposit, fail if not.
                                            if (amountValid && t.transaction.otherTrans.recipient == AddressEncoding.ToEncoded(Con.GetNetworkVersion(), new CSharp2nem.Model.AccountSetup.PublicKey(tx.transaction.otherTrans?.signer == null ? tx.transaction.signer : tx.transaction.otherTrans.signer)))
                                            {
                                                continue;
                                            }
                                            else
                                            {
                                                Console.WriteLine("failed on transaction verification: amount or recipient is invalid");
                                                valid = false;
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine("failed on transaction verification: invalid or missing mosaic");
                                        }
                                    }
                                    else if (m.CostDenomination == "XEM")
                                    {
                                        // set mosaic amount paid out.
                                        var q = m2.quantity;

                                        // get amount that should be paid out for the deposit
                                        var a = Calculations.BonusCalculation(m, Math.Ceiling((depositedAmount / decimal.Parse(m.MosaicCost)) / (decimal)Math.Pow(10, 6 - mosaicDivisibility)));

                                        // if incorrect, fail
                                        valid = a == q ? true : false;

                                        if (!valid)
                                        {
                                            Console.WriteLine("failed on transaction verification: amounts do not match");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("failed on transaction verification: incorrect currency");
                                    }
                                }
                            }, m.MosaicNameSpace, m.MosaicID).AsyncWaitHandle.WaitOne();
                        }
                    }
                    else
                    {
                        Console.WriteLine("failed on transaction verification: missing hash");
                    }
                }
            }, t.transaction.otherTrans.signer).AsyncWaitHandle.WaitOne();

            return(valid);
        }
        internal void ScanAccounts()
        {
            var privateKeys = ConfigurationManager.GetSection("accountsPrivate") as MyConfigSection;

            if (ConfigurationManager.AppSettings["network"] == "test")
            {
                Con.SetTestnet();
            }
            else
            {
                Con.SetMainnet();
            }

            List <KeyLastCheckedPair> listOfCosigs = new List <KeyLastCheckedPair>();

            foreach (MyConfigInstanceElement e in privateKeys.Instances)
            {
                var pair = new KeyLastCheckedPair();

                pair.CheckedHash = new List <string>();

                pair.Acc = new PrivateKeyAccountClientFactory(Con).FromPrivateKey(e.Code);

                listOfCosigs.Add(pair);
            }

            while (true)
            {
                foreach (var pair in listOfCosigs)
                {
                    try
                    {
                        var client = new TransactionDataClient(Con);

                        client.BeginGetUnconfirmedTransactions(ar => {
                            try {
                                if (pair.CheckedHash.Count > 0 && ar.Content.data.Count > 0)
                                {
                                    pair.CheckedHash.RemoveAll(e => ar.Content.data.All(i => e != i.meta.data));
                                }


                                foreach (var t in ar.Content.data)
                                {
                                    if (t.transaction.type != 4100 || t.transaction?.otherTrans?.type != 257 || pair.CheckedHash.Contains(t.meta.data))
                                    {
                                        continue;
                                    }

                                    if (t.transaction.signer == pair.Acc.PublicKey.Raw)
                                    {
                                        continue;
                                    }

                                    Console.WriteLine();

                                    Console.WriteLine("checking transaction: \n" + t.meta.data);

                                    pair.CheckedHash.Add(t.meta.data);

                                    Console.WriteLine("checked");

                                    if (new RuleScanner().ScanTxAgainstRuleSet(t))
                                    {
                                        SignTransaction(
                                            acc: pair.Acc,
                                            t: t,
                                            multisigAcc: AddressEncoding.ToEncoded(
                                                network: Con.GetNetworkVersion(),
                                                publicKey: new PublicKey(t.transaction.otherTrans.signer)));
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }, pair.Acc.Address.Encoded).AsyncWaitHandle.WaitOne();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        continue;
                    }
                }
            }
        }
Example #11
0
        private static async Task Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
#if DEBUG
                                .AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true)
#elif RELEASE
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
#endif
                                .AddCommandLine(args)
                                .Build();

            var settings = configuration.Get <Settings>();
            var seed     = args[0];

            var wavesHelper     = new WavesHelper(settings.NodeUrl, settings.ChainId);
            var account         = PrivateKeyAccount.CreateFromSeed(seed, settings.ChainId);
            var node            = new Node(settings.NodeUrl, settings.ChainId);
            var contractPubKey  = Base58.Decode((settings.ContractPubKey));
            var contractAddress = AddressEncoding.GetAddressFromPublicKey(contractPubKey, settings.ChainId);

            while (true)
            {
                try
                {
                    var height = await wavesHelper.GetHeight();

                    Logger.Info("New height: " + height);
                    Logger.Info("Init");

                    var neutrinoContractData = AccountDataConverter.ToNeutrinoAccountData(
                        await wavesHelper.GetDataByAddress(contractAddress));
                    var controlContractData = AccountDataConverter.ToControlAccountData(
                        await wavesHelper.GetDataByAddress(neutrinoContractData.ControlContractAddress));
                    var auctionControlData = AccountDataConverter.ToAuctionAccountData(
                        await wavesHelper.GetDataByAddress(neutrinoContractData.AuctionContractAddress));
                    var liquidationControlData = AccountDataConverter.ToLiquidationAccountData(
                        await wavesHelper.GetDataByAddress(neutrinoContractData.LiquidationContractAddress));

                    var totalNeutrinoSupply = await wavesHelper.GetTotalSupply(neutrinoContractData.NeutrinoAssetId);

                    var neutrinoBalance = await wavesHelper.GetBalance(contractAddress, neutrinoContractData.NeutrinoAssetId);

                    var wavesBalance = await wavesHelper.GetBalance(contractAddress);

                    Logger.Info($"Price:{controlContractData.Price}");

                    var neutrinoContractBalance = await wavesHelper.GetDetailsBalance(contractAddress);

                    var addresses = new List <string>();
                    if (neutrinoContractData.BalanceLockNeutrinoByUser != null)
                    {
                        addresses.AddRange(neutrinoContractData.BalanceLockNeutrinoByUser.Where(x => x.Value > 0).Select(x => x.Key));
                    }
                    if (neutrinoContractData.BalanceLockWavesByUser != null)
                    {
                        addresses.AddRange(neutrinoContractData.BalanceLockWavesByUser?.Where(x => x.Value > 0).Select(x => x.Key));
                    }

                    long totalWithdraw = 0;
                    foreach (var address in addresses)
                    {
                        var withdrawBlock = neutrinoContractData.BalanceUnlockBlockByAddress.GetValueOrDefault(address);
                        if (height < withdrawBlock)
                        {
                            continue;
                        }

                        var indexes = controlContractData.PriceHeightByIndex.Where(x => x.Value >= withdrawBlock).ToList();

                        if (!indexes.Any())
                        {
                            continue;
                        }

                        var indexString            = indexes.Min(x => x.Key);
                        var index                  = Convert.ToInt64(indexString);
                        var heightByIndex          = controlContractData.PriceHeightByIndex[indexString];
                        var priceByHeight          = controlContractData.PriceByHeight[Convert.ToString(heightByIndex)];
                        var withdrawNeutrinoAmount = neutrinoContractData.BalanceLockNeutrinoByUser.GetValueOrDefault(address);

                        if (withdrawNeutrinoAmount > 0)
                        {
                            var availableBalance = neutrinoContractBalance.Available - totalWithdraw;
                            var wavesAmount      = CurrencyConvert.NeutrinoToWaves(withdrawNeutrinoAmount, priceByHeight);

                            if (wavesAmount > availableBalance)
                            {
                                if (!settings.Leasing.IsLeasingProvider)
                                {
                                    continue;
                                }

                                var totalLeasingCancelAmount = 0L;
                                var activeLeaseTxs           = await wavesHelper.GetActiveLease(settings.Leasing.NodeAddress);

                                foreach (var leasingTx in activeLeaseTxs.OrderBy(x => x.Amount))
                                {
                                    if (totalLeasingCancelAmount >= wavesAmount)
                                    {
                                        break;
                                    }

                                    totalLeasingCancelAmount += leasingTx.Amount;
                                    var cancelLease = new CancelLeasingTransaction(settings.ChainId, contractPubKey, leasingTx.Id, 0.005m);
                                    cancelLease.Sign(account);
                                    // shit code. Bug in wavesCs
                                    var json = JObject.Parse(cancelLease.GetJsonWithSignature().ToJson());
                                    json.Add("proofs", new JArray {
                                        cancelLease.Proofs.Take(Array.FindLastIndex(cancelLease.Proofs, p => p != null && p.Length > 0) + 1)
                                        .Select(p => p == null ? "" : p.ToBase58())
                                        .ToArray()
                                    });
                                    json.Add("version", 2);
                                    json.Add("chainId", settings.ChainId);
                                    var id = await wavesHelper.WaitTxAndGetId(await wavesHelper.Broadcast(json.ToString()));

                                    Logger.Info($"Cancel lease tx:{id} (LeaseId:{cancelLease.LeaseId})");
                                }
                            }

                            totalWithdraw += wavesAmount;
                        }

                        var withdrawTx = node.InvokeScript(account, contractAddress, "withdraw",
                                                           new List <object>()
                        {
                            address, index
                        });
                        var txId = await wavesHelper.WaitTxAndGetId(withdrawTx);

                        Logger.Info($"Withdraw tx id:{txId} (Address:{address})");
                    }

                    if (settings.Leasing.IsLeasingProvider)
                    {
                        var leasingAmountForOneTxInWavelet = settings.Leasing.LeasingAmountForOneTx * CurrencyConvert.Wavelet;

                        var minWaves         = Convert.ToInt64((neutrinoContractBalance.Regular - totalWithdraw) / 100 * (100 - settings.Leasing.LeasingSharePercent));
                        var availableBalance = neutrinoContractBalance.Available - totalWithdraw;
                        var neededAmount     = minWaves - availableBalance;
                        var activeLeaseTxs   = await wavesHelper.GetActiveLease(settings.Leasing.NodeAddress);

                        var totalLeasingCancelAmount = 0L;
                        if (neededAmount > leasingAmountForOneTxInWavelet)
                        {
                            foreach (var leasingTx in activeLeaseTxs.OrderBy(x => x.Amount).Where(x => x.Sender == contractAddress))
                            {
                                if (totalLeasingCancelAmount >= neededAmount)
                                {
                                    break;
                                }

                                totalLeasingCancelAmount += leasingTx.Amount;
                                var cancelLease = new CancelLeasingTransaction(settings.ChainId, contractPubKey,
                                                                               leasingTx.Id, 0.005m);
                                cancelLease.Sign(account);
                                // shit code. Bug in wavesCs
                                var json = JObject.Parse(cancelLease.GetJsonWithSignature().ToJson());
                                json.Add("proofs", new JArray
                                {
                                    cancelLease.Proofs
                                    .Take(Array.FindLastIndex(cancelLease.Proofs, p => p != null && p.Length > 0) +
                                          1)
                                    .Select(p => p == null ? "" : p.ToBase58())
                                    .ToArray()
                                });
                                json.Add("version", 2);
                                json.Add("chainId", settings.ChainId);
                                var id = await wavesHelper.WaitTxAndGetId(await wavesHelper.Broadcast(json.ToString()));

                                Logger.Info($"Cancel lease tx:{id} (LeaseId:{cancelLease.LeaseId})");
                            }
                        }

                        var expectedLeasingBalance = Convert.ToInt64((neutrinoContractBalance.Regular - totalWithdraw) / 100 * settings.Leasing.LeasingSharePercent);
                        var leasingBalance         = neutrinoContractBalance.Regular - neutrinoContractBalance.Available;
                        var neededLeaseTx          = expectedLeasingBalance - leasingBalance;


                        while (neededLeaseTx >= leasingAmountForOneTxInWavelet)
                        {
                            neededLeaseTx -= leasingAmountForOneTxInWavelet;
                            var leaseTx = new LeaseTransaction(settings.ChainId, contractPubKey, settings.Leasing.NodeAddress, settings.Leasing.LeasingAmountForOneTx, 0.005m);
                            leaseTx.Sign(account);
                            // shit code. Bug in wavesCs
                            var json = JObject.Parse(leaseTx.GetJsonWithSignature().ToJson());
                            json.Add("proofs", new JArray {
                                leaseTx.Proofs.Take(Array.FindLastIndex(leaseTx.Proofs, p => p != null && p.Length > 0) + 1)
                                .Select(p => p == null ? "" : p.ToBase58())
                                .ToArray()
                            });
                            json.Add("version", 2);
                            var id = await wavesHelper.WaitTxAndGetId(await wavesHelper.Broadcast(json.ToString()));

                            Logger.Info($"Lease tx:{id}");
                        }
                    }

                    var supply  = totalNeutrinoSupply - neutrinoBalance + neutrinoContractData.BalanceLockNeutrino;
                    var reserve = wavesBalance - neutrinoContractData.BalanceLockWaves;

                    Logger.Info($"Supply:{supply}");
                    Logger.Info($"Reserve:{reserve}");

                    var bondAuctionBalance = await wavesHelper.GetBalance(neutrinoContractData.AuctionContractAddress,
                                                                          neutrinoContractData.BondAssetId);

                    var deficit = CurrencyConvert.NeutrinoToBond(supply - CurrencyConvert.WavesToNeutrino(reserve, controlContractData.Price));
                    var liquidationContractBalance = CurrencyConvert.NeutrinoToBond(await wavesHelper.GetBalance(neutrinoContractData.LiquidationContractAddress, neutrinoContractData.NeutrinoAssetId));

                    Logger.Info($"Deficit:{deficit}");
                    Logger.Info($"BondBalance:{bondAuctionBalance}");

                    if ((deficit > 0 && deficit - bondAuctionBalance >= CurrencyConvert.NeutrinoToBond(supply) * DeficitOffset / 100) || (deficit * -1) - liquidationContractBalance > 0)
                    {
                        Logger.Info("Transfer to auction");
                        var generateBondTx = node.InvokeScript(account, contractAddress,
                                                               "transferToAuction", null);
                        var txId = await wavesHelper.WaitTxAndGetId(generateBondTx);

                        Logger.Info($"Transfer to auction tx id:{txId}");
                    }
                    var surplusWithoutLiquidation = CurrencyConvert.NeutrinoToBond(CurrencyConvert.WavesToNeutrino(reserve, controlContractData.Price) - supply - CurrencyConvert.BondToNeutrino(liquidationContractBalance));
                    if (surplusWithoutLiquidation > 0 && liquidationContractBalance > 0 && !string.IsNullOrEmpty(liquidationControlData.Orderbook))
                    {
                        Logger.Info("Execute order for liquidation");

                        var  orders       = liquidationControlData.Orderbook.Split("_");
                        long totalExecute = 0;
                        var  surplus      = Math.Abs(deficit);
                        foreach (var order in orders.Where(x => !string.IsNullOrEmpty(x)))
                        {
                            var total       = liquidationControlData.TotalByOrder[order];
                            var totalFilled = liquidationControlData.FilledTotalByOrder?.GetValueOrDefault(order) ?? 0;
                            var amount      = total - totalFilled;
                            if (totalExecute >= surplus)
                            {
                                break;
                            }

                            totalExecute += amount;

                            var exTx = node.InvokeScript(account, neutrinoContractData.LiquidationContractAddress, "liquidateBond",
                                                         null);
                            var txId = await wavesHelper.WaitTxAndGetId(exTx);

                            Logger.Info($"Execute order tx id:{txId}");
                        }
                    }
                    else if (surplusWithoutLiquidation <= 0 && liquidationContractBalance > 0)
                    {
                        var exTx = node.InvokeScript(account, neutrinoContractData.LiquidationContractAddress,
                                                     "liquidateBond",
                                                     null);
                        var txId = await wavesHelper.WaitTxAndGetId(exTx);

                        Logger.Info($"Execute order tx id:{txId}");
                    }
                    else if (deficit > 0 && bondAuctionBalance > 0 && !string.IsNullOrEmpty(auctionControlData.Orderbook))
                    {
                        Logger.Info("Execute order for auction");

                        var  orders       = auctionControlData.Orderbook.Split("_");
                        long totalExecute = 0;
                        foreach (var order in orders.Where(x => !string.IsNullOrEmpty(x)))
                        {
                            var total       = auctionControlData.TotalByOrder[order];
                            var totalFilled = auctionControlData.FilledTotalByOrder?.GetValueOrDefault(order) ?? 0;
                            var amount      = CurrencyConvert.NeutrinoToBond(total - totalFilled) * 100 / auctionControlData.PriceByOrder[order];

                            if (totalExecute >= deficit)
                            {
                                break;
                            }

                            totalExecute += amount;

                            var exTx = node.InvokeScript(account, neutrinoContractData.AuctionContractAddress,
                                                         "sellBond", null);
                            var exTxId = await wavesHelper.WaitTxAndGetId(exTx);

                            Logger.Info($"Execute order tx id:{exTxId}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }

                await Task.Delay(TimeSpan.FromSeconds(settings.TimeoutSec));
            }
        }
Example #12
0
        private void generate(string sk)
        {
            blank_voucher();
            if ((!check_rawsk.Checked) && (!check_mobile.Checked))
            {
                MessageBox.Show("You need to include at least one private key format.", "Select private key format");
                return;
            }

            string address      = AddressEncoding.ToEncoded(0x68, new PublicKey(new PrivateKey(sk)));
            string splitaddress = address.Substring(0, 20) + Environment.NewLine + address.Substring(20, address.Length - 20);

            lbl_Address.Text = splitaddress;

            if (check_mobile.Checked)
            {
                string password = txt_password.Text;
                if ((password.Equals("")) | (password.Length < 6))
                {
                    MessageBox.Show("For mobile wallet support you need to provide a password with at least 6 characters.", "Provide password", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string walletname = txt_walletname.Text;
                if ((walletname.Equals("")) | (walletname.Length < 1))
                {
                    MessageBox.Show("For mobile wallet support you need to provide a wallet name.", "Provide name", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if ((!Regex.IsMatch(walletname, @"^[a-zA-Z0-9]+$")) || (!Regex.IsMatch(password, @"^[a-zA-Z0-9]+$")))
                {
                    MessageBox.Show("Your password or walletname contains special or country specific characters, this is not fully tested, please assure you can import the wallet before sending XEM to it!", "Special characters in use", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // Generate salt
                string salt;
                using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
                {
                    byte[] tokenData = new byte[32];
                    rng.GetBytes(tokenData);

                    salt = ByteArrayToString(tokenData);
                }

                //To do: ADD WALLET NAME
                //txt_walletname.Text
                String sk_encoded = voucher.GenEncsk(txt_walletname.Text, password, sk, salt);
                //Console.WriteLine (sk_encoded);

                //generate secret encoded key barcode
                IBarcodeWriter writerskencoded = new BarcodeWriter
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new ZXing.Common.EncodingOptions
                    {
                        Width  = 200,
                        Height = 200,
                    }
                };
                var codesk          = writerskencoded.Write(sk_encoded);
                var barcodeBitmapsk = new Bitmap(codesk);
                picbox_sk_mobile.Image = barcodeBitmapsk;

                picbox_sk_mobile.Visible = true;
                lbl_mob_format.Visible   = true;
                if (check_showPW.Checked)
                {
                    lbl_password.Text    = "Import password: "******"";
                for (int i = 0; i < 64; i += 8)
                {
                    lbl_sk.Text = lbl_sk.Text + (sk.Substring(i, 8).ToUpper() + Environment.NewLine);
                }

                //lbl_sk.Text = sk;
                lbl_sk.Visible         = true;
                lbl_raw_format.Visible = true;
            }



            //generate NEM address barcode
            string         address_qr   = "{\"v\":2,\"type\":1,\"data\":{\"addr\":\"" + address + "\",\"name\":\"" + txt_walletname.Text + "\"}}";
            IBarcodeWriter writeradress = new BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width  = 150,
                    Height = 150
                }
            };
            var codeadress           = writeradress.Write(address_qr);
            var barcodeBitmapAddress = new Bitmap(codeadress);

            picbox_Address.Image   = barcodeBitmapAddress;
            picbox_Address.Visible = true;
            lbl_Address.Visible    = true;


            //string expected = "NAZQOWGZJ5PKR3QJEUZEMS6MXQX3WZZZAKKTLPZT";
        }
        internal void GetSummary(string text, Chat chat)
        {
            int days;

            switch (text)
            {
            case "/dailySummary":
                days = 1;
                break;

            case "/sevenDaySummary":
                days = 7;
                break;

            case "/thirtyOneDaySummary":
                days = 31;
                break;

            default:
                try
                {
                    days = int.Parse(s: Regex.Replace(input: text.Substring(startIndex: text.LastIndexOf(value: ':') + 1), pattern: @"[\s]+", replacement: string.Empty));

                    break;
                }
                catch (Exception)
                {
                    var reqAction = new SendMessage(chatId: chat.Id, text: "Please insert the number of days for which you want a summary. eg. \"/customSummary: 4\"");

                    var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                    Bot.MakeRequestAsync(request: reqAction);

                    return;
                }
            }

            var acc = AccountUtils.GetAccountByUser(chatId: chat.Id);

            var nodes = NodeUtils.GetAllNodes();

            foreach (var address in acc)
            {
                SuperNode nodeAlias = null;

                try
                {
                    nodeAlias = nodes.Single(predicate: x => x.DepositAddress == address.EncodedAddress);
                }
                catch (Exception)
                {
                }


                var txsummaries = SummaryUtils.GetTxSummary(account: address.EncodedAddress, days: days, chatId: chat.Id);

                var txIn = txsummaries.Count(predicate: e => address.EncodedAddress == e.Recipient);

                var txOut = txsummaries.Count(predicate: e => address.EncodedAddress != e.Recipient);

                var txValueIn = txsummaries.Where(predicate: x => txsummaries.Any(predicate: y => y.AmountIn > 0)).ToList()
                                .Select(selector: e => e.AmountIn)
                                .Sum() / 1000000;

                var txValueOut = txsummaries.Where(predicate: x => txsummaries.Any(predicate: y => y.AmountIn > 0)).ToList()
                                 .Select(selector: e => e.AmountOut)
                                 .Sum() / 1000000;

                var snPayout = txsummaries.Where(predicate: x => txsummaries.Any(predicate: y => y.AmountIn > 0)).ToList()
                               .Select(selector: e => e.AmountIn)
                               .Where(
                    predicate: x =>
                    txsummaries.Any(
                        predicate: y =>
                        y.Sender ==
                        AddressEncoding.ToEncoded(network: 0x68,
                                                  publicKey: new PublicKey(
                                                      key: "d96366cdd47325e816ff86039a6477ef42772a455023ccddae4a0bd5d27b8d23"))))
                               .Sum() / 1000000;

                var accountBalanceDifference = txValueIn - txValueOut;
                var totalTxs = txIn + txOut;

                var hbsummaries = SummaryUtils.GetHBSummary(account: address.EncodedAddress, days: days, chatId: chat.Id);

                var totalFees = hbsummaries.Where(predicate: x => hbsummaries.Any(predicate: y => y.FeesEarned > 0)).ToList()
                                .Select(selector: e => e.FeesEarned)
                                .Sum() / 1000000;

                var totalBlocks = hbsummaries.Count(predicate: e => address.EncodedAddress == e.MonitoredAccount);

                var reqAction = new SendMessage(chatId: chat.Id,
                                                text: "Summary for account: \n" + StringUtils.GetResultsWithHyphen(address.EncodedAddress) + "\n" +
                                                (nodeAlias != null ? ("Deposit address for node: " + nodeAlias.Alias + "\n") : "") +
                                                "Transactions in: " + txIn + "\n" +
                                                "Transactions out: " + txOut + "\n" +
                                                "Total transactions: " + totalTxs + "\n" +
                                                "Transactions value in: " + txValueIn + " XEM\n" +
                                                "Transactions value out: " + txValueOut + " XEM\n" +
                                                "Transactions value total: " + (txValueIn - txValueOut) + " XEM\n" +
                                                "Total supernode payout: " + snPayout + " XEM\n" +
                                                "Harvested blocks: " + totalBlocks + "\n" +
                                                "Total harvested fees: " + totalFees + " XEM\n" +
                                                "Change in balance: " + (accountBalanceDifference + totalFees) + " XEM\n" +
                                                "Final balance: " + aClient.EndGetAccountInfo(aClient.BeginGetAccountInfoFromAddress(address.EncodedAddress))
                                                .Account.Balance / 1000000 + "\n" +
                                                "http://explorer.ournem.com/#/s_account?account=" +
                                                address.EncodedAddress
                                                );

                var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                Bot.MakeRequestAsync(request: reqAction);
            }
        }