Exemplo n.º 1
0
 public void MainnetCashAddrNoPrefixAddressOK()
 {
     Assert.True(PaymentAddress.TryParse("qrcuqadqrzp2uztjl9wn5sthepkg22majyxw4gmv6p", out PaymentAddress addr));
     Assert.NotNull(addr);
     Assert.True(addr.IsValid);
     addr.Dispose();
 }
Exemplo n.º 2
0
 public async Task GetConfirmedTransactionsAsync()
 {
     using (var address = new PaymentAddress("bchtest:qp7d6x2weeca9fn6eakwvgd9ryq8g6h0tuyks75rt7"))
         using (var ret = await nodeFixture_.Node.Chain.GetConfirmedTransactionsAsync(address, 10, 1)) {
             Assert.True(ret.Result.Count >= 0);
         }
 }
Exemplo n.º 3
0
        private List <Utxo> GetUnconfirmedUtxo(PaymentAddress address)
        {
            var unconfirmedUtxo = new List <Utxo>();

            using (var addresslist = new PaymentAddressList())
            {
                addresslist.Add(address);
                using (var unconfirmedTxs = chain_.GetMempoolTransactions(addresslist, nodeExecutor_.UseTestnetRules))
                {
                    foreach (var unconfirmedTx in unconfirmedTxs)
                    {
                        unconfirmedUtxo.Add(new Utxo
                        {
                            address       = address.Encoded,
                            txid          = Binary.ByteArrayToHexString(unconfirmedTx.Hash),
                            vout          = 0, //TODO FIX replace with proper tx index
                            amount        = Utils.SatoshisToCoinUnits(unconfirmedTx.TotalOutputValue),
                            satoshis      = (long)unconfirmedTx.TotalOutputValue,
                            height        = -1,
                            confirmations = 0
                        });
                    }
                }
            }

            return(unconfirmedUtxo);
        }
Exemplo n.º 4
0
 public async Task GetConfirmedTransactionsAsync()
 {
     using (var address = new PaymentAddress("1PDatg81sEwirJU3QUKcGLyfQC6epZNyiL"))
         using (var ret = await nodeFixture_.Node.Chain.GetConfirmedTransactionsAsync(address, 10, 1)) {
             Assert.True(ret.Result.Count >= 0);
         }
 }
Exemplo n.º 5
0
        private static async Task <UInt64> SumAddressInputs(ITransaction tx, PaymentAddress address, IChain chain, bool useTestnetRules)
        {
            UInt64 inputSum = 0;

            foreach (Input input in tx.Inputs)
            {
                if (input.PreviousOutput == null)
                {
                    continue;
                }
                using (var getTxResult = await chain.FetchTransactionAsync(input.PreviousOutput.Hash, false))
                {
                    if (getTxResult.ErrorCode == ErrorCode.NotFound)
                    {
                        continue;
                    }
                    CheckBitprimApiErrorCode(getTxResult.ErrorCode, "FetchTransactionAsync(" + Binary.ByteArrayToHexString(input.PreviousOutput.Hash) + ") failed, check error log");
                    Output referencedOutput = getTxResult.Result.Tx.Outputs[input.PreviousOutput.Index];
                    if (referencedOutput.PaymentAddress(useTestnetRules).Encoded == address.Encoded)
                    {
                        inputSum += referencedOutput.Value;
                    }
                }
            }
            return(inputSum);
        }
Exemplo n.º 6
0
        public void TestGetAssetsByAddress()
        {
            using (var address = new PaymentAddress("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t"))
            {
                using (var assets = keokenManager_.GetAssetsByAddress(address))
                {
                    Assert.Equal <UInt64>(2, assets.Count);

                    foreach (GetAssetsByAddressData asset in assets)
                    {
                        if (asset.AssetId == 1)
                        {
                            Assert.Equal(1000000, asset.Amount);
                            Assert.Equal("Bitprim", asset.AssetName);
                            Assert.Equal("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t", asset.AssetCreator.Encoded);
                        }
                        else
                        {
                            Assert.Equal <UInt32>(2, asset.AssetId);
                            Assert.Equal(90, asset.Amount);
                            Assert.Equal("HanchonCoin", asset.AssetName);
                            Assert.Equal("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t", asset.AssetCreator.Encoded);
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        private async Task <GetTransactionsResponse> GetTransactionsBySingleAddress(string paymentAddress, bool pageResults, uint pageNum, bool noAsm, bool noScriptSig, bool noSpend)
        {
            Utils.CheckIfChainIsFresh(chain_, config_.AcceptStaleRequests);

            using (var address = new PaymentAddress(paymentAddress))
                using (var getTransactionResult = await chain_.FetchConfirmedTransactionsAsync(address, UInt64.MaxValue, 0))
                {
                    Utils.CheckBitprimApiErrorCode(getTransactionResult.ErrorCode, "FetchTransactionAsync(" + paymentAddress + ") failed, check error log.");

                    var txIds    = getTransactionResult.Result;
                    var txs      = new List <TransactionSummary>();
                    var pageSize = pageResults ? (uint)config_.TransactionsByAddressPageSize : txIds.Count;

                    for (uint i = 0; i < pageSize && (pageNum * pageSize + i < txIds.Count); i++)
                    {
                        var txHash = txIds[(pageNum * pageSize + i)];
                        using (var getTxResult = await chain_.FetchTransactionAsync(txHash, true))
                        {
                            Utils.CheckBitprimApiErrorCode(getTxResult.ErrorCode, "FetchTransactionAsync(" + Binary.ByteArrayToHexString(txHash) + ") failed, check error log");
                            bool confirmed = CheckIfTransactionIsConfirmed(getTxResult.Result);
                            txs.Add(await TxToJSON(getTxResult.Result.Tx, getTxResult.Result.TxPosition.BlockHeight, confirmed, noAsm, noScriptSig, noSpend));
                        }
                    }
                    UInt64 pageCount = (UInt64)Math.Ceiling((double)txIds.Count / (double)pageSize);
                    List <TransactionSummary> unconfirmedTxs = await GetUnconfirmedTransactions(address, noAsm, noScriptSig, noSpend);

                    txs = unconfirmedTxs.Concat(txs).ToList(); //Unconfirmed txs go first
                    return(new GetTransactionsResponse {
                        pagesTotal = pageCount, txs = txs.ToArray()
                    });
                }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Calculates the amount of sales tax required for the current shopping cart.
        /// We are deliberately applying tax to the shipping cost, so the shipping cost can change based on the
        /// address the user provides.
        /// </summary>
        private static void CalculateTax(PaymentAddress shippingAddress, decimal subtotal, decimal shippingCost, out decimal subtotalTax, out decimal shippingTax)
        {
            subtotalTax = 0;
            shippingTax = 0;

            if (shippingAddress == null)
            {
                return;
            }

            //
            // WARNING!
            //
            // THIS CODE IS FOR EXAMPLE PURPOSES ONLY. IT HAS NO BASIS IN REALITY. ANY SIMILARITIES TO ANY
            // REAL TAX CODES IS COINCIDENTAL AND UNINTENTIONAL.
            //
            switch (shippingAddress.Country.ToUpperInvariant())
            {
            case "US":
            case "USA":
            case "UNITED STATES":
            case "UNITED STATES OF AMERICA":
                switch (shippingAddress.Region.ToUpperInvariant())
                {
                case "WA":
                case "WASHINGTON":
                case "WASHINGTON STATE":
                    subtotalTax = subtotal * 0.2m;
                    shippingTax = shippingCost * 0.2m;
                    return;
                }
                break;
            }
        }
Exemplo n.º 9
0
 public void MainnetLegacyAddressOK()
 {
     Assert.True(PaymentAddress.TryParse("1P3GQYtcWgZHrrJhUa4ctoQ3QoCU2F65nz", out PaymentAddress addr));
     Assert.NotNull(addr);
     Assert.True(addr.IsValid);
     addr.Dispose();
 }
        public void TestGetAssetsByAddressReturnsValidData()
        {
            using (var memoryState = new KeokenMemoryState())
                using (var address_source = new PaymentAddress("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t"))
                    using (var address_target = new PaymentAddress("my2dxGb5jz43ktwGxg2doUaEb9WhZ9PQ7K"))
                    {
                        byte[] hash = Binary.HexStringToByteArray("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
                        memoryState.InitialAssetId = 5;

                        memoryState.CreateAsset("test asset", 15, address_source, 10, hash);

                        memoryState.CreateBalanceEntry(5, 15, address_source, address_target, 5, hash);

                        using (var ret = memoryState.GetAssetsByAddress(address_target))
                        {
                            Assert.Equal <ulong>(1, ret.Count);

                            var data = ret[0];

                            Assert.Equal <uint>(5, data.AssetId);
                            Assert.Equal(15, data.Amount);
                            Assert.Equal("test asset", data.AssetName);
                            Assert.Equal(address_source.Encoded, data.AssetCreator.Encoded);
                        }
                    }
        }
Exemplo n.º 11
0
 private static IntPtr KeokenStateDelegatedGetAssetsByAddressHandlerInternal(IntPtr state, IntPtr addr)
 {
     using (var address = new PaymentAddress(addr))
     {
         return(internalState_.GetAssetsByAddress(address).NativeInstance);
     }
 }
Exemplo n.º 12
0
 public JSOutput(PaymentAddress addr, Fixed8 value, UInt256 Asset_ID)
 {
     this.addr    = addr;
     this.value   = value;
     this.memo    = new byte[0];
     this.AssetID = Asset_ID;
 }
        public void TestGetAssetsReturnsValidData()
        {
            using (var memoryState = new KeokenMemoryState())
                using (var address_source = new PaymentAddress("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t"))
                {
                    byte[] hash = Binary.HexStringToByteArray("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
                    memoryState.InitialAssetId = 5;

                    memoryState.CreateAsset("test asset", 15, address_source, 10, hash);
                    memoryState.CreateAsset("test asset2", 1500, address_source, 10, hash);


                    using (var ret = memoryState.GetAssets())
                    {
                        Assert.Equal <ulong>(2, ret.Count);
                        foreach (GetAssetsData data in ret)
                        {
                            if (data.AssetId == 5)
                            {
                                Assert.Equal(15, data.Amount);
                                Assert.Equal("test asset", data.AssetName);
                                Assert.Equal(address_source.Encoded, data.AssetCreator.Encoded);
                            }
                            else
                            {
                                Assert.Equal(1500, data.Amount);
                                Assert.Equal("test asset2", data.AssetName);
                                Assert.Equal(address_source.Encoded, data.AssetCreator.Encoded);
                            }
                        }
                    }
                }
        }
Exemplo n.º 14
0
 public void ConvertLegacyMainnetToCashAddrNoPrefix()
 {
     using (var address = new PaymentAddress(MAINNET_LEGACY_ADDR))
     {
         Assert.Equal(MAINNET_CASH_ADDR_NO_PREFIX, address.ToCashAddr(includePrefix: false));
     }
 }
Exemplo n.º 15
0
        private List <Utxo> GetUnconfirmedUtxo(PaymentAddress address)
        {
            var unconfirmedUtxo = new List <Utxo>();

            using (MempoolTransactionList unconfirmedTxs = chain_.GetMempoolTransactions(address, nodeExecutor_.UseTestnetRules))
            {
                foreach (MempoolTransaction unconfirmedTx in unconfirmedTxs)
                {
                    var satoshis = Int64.Parse(unconfirmedTx.Satoshis);

                    unconfirmedUtxo.Add(new Utxo
                    {
                        address = address.Encoded,
                        txid    = unconfirmedTx.Hash,
                        vout    = unconfirmedTx.Index,
                        //scriptPubKey = getTxEc == ErrorCode.Success ? GetOutputScript(tx.Outputs[outputPoint.Index]) : null,
                        amount        = Utils.SatoshisToCoinUnits(satoshis),
                        satoshis      = satoshis,
                        height        = -1,
                        confirmations = 0
                    });
                }
            }
            return(unconfirmedUtxo);
        }
Exemplo n.º 16
0
        private static async Task <HashSet <string> > GetAddressFromInput(Executor executor, ITransaction tx)
        {
            var ret = new HashSet <string>();

            if (tx.IsCoinbase)
            {
                return(ret);
            }

            foreach (Input input in tx.Inputs)
            {
                OutputPoint previousOutput = input.PreviousOutput;

                using (DisposableApiCallResult <GetTxDataResult> getTxResult = await executor.Chain.FetchTransactionAsync(previousOutput.Hash, false))
                {
                    Utils.CheckBitprimApiErrorCode(getTxResult.ErrorCode, "FetchTransactionAsync(" + Binary.ByteArrayToHexString(previousOutput.Hash) + ") failed, check errog log");

                    Output output = getTxResult.Result.Tx.Outputs[previousOutput.Index];

                    PaymentAddress outputAddress = output.PaymentAddress(executor.UseTestnetRules);
                    if (outputAddress.IsValid)
                    {
                        ret.Add(outputAddress.Encoded);
                    }
                }
            }

            return(ret);
        }
Exemplo n.º 17
0
 public void ConvertLegacyTestnetToCashAddr()
 {
     using (var address = new PaymentAddress(TESTNET_LEGACY_ADDR))
     {
         Assert.Equal(TESTNET_CASH_ADDR, address.ToCashAddr(includePrefix: true));
     }
 }
Exemplo n.º 18
0
 public IActionResult Pay(PaymentAddress PayAddress)
 {
     PayAddress.UserInfoId = 1;
     if (ModelState.IsValid)
     {
         if (db_context.PaymentAddress.Where(o => o.PaymentAddressId == PayAddress.PaymentAddressId).Count() > 0)
         {
             PaymentAddress pa = db_context.PaymentAddress.Where(o => o.PaymentAddressId == PayAddress.PaymentAddressId).FirstOrDefault();
             pa.AptNo   = PayAddress.AptNo;
             pa.Street  = PayAddress.Street;
             pa.State   = PayAddress.State;
             pa.City    = PayAddress.City;
             pa.ZipCode = PayAddress.ZipCode;
             foreach (PurchaseHistory ph in db_context.PurchaseHistory.Where(o => o.UserInfoId == 1 && o.IsPurchased == false))
             {
                 ph.IsPurchased = true;
             }
             db_context.SaveChanges();
         }
         else
         {
             db_context.PaymentAddress.Add(PayAddress);
             foreach (PurchaseHistory ph in db_context.PurchaseHistory.Where(o => o.UserInfoId == 1 && o.IsPurchased == false))
             {
                 ph.IsPurchased = true;
             }
             db_context.SaveChanges();
         }
         return(RedirectToAction("PurchaseHis"));
     }
     else
     {
         return(View());
     }
 }
Exemplo n.º 19
0
        public void PaymentAddressInitsWithNoArgs()
        {
            var paymentAddress = new PaymentAddress();

            Assert.NotNull(paymentAddress);
            Assert.IsType <PaymentAddress>(paymentAddress);
        }
Exemplo n.º 20
0
 private static Int64 KeokenStateDelegatedGetBalanceHandlerInternal(IntPtr state, UInt32 asset_id, IntPtr addr)
 {
     using (var address = new PaymentAddress(addr))
     {
         return(internalState_.GetBalance(asset_id, address));
     }
 }
        private async Task GetTransactionPositionsBySingleAddress(string paymentAddress, SortedSet <Tuple <Int64, string> > txPositions, Stopwatch stopWatch)
        {
            Utils.CheckIfChainIsFresh(chain_, config_.AcceptStaleRequests);

            using (var address = new PaymentAddress(paymentAddress))
            {
                //Unconfirmed first
                GetUnconfirmedTransactionPositions(address, txPositions);
                //3
                statsGetTransactions.Add(stopWatch.ElapsedMilliseconds);

                using (var getTransactionResult = await chain_.FetchConfirmedTransactionsAsync(address, UInt64.MaxValue, 0))
                {
                    Utils.CheckBitprimApiErrorCode(getTransactionResult.ErrorCode, "FetchConfirmedTransactionsAsync(" + paymentAddress + ") failed, check error log.");

                    //4
                    statsGetTransactions.Add(stopWatch.ElapsedMilliseconds);

                    INativeList <byte[]> confirmedTxIds = getTransactionResult.Result;

                    //Confirmed
                    foreach (byte[] txHash in confirmedTxIds)
                    {
                        ApiCallResult <GetTxPositionResult> getTxPosResult = await chain_.FetchTransactionPositionAsync(txHash, true);

                        string txHashStr = Binary.ByteArrayToHexString(txHash);
                        Utils.CheckBitprimApiErrorCode(getTxPosResult.ErrorCode, "FetchTransactionPositionAsync(" + txHashStr + ") failed, check error log");
                        txPositions.Add(new Tuple <Int64, string>((Int64)getTxPosResult.Result.BlockHeight, txHashStr));
                    }

                    //5
                    statsGetTransactions.Add(stopWatch.ElapsedMilliseconds);
                }
            }
        }
Exemplo n.º 22
0
 private static void KeokenStateDelegatedCreateAssetHandlerInternal(IntPtr state, string asset_name, Int64 asset_amount,
                                                                    IntPtr owner, UInt64 block_height, hash_t txid)
 {
     using (var owner_address = new PaymentAddress(owner))
     {
         internalState_.CreateAsset(asset_name, asset_amount, owner_address, block_height, txid.hash);
     }
 }
Exemplo n.º 23
0
 public async Task FetchHistoryAsync()
 {
     using (var address = new PaymentAddress("1PDatg81sEwirJU3QUKcGLyfQC6epZNyiL"))
         using (var ret = await executorFixture_.Executor.Chain.FetchHistoryAsync(address, 10, 1))
         {
             Assert.True(ret.Result.Count >= 0);
         }
 }
Exemplo n.º 24
0
        public IActionResult DeleteAddress(int PaymentAddressId)
        {
            ViewData["Message"] = "Delete Address.";
            PaymentAddress pa = db_context.PaymentAddress.Where(o => o.PaymentAddressId == PaymentAddressId).FirstOrDefault();

            db_context.PaymentAddress.Remove(pa);
            db_context.SaveChanges();
            return(RedirectToAction("Payment"));
        }
Exemplo n.º 25
0
 private static void KeokenStateDelegatedCreateBalanceEntryHandlerInternal(IntPtr state, UInt32 asset_id, Int64 asset_amount,
                                                                           IntPtr source, IntPtr target, UInt64 block_height, hash_t txid)
 {
     using (var source_address = new PaymentAddress(source))
         using (var target_address = new PaymentAddress(target))
         {
             internalState_.CreateBalanceEntry(asset_id, asset_amount, source_address, target_address, block_height, txid.hash);
         }
 }
Exemplo n.º 26
0
        private void btn_new_wallet_yes_Click(object sender, EventArgs e)
        {
            if (!CheckParameter())
            {
                return;
            }

            UserWallet wallet;

            if (chk_anonymous.Checked == true)
            {
                wallet = UserWallet.Create(txb_wallet_path.Text, txb_password.Text, KeyType.Anonymous);
            }
            else
            {
                wallet = UserWallet.Create(txb_wallet_path.Text, txb_password.Text, KeyType.Transparent);
            }


            Settings.Default.LastWalletPath = txb_wallet_path.Text;
            Settings.Default.Save();

            using (MainWalletForm dialog = new MainWalletForm(wallet))
            {
                this.Hide();
                FormManager.GetInstance().Push(dialog);
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
            }
            //Get hSig
            byte[] random_byte256 = new byte[32];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(random_byte256);
            }
            UInt256        hSig    = new UInt256(random_byte256);
            NoteEncryption noteEnc = new NoteEncryption(hSig);

            SpendingKey sk = SpendingKey.random();

            Console.Write("SpendingKey is " + sk.ToArray().ToHexString());
            Console.WriteLine();

            PaymentAddress addr  = sk.address();
            PaymentAddress addr1 = sk.address();


            byte[] plain_text  = { 0x74, 0x64, 0x64, 0x66, 0x23, 0x46, 0x54, 0x23, 0x32, 0x33, 0x33, 0x33, 0x33 };
            byte[] cipher_text = noteEnc.Encrypt(addr.pk_enc, plain_text);

            NoteDecryption noteDec = new NoteDecryption(sk.receiving_key());

            byte[] plain_text_m = noteDec.Decrypt(cipher_text, noteEnc.get_epk(), hSig, (char)0);
        }
Exemplo n.º 27
0
        public static async Task <Int64> CalculateBalanceDelta(ITransaction tx, string address, IChain chain, bool useTestnetRules)
        {
            using (var paymentAddress = new PaymentAddress(address))
            {
                Int64 inputsSum = (Int64) await SumAddressInputs(tx, paymentAddress, chain, useTestnetRules);

                Int64 outputsSum = (Int64)SumAddressOutputs(tx, paymentAddress, useTestnetRules);
                return(outputsSum - inputsSum);
            }
        }
Exemplo n.º 28
0
 public async Task FetchHistoryAsync()
 {
     using (var address = new PaymentAddress("bchtest:qp7d6x2weeca9fn6eakwvgd9ryq8g6h0tuyks75rt7"))
     {
         using (var ret = await executorFixture_.Executor.Chain.FetchHistoryAsync(address, 10, 1))
         {
             Assert.True(ret.Result.Count >= 0);
         }
     }
 }
Exemplo n.º 29
0
 public async Task GetHistoryAsync()
 {
     using (var address = new PaymentAddress("bchtest:qp7d6x2weeca9fn6eakwvgd9ryq8g6h0tuyks75rt7")) {
         using (var ret = await nodeFixture_.Node.Chain.GetHistoryAsync(address, 10, 1))
         {
             foreach (var x in ret.Result)
             {
             }
             Assert.True(ret.Result.Count >= 0);
         }
     }
 }
 public void TestCreateAsset()
 {
     using (var memoryState = new KeokenMemoryState())
         using (var address = new PaymentAddress("16TGufqQ9FPnEbixbD4ZjVabaP455roE6t"))
         {
             byte[] hash = Binary.HexStringToByteArray("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
             memoryState.InitialAssetId = 5;
             Assert.Equal(false, memoryState.StateAssetIdExists(5));
             memoryState.CreateAsset("test asset", 1547, address, 10, hash);
             Assert.Equal(true, memoryState.StateAssetIdExists(5));
         }
 }