/// <summary>
 /// Creates an UNSIGNED input that links to the given output
 /// </summary>
 internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, TransactionOutput output)
     : base(@params)
 {
     var outputIndex = output.Index;
     Outpoint = new TransactionOutPoint(@params, outputIndex, output.ParentTransaction);
     ScriptBytes = EmptyArray;
     _sequence = uint.MaxValue;
     ParentTransaction = parentTransaction;
 }
Exemple #2
0
        // The function MintTokens is only usable by the chosen wallet
        // contract to mint a number of tokens proportional to the
        // amount of neo sent to the wallet contract. The function
        // can only be called during the tokenswap period
        // 将众筹的neo转化为等价的ico代币
        public static bool MintTokens()
        {
            Transaction       tx        = (Transaction)ExecutionEngine.ScriptContainer;
            TransactionOutput reference = tx.GetReferences()[0];

            // check whether asset is neo
            // 检查资产是否为neo
            if (reference.AssetId != neo_asset_id)
            {
                return(false);
            }
            byte[] sender = reference.ScriptHash;
            TransactionOutput[] outputs = tx.GetOutputs();
            byte[] receiver             = ExecutionEngine.ExecutingScriptHash;
            ulong  value = 0;

            // get the total amount of Neo
            // 获取转入智能合约地址的Neo总量
            foreach (TransactionOutput output in outputs)
            {
                if (output.ScriptHash == receiver)
                {
                    value += (ulong)output.Value;
                }
            }
            uint now  = Blockchain.GetHeader(Blockchain.GetHeight()).Timestamp;
            int  time = (int)now - sales_start_time;
            // the current exchange rate between sales tokens and neo during the token swap period
            // 获取众筹期间token和neo间的转化率
            ulong swap_rate = CurrentSwapRate(time);

            // crowdfunding failure
            // 众筹失败
            if (swap_rate == 0)
            {
                Refund(sender, value);
                return(false);
            }
            value = InvestCapacity(time, sender, value);
            if (value == 0)
            {
                return(false);
            }
            // crowdfunding success
            // 众筹成功
            ulong      token   = value / neo_decimals * swap_rate;
            BigInteger balance = Storage.Get(Storage.CurrentContext, sender).AsBigInteger();

            Storage.Put(Storage.CurrentContext, sender, token + balance);
            BigInteger totalSupply = Storage.Get(Storage.CurrentContext, "totalSupply").AsBigInteger();

            Storage.Put(Storage.CurrentContext, "totalSupply", token + totalSupply);
            Transferred(null, sender, token);
            return(true);
        }
        public static Transaction CreateGlobalTransfer(SignDelegate sign)
        {
            string      preTxId = "0x7866a1aae60e7e6a2da87a681edf8c265db200ba68f4a96b447f85bb60c3594b";
            UInt256     hash    = UInt256.Parse(preTxId);
            Transaction tx1     = Blockchain.Singleton.GetTransaction(hash);

            Fixed8 preOutVal     = tx1.Outputs[100].Value;
            Fixed8 currentOutVal = new Fixed8(1 * (long)Math.Pow(10, 8));

            if (preOutVal < currentOutVal)
            {
                Console.WriteLine("insufficient fund");
                return(null);
            }

            var inputs = new List <CoinReference>
            {
                new CoinReference()
                {
                    PrevHash  = new UInt256(preTxId.Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 100
                }
            }.ToArray();

            var outputs = new List <TransactionOutput>();

            var output1 = new TransactionOutput()
            {
                AssetId    = UInt256.Parse(assetid),
                ScriptHash = "AYuApoS1MQvJMQF7J9GiMcCA9du7s6YBwo".ToScriptHash(),
                Value      = currentOutVal
            };

            outputs.Add(output1);
            if (preOutVal > currentOutVal)
            {
                var output2 = new TransactionOutput()
                {
                    AssetId    = UInt256.Parse(assetid),
                    ScriptHash = "AZi4EzuSSp4kiWCUvLZcWo8daymKf53ez6".ToScriptHash(),
                    Value      = preOutVal - currentOutVal
                };
                outputs.Add(output2);
            }

            var tx = new ContractTransaction()
            {
                Outputs    = outputs.ToArray(),
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0]
            };

            return(sign.Invoke(tx));
        }
        private static bool Output_GetAssetId(ExecutionEngine engine)
        {
            TransactionOutput output = engine.EvaluationStack.Pop().GetInterface <TransactionOutput>();

            if (output == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(output.AssetId.ToArray());
            return(true);
        }
Exemple #5
0
        private JObject ConvertTransactionOutputs(int index, TransactionOutput transactionOutput)
        {
            var json = new JObject();

            json["n"]       = index;
            json["asset"]   = transactionOutput.AssetId.ToString();
            json["value"]   = transactionOutput.Value.ToString();
            json["address"] = transactionOutput.ScriptHash.ToAddress();

            return(json);
        }
Exemple #6
0
        private static bool Output_GetScriptHash(ScriptEngine engine)
        {
            TransactionOutput output = engine.EvaluationStack.Pop().GetInterface <TransactionOutput>();

            if (output == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(output.ScriptHash.ToArray());
            return(true);
        }
Exemple #7
0
        public TestTransaction(UInt256 assetId, TransactionType type, UInt160 scriptHash) : base(type)
        {
            TransactionOutput transVal = new TransactionOutput();

            transVal.Value      = Fixed8.FromDecimal(50);
            transVal.AssetId    = assetId;
            transVal.ScriptHash = scriptHash;
            base.Outputs        = new TransactionOutput[1] {
                transVal
            };
        }
        protected virtual bool Output_GetValue(ExecutionEngine engine)
        {
            TransactionOutput output = engine.EvaluationStack.Pop().GetInterface <TransactionOutput>();

            if (output == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(output.Value.GetData());
            return(true);
        }
        /// <summary>
        /// Parses a Bitcoin transaction output.
        /// </summary>
        /// <param name="blockMemoryStreamReader">
        /// Provides access to a section of the Bitcoin blockchain file.
        /// </param>
        /// <returns>
        /// The Bitcoin transaction output that was parsed.
        /// </returns>
        private static TransactionOutput ParseTransactionOutput(BlockMemoryStreamReader blockMemoryStreamReader)
        {
            TransactionOutput transactionOutput = new TransactionOutput();

            transactionOutput.OutputValueSatoshi = blockMemoryStreamReader.ReadUInt64();
            int scriptLength = (int)blockMemoryStreamReader.ReadVariableLengthInteger();

            transactionOutput.OutputScript = new ByteArray(blockMemoryStreamReader.ReadBytes(scriptLength));

            return(transactionOutput);
        }
Exemple #10
0
        public void VoidTransaction_InvalidAuthorizationId_ReturnsError()
        {
            Mock <HttpMessageHandler> mockHttpHandler = GetHttpHandlerMock("success");
            Mock <IPaymentRepository> mockRepository  = GetMockRepository();
            PaymentService            service         = GetService(mockRepository, mockHttpHandler);

            TransactionOutput output = service.VoidTransaction(2).Result;

            Assert.IsNotNull(output.Error);
            Assert.IsTrue(output.Error.Length > 0);
        }
Exemple #11
0
        public void VoidTransaction_ServiceReturnsFailure_ReturnsError()
        {
            Mock <HttpMessageHandler> mockHttpHandler = GetHttpHandlerMock("fail");
            Mock <IPaymentRepository> mockRepository  = GetMockRepository();
            PaymentService            service         = GetService(mockRepository, mockHttpHandler);

            TransactionOutput output = service.VoidTransaction(1).Result;

            Assert.IsNotNull(output.Error);
            Assert.IsTrue(output.Error.Length > 0);
        }
Exemple #12
0
        protected virtual bool Output_GetAssetId(ExecutionEngine engine)
        {
            TransactionOutput output = (engine.EvaluationStack.Pop() as VM.Types.InteropInterface).GetInterface <TransactionOutput>();

            if (output == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(output.AssetId.ToArray());
            return(true);
        }
Exemple #13
0
        public DepositOutput(
            Credit credit,
            Amount updatedBalance)
        {
            Transaction = new TransactionOutput(
                credit.Description,
                credit.Amount,
                credit.TransactionDate);

            UpdatedBalance = updatedBalance;
        }
        protected virtual bool Output_GetScriptHash(ExecutionEngine engine)
        {
            TransactionOutput output = engine.EvaluationStack.Pop().GetInterface <TransactionOutput>();

            if (output == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(output.ScriptHash.ToArray());
            return(true);
        }
Exemple #15
0
        public Transaction ReadTransaction(LoggedBinaryReader binaryReader)
        {
            var version = binaryReader.ReadUInt32();

            var countTransactionInputs = _hexReader.ReadVarInt(binaryReader, Endian.Little, out _);
            var hasWitness             = countTransactionInputs == 0;

            if (hasWitness)
            {
                // todo: use SegWit
                var __ = binaryReader.ReadByte();

                countTransactionInputs = _hexReader.ReadVarInt(binaryReader, Endian.Little, out _);
            }

            // todo: use transaction input pool here
            var transactionInputs = new TransactionInput[countTransactionInputs];

            for (var i = 0; i < countTransactionInputs; i++)
            {
                transactionInputs[i] = ReadTransactionInput(binaryReader);
            }

            var countTransactionOutputs = _hexReader.ReadVarInt(binaryReader, Endian.Little, out _);

            // todo: use transaction output pool here
            var transactionOutputs = new TransactionOutput[countTransactionOutputs];

            for (var i = 0; i < countTransactionOutputs; i++)
            {
                transactionOutputs[i] = ReadTransactionOutput(binaryReader);
            }

            var witnessAsciiStrings = new List <AsciiString>();

            if (hasWitness)
            {
                for (var i = 0; i < countTransactionInputs; i++)
                {
                    var countWitnessStackItems = _hexReader.ReadVarInt(binaryReader, Endian.Little, out _);
                    for (var j = 0; j < countWitnessStackItems; j++)
                    {
                        witnessAsciiStrings.Add(_hexReader.ReadVarString(binaryReader));
                    }
                }
            }

            var lockTime = binaryReader.ReadUInt32();

            var txId = GetTrxId(binaryReader.AsSpan());

            return(new Transaction(txId, version, transactionInputs, transactionOutputs, lockTime, hasWitness, witnessAsciiStrings));
        }
Exemple #16
0
        public async Task <SignedTransaction> SendAsset(byte[] toAddress, string symbol, decimal amount)
        {
            var toScriptHash = toAddress.ToScriptHash().ToArray(); //TODO test this
            var target       = new TransactionOutput {
                AddressHash = toScriptHash, Amount = amount
            };
            var targets = new List <TransactionOutput> {
                target
            };

            return(await SendAsset(_accountKey, symbol, targets));
        }
        public void PerformFundTransfer(Fixed8 amountToTransfer, UInt160 destinationScriptHash, IInventory assetId, UInt160 fromAddress)
        {
            //  public UInt160 ChangeAddress => Wallet.ToScriptHash((string)comboBox1.SelectedItem);

            var tx        = new ContractTransaction();
            var neoOutput = new TransactionOutput();

            neoOutput.AssetId    = assetId.Hash;
            neoOutput.Value      = amountToTransfer;
            neoOutput.ScriptHash = destinationScriptHash;
            tx.Outputs           = new[] { neoOutput };

            var walletTx = NeoWallet.MakeTransaction(tx, fromAddress);

            if (walletTx == null)
            {
                throw new ApplicationException("Wallet TX was null. Possibly insufficient funds");
            }

            ContractParametersContext context;

            try
            {
                context = new ContractParametersContext(walletTx);
            }
            catch (InvalidOperationException)
            {
                throw new ApplicationException("unsynchronized block");
            }

            var sign = NeoWallet.Sign(context);

            if (context.Completed)
            {
                context.Verifiable.Scripts = context.GetScripts();
                NeoWallet.ApplyTransaction(walletTx); //changes with different versions of NEO
                var relay = _node.Relay(walletTx);

                //TODO: make this use our transaction watcher
                var originalHeight = Blockchain.Default.Height; //store the height we sent at then wait for the next block
                //possibly check if sign/relay/save has actually worked?

                while (Blockchain.Default.Height <= originalHeight + 1)
                {
                    Thread.Sleep(1000);                                                     //wait for next block
                }
            }
            else
            {
                throw new ApplicationException("Incompleted Signature");
            }
        }
Exemple #18
0
        /// <summary>
        /// The first transaction sends all NEO to contract 'managed' by 2/3 + 1 of the validators.
        /// </summary>
        /// <returns>The governing token transaction output.</returns>
        private static TransactionOutput GenesisGoverningTokenTransactionOutput()
        {
            var genesisContract = GenesisValidatorsContract();

            var transactionOutput = new TransactionOutput
            {
                AssetId    = GoverningTokenRegisterTransaction.Hash,
                Value      = GoverningTokenRegisterTransaction.Amount,
                ScriptHash = genesisContract.ScriptHash
            };

            return(transactionOutput);
        }
Exemple #19
0
        private void ProcessPaymentOutputForEmailInvoice(EmailInvoice emailInvoice, TransactionOutput output, bool sendEmailFlag)
        {
            if (output.Status && !output.Has3DSecure)
            {
                // Create order payment
                var orderPayment = new OrderPayment
                {
                    OrderId      = emailInvoice.OrderId,
                    TimeStamp    = DateTime.Now,
                    Amount       = emailInvoice.Amount,
                    CurrencyCode = emailInvoice.CurrencyCode,
                    ExchangeRate = emailInvoice.ExchangeRate,
                    IsCompleted  = true
                };

                int orderPaymentId = _orderPaymentRepository.Create(orderPayment);

                // Update email invoice
                emailInvoice.OrderPaymentId = orderPaymentId;
                emailInvoice.Paid           = true;
                emailInvoice.DatePaid       = DateTime.Now;

                _emailInvoiceRepository.Update(emailInvoice);

                // Save to comment
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<b>{0}</b>", "Payment Complete");

                string address = BuildEmailInvoiceBillingAddress(emailInvoice);
                string amount  = string.Format("{0}{1:0.00}",
                                               emailInvoice.CurrencyCode,
                                               Math.Round(emailInvoice.Amount * emailInvoice.ExchangeRate, 2, MidpointRounding.AwayFromZero));
                string message = string.Format("Payment Reference:<br/>{0}<br/><br/>Ammount:<br/>{1}<br/><br/>{2}",
                                               emailInvoice.PaymentRef,
                                               amount,
                                               address);

                _orderService.ProcessOrderCommentInsertion(emailInvoice.OrderId,
                                                           emailInvoice.ProfileId,
                                                           emailInvoice.FirstName,
                                                           "Payment Complete",
                                                           message,
                                                           string.Empty);

                // Send confirmation email if needed
                if (sendEmailFlag)
                {
                    _emailManager.SendPaymentInvoiceConfirmationEmail(emailInvoice.Email, emailInvoice.FirstName, amount);
                }
            }
        }
Exemple #20
0
        public async Task <IActionResult> Void(VoidRequest request)
        {
            TransactionOutput serviceResponse = await _service.VoidTransaction(request.AuthorizationId);

            StatusResponse response = new StatusResponse
            {
                AmountAvailable = serviceResponse.AmountAvailable,
                Currency        = serviceResponse.Currency,
                Error           = serviceResponse.Error,
                Success         = serviceResponse.Success
            };

            return(Ok(response));
        }
 public static Transaction CreateFakeTx(NetworkParameters @params, ulong nanocoins, Address to)
 {
     var t = new Transaction(@params);
     var o1 = new TransactionOutput(@params, t, nanocoins, to);
     t.AddOutput(o1);
     // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't
     // matter for our purposes.
     var prevTx = new Transaction(@params);
     var prevOut = new TransactionOutput(@params, prevTx, nanocoins, to);
     prevTx.AddOutput(prevOut);
     // Connect it.
     t.AddInput(prevOut);
     return t;
 }
Exemple #22
0
        // The function MintTokens is only usable by the chosen wallet
        // contract to mint a number of tokens proportional to the
        // amount of neo sent to the wallet contract. The function
        // can only be called during the tokenswap period
        // 将众筹的neo转化为等价的RPX tokens
        private static bool MintTokens()
        {
            uint decimals_rate = 100000000;

            //检查转入资产是否为小蚁股
            byte[]           neo_asset_id = new byte[] { 197, 111, 51, 252, 110, 207, 205, 12, 34, 92, 74, 179, 86, 254, 229, 147, 144, 175, 133, 96, 190, 14, 147, 15, 174, 190, 116, 166, 218, 255, 124, 155 };
            Transaction      trans        = (Transaction)ExecutionEngine.ScriptContainer;
            TransactionInput trans_input  = trans.GetInputs()[0];

            byte[]            prev_hash         = trans_input.PrevHash;
            Transaction       prev_trans        = Blockchain.GetTransaction(prev_hash);
            TransactionOutput prev_trans_output = prev_trans.GetOutputs()[trans_input.PrevIndex];

            if (!BytesEqual(prev_trans_output.AssetId, neo_asset_id))
            {
                return(false);
            }
            byte[] sender = prev_trans_output.ScriptHash;
            TransactionOutput[] trans_outputs = trans.GetOutputs();
            byte[] receiver = ExecutionEngine.ExecutingScriptHash;
            //统计转入到当前合约地址output的总和
            long value = 0;

            foreach (TransactionOutput trans_output in trans_outputs)
            {
                if (BytesEqual(trans_output.ScriptHash, receiver))
                {
                    value += trans_output.Value;
                }
            }
            //获得当前bonus并计算实际所得
            uint swap_rate = CurrentSwapRate();

            if (swap_rate == 0)
            {
                byte[] refund       = Storage.Get(Storage.CurrentContext, "refund");
                byte[] sender_value = IntToBytes(value);
                byte[] new_refund   = refund.Concat(sender.Concat(IntToBytes(sender_value.Length).Concat(sender_value)));
                Storage.Put(Storage.CurrentContext, "refund", new_refund);
                return(false);
            }
            long token = value * swap_rate * decimals_rate;
            //落账
            BigInteger total_token = BytesToInt(Storage.Get(Storage.CurrentContext, sender));

            Storage.Put(Storage.CurrentContext, sender, IntToBytes(token + total_token));
            byte[] totalSypply = Storage.Get(Storage.CurrentContext, "totalSypply");
            Storage.Put(Storage.CurrentContext, "totalSypply", IntToBytes(token + BytesToInt(totalSypply)));
            return(true);
        }
Exemple #23
0
 private bool Output_GetScriptHash(ExecutionEngine engine)
 {
     if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
     {
         TransactionOutput output = _interface.GetInterface <TransactionOutput>();
         if (output == null)
         {
             return(false);
         }
         engine.CurrentContext.EvaluationStack.Push(output.ScriptHash.ToArray());
         return(true);
     }
     return(false);
 }
 private bool Output_GetValue(ExecutionEngine engine)
 {
     if (engine.CurrentContext.EvaluationStack.Pop() is InteropContract _interface)
     {
         TransactionOutput output = _interface.GetInterface <TransactionOutput>();
         if (output == null)
         {
             return(false);
         }
         engine.CurrentContext.EvaluationStack.Push(output.Value.GetData());
         return(true);
     }
     return(false);
 }
Exemple #25
0
        private void button2_Click(object sender, EventArgs e)
        {
            IEnumerable <CoinReference>     inputs;
            IEnumerable <TransactionOutput> outputs;
            JObject json = JObject.Parse(textBox2.Text);

            if (json.ContainsProperty("hex"))
            {
                ContractTransaction tx_mine   = JsonToRequest(JObject.Parse(textBox3.Text));
                ContractTransaction tx_others = (ContractTransaction)ContractParametersContext.FromJson(json).Verifiable;
                inputs = tx_others.Inputs.Except(tx_mine.Inputs);
                List <TransactionOutput> outputs_others = new List <TransactionOutput>(tx_others.Outputs);
                foreach (TransactionOutput output_mine in tx_mine.Outputs)
                {
                    TransactionOutput output_others = outputs_others.FirstOrDefault(p => p.AssetId == output_mine.AssetId && p.Value == output_mine.Value && p.ScriptHash == output_mine.ScriptHash);
                    if (output_others == null)
                    {
                        MessageBox.Show(LanHelper.LocalLanguage("Validation failed, the counterparty falsified the transaction content!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    outputs_others.Remove(output_others);
                }
                outputs = outputs_others;
            }
            else
            {
                ContractTransaction tx_others = JsonToRequest(json);
                inputs  = tx_others.Inputs;
                outputs = tx_others.Outputs;
            }
            try
            {
                if (inputs.Select(p => Blockchain.Singleton.GetTransaction(p.PrevHash).Outputs[p.PrevIndex].ScriptHash).Distinct().Any(p => Program.CurrentWallet.Contains(p)))
                {
                    MessageBox.Show(LanHelper.LocalLanguage("Validation failed, the counterparty generated illegal transaction content!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(LanHelper.LocalLanguage("Validation failed, invalid transaction or unsynchronized blockchain, please try again when synchronized!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            outputs = outputs.Where(p => Program.CurrentWallet.Contains(p.ScriptHash));
            using (TradeVerificationDialog dialog = new TradeVerificationDialog(outputs))
            {
                button3.Enabled = dialog.ShowDialog() == DialogResult.OK;
            }
        }
Exemple #26
0
        private void button2_Click(object sender, EventArgs e)
        {
            IEnumerable <CoinReference>     inputs;
            IEnumerable <TransactionOutput> outputs;
            JObject json = JObject.Parse(textBox2.Text);

            if (json.ContainsProperty("hex"))
            {
                ContractTransaction tx_mine   = JsonToRequest(JObject.Parse(textBox3.Text));
                ContractTransaction tx_others = (ContractTransaction)SignatureContext.FromJson(json).Verifiable;
                inputs = tx_others.Inputs.Except(tx_mine.Inputs);
                List <TransactionOutput> outputs_others = new List <TransactionOutput>(tx_others.Outputs);
                foreach (TransactionOutput output_mine in tx_mine.Outputs)
                {
                    TransactionOutput output_others = outputs_others.FirstOrDefault(p => p.AssetId == output_mine.AssetId && p.Value == output_mine.Value && p.ScriptHash == output_mine.ScriptHash);
                    if (output_others == null)
                    {
                        MessageBox.Show(Strings.TradeFailedFakeDataMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    outputs_others.Remove(output_others);
                }
                outputs = outputs_others;
            }
            else
            {
                ContractTransaction tx_others = JsonToRequest(json);
                inputs  = tx_others.Inputs;
                outputs = tx_others.Outputs;
            }
            try
            {
                if (inputs.Select(p => Blockchain.Default.GetTransaction(p.PrevHash).Outputs[p.PrevIndex].ScriptHash).Distinct().Any(p => Program.CurrentWallet.ContainsAddress(p)))
                {
                    MessageBox.Show(Strings.TradeFailedInvalidDataMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(Strings.TradeFailedNoSyncMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            outputs = outputs.Where(p => Program.CurrentWallet.ContainsAddress(p.ScriptHash));
            using (TradeVerificationDialog dialog = new TradeVerificationDialog(outputs))
            {
                button3.Enabled = dialog.ShowDialog() == DialogResult.OK;
            }
        }
Exemple #27
0
        // Gets the amount of assest depositied
        private static BigInteger GetTransactionAmount(byte[] asset)
        {
            // Gets the sender transaction object [AssetId, ScriptHash, Value]
            TransactionOutput senderObject = GetSenderObjectForAsset(GetSenderObjects(), asset);

            BigInteger actualAmount = (long)senderObject.Value / (long)100000000;

            // If the transaction asset matches return the amount
            if (senderObject.AssetId == asset)
            {
                return(actualAmount);
            }

            return(actualAmount);
        }
        public void TestCreation()
        {
            var previousOutput = new TransactionInput.OutPoint(
                transactionHash: new byte[] { 0x48, 0x4d, 0x40, 0xd4, 0x5b, 0x9e, 0xa0, 0xd6, 0x52, 0xfc, 0xa8, 0x25, 0x8a, 0xb7, 0xca, 0xa4, 0x25, 0x41, 0xeb, 0x52, 0x97, 0x58, 0x57, 0xf9, 0x6f, 0xb5, 0x0c, 0xd7, 0x32, 0xc8, 0xb4, 0x81 },
                index: 0
                );

            var input  = new TransactionInput(previousOutput, "");
            var output = new TransactionOutput(91234, "");

            var transaction = new Transaction(
                new[] { input },
                new[] { output }
                );
        }
        private void TransactAction(Account[] accountPair)
        {
            Program.CurrentWallet = accountPair[0].Wallet;
            int curWalletAmount = int.Parse(Program.CurrentWallet.GetAvailable(Blockchain.GoverningToken.Hash).ToString());

            if (direction)
            {
                accountB.walletAccounts[index] = accountB.Wallet.CreateAccount();
                accountB.Save();
                TransactionOutput[] outputs = new TransactionOutput[1];

                outputs[0] = new TransactionOutput
                {
                    AssetId    = Blockchain.GoverningToken.Hash,
                    ScriptHash = Wallet.ToScriptHash(accountPair[1].walletAccounts[index++].Address),
                    Value      = Fixed8.Parse(amount.ToString())
                };

                if (curWalletAmount >= amount)
                {
                    TransactProcess(outputs, Program.CurrentWallet);
                }
                else
                {
                    Thread.Sleep(16000);
                }
            }
            else
            {
                TransactionOutput[] outputs = new TransactionOutput[1];

                outputs[0] = new TransactionOutput
                {
                    AssetId    = Blockchain.GoverningToken.Hash,
                    ScriptHash = Wallet.ToScriptHash(accountPair[1].Address),
                    Value      = Fixed8.Parse(amount.ToString())
                };

                if (curWalletAmount >= amount)
                {
                    TransactProcess(outputs, Program.CurrentWallet);
                }
                else
                {
                    Thread.Sleep(16000);
                }
            }
        }
        public void CapturePayment_Success_ReturnsCorrectAvailableAmount()
        {
            Mock <HttpMessageHandler> mockHttpHandler = GetHttpHandlerMock("success");
            Mock <IPaymentRepository> mockRepository  = GetMockRepository();
            PaymentRequest            request         = new PaymentRequest
            {
                Amount          = 10.00M,
                AuthorizationId = 1
            };

            PaymentService service = GetService(mockRepository, mockHttpHandler);

            TransactionOutput output = service.CapturePayment(request).Result;

            Assert.IsTrue(output.AmountAvailable == 5M);
        }
Exemple #31
0
        private static Transaction CreateFakeTx(ulong nanocoins, Address to)
        {
            var t  = new Transaction(_params);
            var o1 = new TransactionOutput(_params, t, nanocoins, to);

            t.AddOutput(o1);
            // Make a previous tx simply to send us sufficient coins. This previous tx is not really valid but it doesn't
            // matter for our purposes.
            var prevTx  = new Transaction(_params);
            var prevOut = new TransactionOutput(_params, prevTx, nanocoins, to);

            prevTx.AddOutput(prevOut);
            // Connect it.
            t.AddInput(prevOut);
            return(t);
        }
Exemple #32
0
        protected virtual void ReadOutputs(BinaryReader reader, Transaction transaction)
        {
            var ouputs = ReadCompactSize(reader);

            foreach (var index in Range.UInt64(0, ouputs - 1))
            {
                var output = new TransactionOutput();

                output.Index = (int)index;
                output.Value = reader.ReadInt64();
                var scriptLen = ReadCompactSize(reader);
                output.ScriptBytes = reader.ReadBytes((int)scriptLen);

                transaction.Outputs.Add(output);
            }
        }
Exemple #33
0
 public BlockContext(Block _block, TransactionOutput[][] _prevTxOutss, long _feesRawAmount, Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> _unspentTxOuts, Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> _spentTxOuts)
 {
     block = _block;
     prevTxOutss = _prevTxOutss;
     feeRawAmount = _feesRawAmount;
     unspentTxOuts = _unspentTxOuts;
     spentTxOuts = _spentTxOuts;
 }
 /// <summary>
 /// Adds the given output to this transaction. The output must be completely initialized.
 /// </summary>
 public void AddOutput(TransactionOutput to)
 {
     to.ParentTransaction = this;
     _outputs.Add(to);
 }
 /// <summary>
 /// Adds an input to this transaction that imports value from the given output. Note that this input is NOT
 /// complete and after every input is added with addInput() and every output is added with addOutput(),
 /// signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be
 /// accepted by the network.
 /// </summary>
 public void AddInput(TransactionOutput from)
 {
     AddInput(new TransactionInput(Params, this, from));
 }
Exemple #36
0
 public void Transactions()
 {
     // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
     var tx = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress);
     // Now add another output (ie, change) that goes to some other address.
     var someOtherGuy = new EcKey().ToAddress(_params);
     var output = new TransactionOutput(_params, tx, Utils.ToNanoCoins(0, 5), someOtherGuy);
     tx.AddOutput(output);
     // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
     // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
     // transactions you can't check they add up.
     _wallet.Receive(tx, null, BlockChain.NewBlockType.BestChain);
     // Now the other guy creates a transaction which spends that change.
     var tx2 = new Transaction(_params);
     tx2.AddInput(output);
     tx2.AddOutput(new TransactionOutput(_params, tx2, Utils.ToNanoCoins(0, 5), _myAddress));
     // tx2 doesn't send any coins from us, even though the output is in the wallet.
     Assert.AreEqual(Utils.ToNanoCoins(0, 0), tx2.GetValueSentFromMe(_wallet));
 }
 /// <exception cref="ProtocolException"/>
 protected override void Parse()
 {
     _version = ReadUint32();
     // First come the inputs.
     var numInputs = ReadVarInt();
     _inputs = new List<TransactionInput>((int) numInputs);
     for (var i = 0UL; i < numInputs; i++)
     {
         var input = new TransactionInput(Params, this, Bytes, Cursor);
         _inputs.Add(input);
         Cursor += input.MessageSize;
     }
     // Now the outputs
     var numOutputs = ReadVarInt();
     _outputs = new List<TransactionOutput>((int) numOutputs);
     for (var i = 0UL; i < numOutputs; i++)
     {
         var output = new TransactionOutput(Params, this, Bytes, Cursor);
         _outputs.Add(output);
         Cursor += output.MessageSize;
     }
     _lockTime = ReadUint32();
 }
Exemple #38
0
            public TestWindow(Program.Logger _logger)
            {
                StackPanel sp1 = null;
                StackPanel sp2 = null;

                EventHandler<Program.LogData> _LoggerLogAdded = (sender, e) => ((Action)(() =>
                {
                    TextBlock tb = new TextBlock();
                    tb.Text = e.Text;
                    tb.Foreground = e.Kind == Program.LogData.LogKind.error ? Brushes.Red : Brushes.White;
                    tb.Margin = new Thickness(0.0, 10.0, 0.0, 10.0);

                    sp2.Children.Add(tb);
                })).BeginExecuteInUIThread();

                Loaded += (sender, e) =>
                {
                    Grid grid = new Grid();
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    grid.ColumnDefinitions.Add(new ColumnDefinition());

                    ScrollViewer sv1 = new ScrollViewer();
                    sv1.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sv1.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sv1.SetValue(Grid.RowProperty, 0);
                    sv1.SetValue(Grid.ColumnProperty, 0);

                    sp1 = new StackPanel();
                    sp1.Background = Brushes.Black;

                    ScrollViewer sv2 = new ScrollViewer();
                    sv2.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sv2.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sv2.SetValue(Grid.RowProperty, 1);
                    sv2.SetValue(Grid.ColumnProperty, 0);

                    sp2 = new StackPanel();
                    sp2.Background = Brushes.Black;

                    sv1.Content = sp1;
                    sv2.Content = sp2;

                    TextBox tb = new TextBox();
                    tb.SetValue(Grid.RowProperty, 2);
                    tb.SetValue(Grid.ColumnProperty, 0);

                    grid.Children.Add(sv1);
                    grid.Children.Add(sv2);
                    grid.Children.Add(tb);

                    Content = grid;

                    Console.SetOut(new TextBlockStreamWriter(sp1));

                    _logger.LogAdded += _LoggerLogAdded;

                    //SimulationWindow sw = new SimulationWindow();
                    //sw.ShowDialog();

                    this.StartTask(string.Empty, string.Empty, () =>
                    {


                        //string testPrivateRsaParameters;
                        //using (RSACryptoServiceProvider rsacsp = new RSACryptoServiceProvider(2048))
                        //    testPrivateRsaParameters = rsacsp.ToXmlString(true);


                        //RealInboundChennel ric = new RealInboundChennel(7777, RsaKeySize.rsa2048, 100);
                        //ric.Accepted += (sender2, e2) =>
                        //{
                        //    this.StartTask("", "", () =>
                        //    {
                        //        e2.WriteBytes(BitConverter.GetBytes(true));

                        //        bool b = BitConverter.ToBoolean(e2.ReadBytes(), 0);

                        //        SessionChannel sc = e2.NewSession();
                        //        sc.WriteBytes(BitConverter.GetBytes(true));
                        //        sc.Close();

                        //        //e2.Close();
                        //    });


                        //    //e2.Close();

                        //    //Console.WriteLine("");
                        //};
                        //ric.RequestAcceptanceStart();


                        //AutoResetEvent are = new AutoResetEvent(false);
                        //SocketChannel socketc = null;

                        //RealOutboundChannel roc = new RealOutboundChannel(IPAddress.Loopback, 7777, RsaKeySize.rsa2048, testPrivateRsaParameters);
                        //roc.Connected += (sender2, e2) =>
                        //{
                        //    socketc = e2;
                        //    socketc.Sessioned += (sender3, e3) =>
                        //    {
                        //        bool b3 = BitConverter.ToBoolean(e3.ReadBytes(), 0);

                        //        Console.WriteLine("");
                        //    };

                        //    are.Set();

                        //    //e2.Close();

                        //    //Console.WriteLine("connected");
                        //};
                        //roc.RequestConnection();

                        //are.WaitOne();

                        //bool b2 = BitConverter.ToBoolean(socketc.ReadBytes(), 0);

                        //socketc.WriteBytes(BitConverter.GetBytes(true));

                        //socketc.Close();


                        //CirculatedInteger ci = new CirculatedInteger(5);

                        //Console.WriteLine(ci.GetForward(0));
                        //Console.WriteLine(ci.GetForward(1));
                        //Console.WriteLine(ci.GetForward(2));
                        //Console.WriteLine(ci.GetForward(3));
                        //Console.WriteLine(ci.GetForward(4));
                        //Console.WriteLine(ci.GetForward(5));
                        //Console.WriteLine(ci.GetForward(6));

                        //Console.WriteLine(ci.GetBackward(0));
                        //Console.WriteLine(ci.GetBackward(1));
                        //Console.WriteLine(ci.GetBackward(2));
                        //Console.WriteLine(ci.GetBackward(3));
                        //Console.WriteLine(ci.GetBackward(4));
                        //Console.WriteLine(ci.GetBackward(5));
                        //Console.WriteLine(ci.GetBackward(6));

                        Secp256k1KeyPair<Sha256Hash> secp256k1KeyPair = new Secp256k1KeyPair<Sha256Hash>(true);

                        Sha256Ripemd160Hash address = new Sha256Ripemd160Hash(secp256k1KeyPair.pubKey.pubKey);

                        TransactionInput ti1 = new TransactionInput();
                        ti1.LoadVersion1(0, 0, 0);

                        TransactionOutput to1 = new TransactionOutput();
                        to1.LoadVersion0(address, new Creacoin(50m));

                        CoinbaseTransaction ct1 = new CoinbaseTransaction();
                        ct1.LoadVersion0(new TransactionOutput[] { to1 });

                        byte[] ctBytes1 = ct1.ToBinary();

                        CoinbaseTransaction ct2 = SHAREDDATA.FromBinary<CoinbaseTransaction>(ctBytes1);

                        TransferTransaction tt1 = new TransferTransaction();
                        tt1.LoadVersion1(new TransactionInput[] { ti1 }, new TransactionOutput[] { to1 });
                        tt1.Sign(new TransactionOutput[] { to1 }, new DSAPRIVKEYBASE[] { secp256k1KeyPair.privKey });

                        byte[] ttBytes1 = tt1.ToBinary();

                        TransferTransaction tt2 = SHAREDDATA.FromBinary<TransferTransaction>(ttBytes1);

                        ResTransactions rt1 = new ResTransactions(new Transaction[] { ct1, tt1 });

                        byte[] rtBytes1 = rt1.ToBinary();

                        ResTransactions rt2 = SHAREDDATA.FromBinary<ResTransactions>(rtBytes1);


                        byte[] test1 = SHAREDDATA.ToBinary<Transaction>(ct2);

                        CoinbaseTransaction ct3 = SHAREDDATA.FromBinary<Transaction>(test1) as CoinbaseTransaction;

                        byte[] test2 = SHAREDDATA.ToBinary<Transaction>(tt2);

                        TransferTransaction tt3 = SHAREDDATA.FromBinary<Transaction>(test2) as TransferTransaction;

                        //string pathBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                        //New.BlockManagerDB bmdb = new New.BlockManagerDB(pathBase);
                        //New.BlockDB blkdb = new New.BlockDB(pathBase);
                        //New.BlockFilePointersDB bfpdb = new New.BlockFilePointersDB(pathBase);

                        //New.BlockManager bm = new New.BlockManager(bmdb, blkdb, bfpdb);

                        //New.TestBlock block1 = new New.TestBlock(1);

                        //bm.AddMainBlock(block1);
                        //bm.AddMainBlock(block1);


                        //Test10NodesInv();

                        //TestDHT();

                        //bool isFirst = true;
                        //int portNumber = 0;
                        //CreaNode cnlt = null;
                        //tb.KeyDown += (sender2, e2) =>
                        //{
                        //    if (e2.Key != Key.Enter)
                        //        return;

                        //    if (isFirst)
                        //    {
                        //        portNumber = int.Parse(tb.Text);

                        //        FirstNodeInfosDatabase fnidb = new FirstNodeInfosDatabase(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

                        //        cnlt = new CreaNode((ushort)portNumber, 0, "test", fnidb);
                        //        cnlt.Start();

                        //        cnlt.ReceivedNewChat += (sender3, e3) =>
                        //        {
                        //            this.ConsoleWriteLine(e3.Message);
                        //        };

                        //        isFirst = false;

                        //        return;
                        //    }

                        //    Chat chat = new Chat();
                        //    chat.LoadVersion0(portNumber.ToString(), tb.Text);
                        //    chat.Sign(secp256k1KeyPair.privKey);

                        //    cnlt.DiffuseNewChat(chat);
                        //};
                    });
                };

                Closed += (sender, e) =>
                {
                    _logger.LogAdded -= _LoggerLogAdded;

                    string fileText = string.Empty;
                    foreach (var child in sp1.Children)
                        fileText += (child as TextBlock).Text + Environment.NewLine;

                    File.AppendAllText(Path.Combine(new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName, "LogTest.txt"), fileText);
                };
            }
Exemple #39
0
        public void StartSystem()
        {
            if (isSystemStarted)
                throw new InvalidOperationException("core_started");

            ahdb = new AccountHoldersDatabase(databaseBasepath);
            thdb = new TransactionHistoriesDatabase(databaseBasepath);
            bcadb = new BlockchainAccessDB(databaseBasepath);
            bmdb = new BlockManagerDB(databaseBasepath);
            bdb = new BlockDB(databaseBasepath);
            bfpdb = new BlockFilePointersDB(databaseBasepath);
            ufadb = new UtxoFileAccessDB(databaseBasepath);
            ufpdb = new UtxoFilePointersDB(databaseBasepath);
            ufptempdb = new UtxoFilePointersTempDB(databaseBasepath);
            utxodb = new UtxoDB(databaseBasepath);

            accountHolders = new AccountHolders();
            accountHoldersFactory = new AccountHoldersFactory();

            byte[] ahDataBytes = ahdb.GetData();
            if (ahDataBytes.Length != 0)
                accountHolders.FromBinary(ahDataBytes);
            else
                accountHolders.LoadVersion0();

            transactionHistories = thdb.GetData().Pipe((data) => data.Length == 0 ? new TransactionHistories() : SHAREDDATA.FromBinary<TransactionHistories>(data));
            transactionHistories.UnconfirmedTransactionAdded += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        foreach (var prevTxOut in e.senders)
                            if (account.Address.Equals(prevTxOut.Address))
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount + prevTxOut.Amount.rawAmount);
            };
            transactionHistories.UnconfirmedTransactionRemoved += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        foreach (var prevTxOut in e.receivers)
                            if (account.Address.Equals(prevTxOut.Address))
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount - prevTxOut.Amount.rawAmount);
            };

            usableBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.usableAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            unusableBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.unusableAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            unconfirmedBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.unconfirmedAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            usableBalanceWithUnconfirmedCache = new CachedData<CurrencyUnit>(() => new CurrencyUnit(usableBalanceCache.Data.rawAmount - unconfirmedBalanceCache.Data.rawAmount));
            unusableBalanceWithUnconformedCache = new CachedData<CurrencyUnit>(() => new CurrencyUnit(unusableBalanceCache.Data.rawAmount + unconfirmedBalanceCache.Data.rawAmount));

            blockChain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb);
            blockChain.LoadTransactionHistories(transactionHistories);

            //<未改良>暫定?
            if (blockChain.headBlockIndex == -1)
            {
                blockChain.UpdateChain(new GenesisBlock());

                this.RaiseNotification("genesis_block_generated", 5);
            }

            Dictionary<Account, EventHandler<Tuple<CurrencyUnit, CurrencyUnit>>> changeAmountDict = new Dictionary<Account, EventHandler<Tuple<CurrencyUnit, CurrencyUnit>>>();

            Action<bool> _UpdateBalance = (isOnlyUnconfirmed) =>
            {
                if (!isOnlyUnconfirmed)
                {
                    usableBalanceCache.IsModified = true;
                    unusableBalanceCache.IsModified = true;
                }
                unconfirmedBalanceCache.IsModified = true;
                usableBalanceWithUnconfirmedCache.IsModified = true;
                unusableBalanceWithUnconformedCache.IsModified = true;

                BalanceUpdated(this, EventArgs.Empty);
            };

            Action<Account, bool> _AddAddressEvent = (account, isUpdatebalance) =>
            {
                EventHandler<Tuple<CurrencyUnit, CurrencyUnit>> eh = (sender, e) =>
                {
                    account.accountStatus.usableAmount = e.Item1;
                    account.accountStatus.unusableAmount = e.Item2;
                };

                changeAmountDict.Add(account, eh);

                AddressEvent addressEvent = new AddressEvent(account.Address.Hash);
                addressEvent.BalanceUpdated += eh;

                blockChain.AddAddressEvent(addressEvent);

                long rawAmount = 0;
                foreach (var unconfirmedTh in transactionHistories.unconfirmedTransactionHistories.ToArray())
                    foreach (var prevTxOut in unconfirmedTh.senders)
                        if (prevTxOut.Address.Equals(account.Address))
                            rawAmount += prevTxOut.Amount.rawAmount;
                account.accountStatus.unconfirmedAmount = new CurrencyUnit(rawAmount);

                if (isUpdatebalance)
                    _UpdateBalance(false);
            };

            EventHandler<Account> _AccountAdded = (sender, e) =>
            {
                utxodb.Open();

                _AddAddressEvent(e, true);

                utxodb.Close();
            };
            EventHandler<Account> _AccountRemoved = (sender, e) =>
            {
                EventHandler<Tuple<CurrencyUnit, CurrencyUnit>> eh = changeAmountDict[e];

                changeAmountDict.Remove(e);

                AddressEvent addressEvent = blockChain.RemoveAddressEvent(e.Address.Hash);
                addressEvent.BalanceUpdated -= eh;

                _UpdateBalance(false);
            };

            utxodb.Open();

            foreach (var accountHolder in accountHolders.AllAccountHolders)
            {
                foreach (var account in accountHolder.Accounts)
                    _AddAddressEvent(account, false);

                accountHolder.AccountAdded += _AccountAdded;
                accountHolder.AccountRemoved += _AccountRemoved;
            }

            utxodb.Close();

            accountHolders.AccountHolderAdded += (sender, e) =>
            {
                e.AccountAdded += _AccountAdded;
                e.AccountRemoved += _AccountRemoved;
            };
            accountHolders.AccountHolderRemoved += (semder, e) =>
            {
                e.AccountAdded -= _AccountAdded;
                e.AccountRemoved -= _AccountRemoved;
            };

            blockChain.BalanceUpdated += (sender, e) => _UpdateBalance(false);

            _UpdateBalance(false);

            unconfirmedTtxs = new Dictionary<TransferTransaction, TransactionOutput[]>();
            mining = new Mining();
            mining.FoundNonce += (sender, e) => creaNodeTest.DiffuseNewBlock(e);

            blockChain.Updated += (sender, e) =>
            {
                foreach (var block in e)
                    foreach (var tx in block.Transactions)
                        foreach (var txIn in tx.TxInputs)
                        {
                            TransferTransaction contradiction = null;

                            foreach (var unconfirmedTx in unconfirmedTtxs)
                            {
                                foreach (var unconfirmedTxIn in unconfirmedTx.Key.TxInputs)
                                    if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                                    {
                                        contradiction = unconfirmedTx.Key;

                                        break;
                                    }

                                if (contradiction != null)
                                    break;
                            }

                            if (contradiction != null)
                                unconfirmedTtxs.Remove(contradiction);
                        }

                Mine();
            };

            Mine();

            //creaNodeTest = new CreaNode(ps.NodePort, creaVersion, appnameWithVersion, new FirstNodeInfosDatabase(p2pDirectory));
            creaNodeTest = new CreaNodeTest(blockChain, ps.NodePort, creaVersion, appnameWithVersion);
            creaNodeTest.ConnectionKeeped += (sender, e) => creaNodeTest.SyncronizeBlockchain();
            creaNodeTest.ReceivedNewTransaction += (sender, e) =>
            {
                TransferTransaction ttx = e as TransferTransaction;

                if (ttx == null)
                    return;

                TransactionOutput[] prevTxOuts = new TransactionOutput[ttx.TxInputs.Length];
                for (int i = 0; i < prevTxOuts.Length; i++)
                    prevTxOuts[i] = blockChain.GetMainBlock(ttx.TxInputs[i].PrevTxBlockIndex).Transactions[ttx.TxInputs[i].PrevTxIndex].TxOutputs[ttx.TxInputs[i].PrevTxOutputIndex];

                if (!ttx.Verify(prevTxOuts))
                    return;

                List<TransactionOutput> senders = new List<TransactionOutput>();
                List<TransactionOutput> receivers = new List<TransactionOutput>();

                long sentAmount = 0;
                long receivedAmount = 0;

                for (int i = 0; i < ttx.txInputs.Length; i++)
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                        foreach (var account in accountHolder.Accounts)
                            if (prevTxOuts[i].Address.Equals(account.Address.Hash))
                            {
                                sentAmount += prevTxOuts[i].Amount.rawAmount;

                                senders.Add(prevTxOuts[i]);
                            }

                for (int i = 0; i < ttx.TxOutputs.Length; i++)
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                        foreach (var account in accountHolder.Accounts)
                            if (ttx.TxOutputs[i].Address.Equals(account.Address.Hash))
                            {
                                receivedAmount += ttx.TxOutputs[i].Amount.rawAmount;

                                receivers.Add(ttx.TxOutputs[i]);
                            }

                if (senders.Count > 0 || receivers.Count > 0)
                {
                    TransactionHistoryType type = TransactionHistoryType.transfered;
                    if (receivers.Count < ttx.TxOutputs.Length)
                        type = TransactionHistoryType.sent;
                    else if (senders.Count < ttx.TxInputs.Length)
                        type = TransactionHistoryType.received;

                    transactionHistories.AddTransactionHistory(new TransactionHistory(true, false, type, DateTime.MinValue, 0, ttx.Id, senders.ToArray(), receivers.ToArray(), ttx, prevTxOuts, new CurrencyUnit(sentAmount), new CurrencyUnit(receivedAmount - sentAmount)));
                }

                utxodb.Open();

                for (int i = 0; i < ttx.TxInputs.Length; i++)
                    if (blockChain.FindUtxo(prevTxOuts[i].Address, ttx.TxInputs[i].PrevTxBlockIndex, ttx.TxInputs[i].PrevTxIndex, ttx.TxInputs[i].PrevTxOutputIndex) == null)
                        return;

                utxodb.Close();

                foreach (var txIn in ttx.TxInputs)
                    foreach (var unconfirmedTtx in unconfirmedTtxs)
                        foreach (var unconfirmedTxIn in unconfirmedTtx.Key.TxInputs)
                            if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                                return;

                unconfirmedTtxs.Add(ttx, prevTxOuts);

                Mine();
            };
            creaNodeTest.ReceivedNewBlock += (sender, e) => blockChain.UpdateChain(e).Pipe((ret) => this.RaiseResult("blockchain_update", 5, ret.ToString()));
            //creaNodeTest.Start();

            isSystemStarted = true;
        }
Exemple #40
0
        public void NewTransaction(IAccount iAccount, Sha256Ripemd160Hash address, CurrencyUnit amount, CurrencyUnit fee)
        {
            if (!isSystemStarted)
                throw new InvalidOperationException("core_not_started");

            Account account = iAccount as Account;
            if (account == null)
                throw new ArgumentException("iaccount_type");

            utxodb.Open();

            List<Utxo> utxosList = blockChain.GetAllUtxos(account.Address.Hash);
            utxosList.Sort((a, b) =>
            {
                if (a.blockIndex < b.blockIndex)
                    return -1;
                else if (a.blockIndex > b.blockIndex)
                    return 1;

                if (a.txIndex < b.txIndex)
                    return -1;
                else if (a.txIndex > b.txIndex)
                    return 1;

                if (a.txOutIndex < b.txOutIndex)
                    return -1;
                else if (a.txOutIndex > b.txOutIndex)
                    return 1;

                return 0;
            });
            Utxo[] utxos = utxosList.ToArray();

            utxodb.Close();

            List<TransactionInput> usedTxInList = new List<TransactionInput>();
            foreach (var unconfirmedTh in transactionHistories.unconfirmedTransactionHistories.ToArray())
                for (int i = 0; i < unconfirmedTh.prevTxOuts.Length; i++)
                    if (unconfirmedTh.prevTxOuts[i].Address.Equals(account.Address.Hash))
                        usedTxInList.Add(unconfirmedTh.transaction.TxInputs[i]);
            usedTxInList.Sort((a, b) =>
            {
                if (a.PrevTxBlockIndex < b.PrevTxBlockIndex)
                    return -1;
                else if (a.PrevTxBlockIndex > b.PrevTxBlockIndex)
                    return 1;

                if (a.PrevTxIndex < b.PrevTxIndex)
                    return -1;
                else if (a.PrevTxIndex > b.PrevTxIndex)
                    return 1;

                if (a.PrevTxOutputIndex < b.PrevTxOutputIndex)
                    return -1;
                else if (a.PrevTxOutputIndex > b.PrevTxOutputIndex)
                    return 1;

                return 0;
            });
            TransactionInput[] usedTxIns = usedTxInList.ToArray();

            List<Utxo> unusedUtxosList = new List<Utxo>();

            int position = -1;
            for (int i = 0; i < usedTxIns.Length; i++)
            {
                bool flag = false;
                while (position < utxos.Length)
                {
                    position++;

                    if (usedTxIns[i].PrevTxBlockIndex == utxos[position].blockIndex && usedTxIns[i].PrevTxIndex == utxos[position].txIndex && usedTxIns[i].PrevTxOutputIndex == utxos[position].txOutIndex)
                    {
                        flag = true;

                        break;
                    }
                    else
                        unusedUtxosList.Add(utxos[position]);
                }

                if (!flag)
                    throw new InvalidOperationException();
            }

            long rawFeeAndAmount = amount.rawAmount + fee.rawAmount;

            List<Utxo> useUtxosList = new List<Utxo>();
            long rawFeeAndAmountAndChange = 0;

            bool flag2 = false;
            foreach (var utxo in unusedUtxosList)
            {
                useUtxosList.Add(utxo);

                if ((rawFeeAndAmountAndChange += utxo.amount.rawAmount) > rawFeeAndAmount)
                {
                    flag2 = true;

                    break;
                }
            }

            if (!flag2)
                for (int i = position + 1; i < utxos.Length; i++)
                {
                    useUtxosList.Add(utxos[i]);

                    if ((rawFeeAndAmountAndChange += utxos[i].amount.rawAmount) > rawFeeAndAmount)
                    {
                        flag2 = true;

                        break;
                    }
                }

            if (!flag2)
                throw new InvalidOperationException();

            Utxo[] useUtxos = useUtxosList.ToArray();

            TransactionInput[] txIns = new TransactionInput[useUtxos.Length];
            for (int i = 0; i < txIns.Length; i++)
            {
                txIns[i] = new TransactionInput();
                txIns[i].LoadVersion0(useUtxos[i].blockIndex, useUtxos[i].txIndex, useUtxos[i].txOutIndex, account.Ecdsa256KeyPair.pubKey);
            }

            long rawChange = rawFeeAndAmountAndChange - rawFeeAndAmount;

            TransactionOutput[] txOuts = new TransactionOutput[rawChange == 0 ? 1 : 2];
            txOuts[0] = new TransactionOutput();
            txOuts[0].LoadVersion0(address, amount);
            if (rawChange != 0)
            {
                txOuts[1] = new TransactionOutput();
                txOuts[1].LoadVersion0(account.Address.Hash, new CurrencyUnit(rawChange));
            }

            TransactionOutput[] prevTxOuts = new TransactionOutput[useUtxos.Length];
            for (int i = 0; i < prevTxOuts.Length; i++)
                prevTxOuts[i] = blockChain.GetMainBlock(txIns[i].PrevTxBlockIndex).Transactions[txIns[i].PrevTxIndex].TxOutputs[txIns[i].PrevTxOutputIndex];

            Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[useUtxos.Length];
            for (int i = 0; i < privKeys.Length; i++)
                privKeys[i] = account.Ecdsa256KeyPair.privKey;

            TransferTransaction ttx = new TransferTransaction();
            ttx.LoadVersion0(txIns, txOuts);
            ttx.Sign(prevTxOuts, privKeys);

            creaNodeTest.DiffuseNewTransaction(ttx);
        }
Exemple #41
0
        public BlockContext CreateNextValidBlock()
        {
            currentBIndex++;

            if (currentBIndex == 0)
            {
                Block blk = new GenesisBlock();

                blks.Add(blk);

                Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();
                Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();

                for (int i = 0; i < keyPairs.Length; i++)
                {
                    unspentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>());
                    foreach (var toc in unspentTxOutsDict[addresses[i]])
                        unspentTxOutsDictClone2[addresses[i]].Add(toc);
                    spentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>());
                    foreach (var toc in spentTxOutsDict[addresses[i]])
                        spentTxOutsDictClone2[addresses[i]].Add(toc);
                }

                return new BlockContext(blk, new TransactionOutput[][] { }, 0, unspentTxOutsDictClone2, spentTxOutsDictClone2);
            }

            int numOfSpendTxs = maxNumOfSpendTxs.RandomNum() + 1;
            int[] numOfSpendTxOutss = new int[numOfSpendTxs];
            for (int i = 0; i < numOfSpendTxOutss.Length; i++)
                numOfSpendTxOutss[i] = maxNumOfSpendTxOuts.RandomNum() + 1;

            TransactionOutputContext[][] spendTxOutss = new TransactionOutputContext[numOfSpendTxs][];
            for (int i = 0; i < spendTxOutss.Length; i++)
            {
                if (unspentTxOuts.Count == 0)
                    break;

                spendTxOutss[i] = new TransactionOutputContext[numOfSpendTxOutss[i]];

                for (int j = 0; j < spendTxOutss[i].Length; j++)
                {
                    int index = unspentTxOuts.Count.RandomNum();

                    spendTxOutss[i][j] = unspentTxOuts[index];

                    spentTxOutsDict[unspentTxOuts[index].address].Add(unspentTxOuts[index]);
                    unspentTxOutsDict[unspentTxOuts[index].address].Remove(unspentTxOuts[index]);

                    spentTxOuts.Add(unspentTxOuts[index]);
                    unspentTxOuts.RemoveAt(index);

                    if (unspentTxOuts.Count == 0)
                        break;
                }
            }

            long fee = 0;
            List<TransferTransaction> transferTxs = new List<TransferTransaction>();
            List<TransactionOutput[]> prevTxOutsList = new List<TransactionOutput[]>();
            for (int i = 0; i < spendTxOutss.Length; i++)
            {
                if (spendTxOutss[i] == null)
                    break;

                long sumRawAmount = 0;

                List<TransactionInput> txInputsList = new List<TransactionInput>();
                for (int j = 0; j < spendTxOutss[i].Length; j++)
                {
                    if (spendTxOutss[i][j] == null)
                        break;

                    txInputsList.Add(spendTxOutss[i][j].GenerateTransactionInput());

                    sumRawAmount += spendTxOutss[i][j].amount.rawAmount;
                }

                TransactionInput[] txIns = txInputsList.ToArray();

                int num = sumRawAmount > 1000000 ? (int)Math.Ceiling(((avgIORatio - 1) * 2) * 1.RandomDouble() * txIns.Length) : 1;

                TransactionOutputContext[] txOutsCon = new TransactionOutputContext[num];
                TransactionOutput[] txOuts = new TransactionOutput[num];
                for (int j = 0; j < txOutsCon.Length; j++)
                {
                    long outAmount = 0;
                    if (sumRawAmount > 1000000)
                    {
                        long sumRawAmountDivided = sumRawAmount / 1000000;

                        int subtract = ((int)sumRawAmountDivided / 2).RandomNum() + 1;

                        outAmount = (long)subtract * 1000000;
                    }
                    else
                        outAmount = sumRawAmount;

                    sumRawAmount -= outAmount;

                    int index = numOfKeyPairs.RandomNum();

                    txOutsCon[j] = new TransactionOutputContext(currentBIndex, i + 1, j, new CurrencyUnit(outAmount), addresses[index], keyPairs[index]);
                    txOuts[j] = txOutsCon[j].GenerateTrasactionOutput();
                }

                fee += sumRawAmount;

                for (int j = 0; j < txOutsCon.Length; j++)
                {
                    unspentTxOutsDict[txOutsCon[j].address].Add(txOutsCon[j]);

                    unspentTxOuts.Add(txOutsCon[j]);
                }

                TransactionOutput[] prevTxOuts = new TransactionOutput[txIns.Length];
                Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[txIns.Length];
                for (int j = 0; j < prevTxOuts.Length; j++)
                {
                    prevTxOuts[j] = spendTxOutss[i][j].GenerateTrasactionOutput();
                    privKeys[j] = spendTxOutss[i][j].keyPair.privKey;
                }

                TransferTransaction tTx = new TransferTransaction();
                tTx.LoadVersion0(txIns, txOuts);
                tTx.Sign(prevTxOuts, privKeys);

                transferTxs.Add(tTx);
                prevTxOutsList.Add(prevTxOuts);
            }

            long rewardAndFee = TransactionalBlock.GetRewardToMiner(currentBIndex, 0).rawAmount + fee;

            TransactionOutputContext[] coinbaseTxOutsCon = new TransactionOutputContext[numOfCoinbaseTxOuts];
            TransactionOutput[] coinbaseTxOuts = new TransactionOutput[numOfCoinbaseTxOuts];
            for (int i = 0; i < coinbaseTxOutsCon.Length; i++)
            {
                long outAmount2 = 0;
                if (i != coinbaseTxOutsCon.Length - 1)
                {
                    long rewardAndFeeDevided = rewardAndFee / 1000000;

                    int subtract2 = ((int)rewardAndFeeDevided / 2).RandomNum() + 1;

                    outAmount2 = (long)subtract2 * 1000000;

                    rewardAndFee -= outAmount2;
                }
                else
                    outAmount2 = rewardAndFee;

                int index = numOfKeyPairs.RandomNum();

                coinbaseTxOutsCon[i] = new TransactionOutputContext(currentBIndex, 0, i, new CurrencyUnit(outAmount2), addresses[index], keyPairs[index]);
                coinbaseTxOuts[i] = coinbaseTxOutsCon[i].GenerateTrasactionOutput();
            }

            CoinbaseTransaction coinbaseTx = new CoinbaseTransaction();
            coinbaseTx.LoadVersion0(coinbaseTxOuts);

            for (int i = 0; i < coinbaseTxOutsCon.Length; i++)
            {
                unspentTxOutsDict[coinbaseTxOutsCon[i].address].Add(coinbaseTxOutsCon[i]);

                unspentTxOuts.Add(coinbaseTxOutsCon[i]);
            }

            prevTxOutsList.Insert(0, new TransactionOutput[] { });

            Difficulty<Creahash> diff = new Difficulty<Creahash>(HASHBASE.FromHash<Creahash>(new byte[] { 0, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }));
            byte[] nonce = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            BlockHeader bh = new BlockHeader();
            bh.LoadVersion0(currentBIndex, blks[blks.Count - 1].Id, DateTime.Now, diff, nonce);

            NormalBlock nblk = new NormalBlock();
            nblk.LoadVersion0(bh, coinbaseTx, transferTxs.ToArray());
            nblk.UpdateMerkleRootHash();

            blks.Add(nblk);

            Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();
            Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();

            for (int i = 0; i < keyPairs.Length; i++)
            {
                unspentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>());
                foreach (var toc in unspentTxOutsDict[addresses[i]])
                    unspentTxOutsDictClone[addresses[i]].Add(toc);
                spentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>());
                foreach (var toc in spentTxOutsDict[addresses[i]])
                    spentTxOutsDictClone[addresses[i]].Add(toc);
            }

            BlockContext blkCon = new BlockContext(nblk, prevTxOutsList.ToArray(), fee, unspentTxOutsDictClone, spentTxOutsDictClone);

            return blkCon;
        }
Exemple #42
0
        //TransactionOutput、TransactionInput、CoinbaseTransaction、TransferTransactionのテスト
        public static void Test10()
        {
            Ecdsa256KeyPair keypair1 = new Ecdsa256KeyPair(true);
            Ecdsa256KeyPair keypair2 = new Ecdsa256KeyPair(true);
            Ecdsa256KeyPair keypair3 = new Ecdsa256KeyPair(true);

            Sha256Ripemd160Hash address1 = new Sha256Ripemd160Hash(keypair1.pubKey.pubKey);
            CurrencyUnit amount1 = new Creacoin(50.0m);
            Sha256Ripemd160Hash address2 = new Sha256Ripemd160Hash(keypair2.pubKey.pubKey);
            CurrencyUnit amount2 = new Creacoin(25.0m);
            Sha256Ripemd160Hash address3 = new Sha256Ripemd160Hash(keypair3.pubKey.pubKey);
            CurrencyUnit amount3 = new Yumina(0.01m);

            TransactionOutput txOut1 = new TransactionOutput();
            txOut1.LoadVersion0(address1, amount1);
            TransactionOutput txOut2 = new TransactionOutput();
            txOut2.LoadVersion0(address2, amount2);
            TransactionOutput txOut3 = new TransactionOutput();
            txOut3.LoadVersion0(address3, amount3);

            if (txOut1.Address != address1)
                throw new Exception("test10_1");
            if (txOut1.Amount != amount1)
                throw new Exception("test10_2");

            byte[] txOutBytes = txOut1.ToBinary();

            if (txOutBytes.Length != 29)
                throw new Exception("test10_3");

            TransactionOutput txOutRestore = SHAREDDATA.FromBinary<TransactionOutput>(txOutBytes, 0);

            if (!txOut1.Address.Equals(txOutRestore.Address))
                throw new Exception("test10_4");
            if (txOut1.Amount.rawAmount != txOutRestore.Amount.rawAmount)
                throw new Exception("test10_5");

            TransactionInput txIn1 = new TransactionInput();
            txIn1.LoadVersion0(0, 0, 0, keypair1.pubKey);
            TransactionInput txIn2 = new TransactionInput();
            txIn2.LoadVersion0(1, 0, 0, keypair2.pubKey);
            TransactionInput txIn3 = new TransactionInput();
            txIn3.LoadVersion0(2, 0, 0, keypair3.pubKey);

            if (txIn1.PrevTxBlockIndex != 0)
                throw new Exception("test10_6");
            if (txIn1.PrevTxIndex != 0)
                throw new Exception("test10_7");
            if (txIn1.PrevTxOutputIndex != 0)
                throw new Exception("test10_8");
            if (txIn1.SenderPubKey != keypair1.pubKey)
                throw new Exception("test10_9");

            TransactionOutput[] txOuts = new TransactionOutput[] { txOut1, txOut2, txOut3 };

            CoinbaseTransaction cTx = new CoinbaseTransaction();
            cTx.LoadVersion0(txOuts);

            if (cTx.TxOutputs != txOuts)
                throw new Exception("test10_10");
            if (cTx.TxInputs.Length != 0)
                throw new Exception("test10_11");

            byte[] cTxBytes = cTx.ToBinary();

            if (cTxBytes.Length != 97)
                throw new Exception("test10_12");

            CoinbaseTransaction cTxRestore = SHAREDDATA.FromBinary<CoinbaseTransaction>(cTxBytes);

            if (!cTx.Id.Equals(cTxRestore.Id))
                throw new Exception("test10_13");

            if (cTx.Verify())
                throw new Exception("test10_14");
            if (cTx.VerifyNotExistDustTxOutput())
                throw new Exception("test10_15");
            if (!cTx.VerifyNumberOfTxInputs())
                throw new Exception("test10_16");
            if (!cTx.VerifyNumberOfTxOutputs())
                throw new Exception("test10_17");

            TransactionOutput[] txOuts2 = new TransactionOutput[11];
            for (int i = 0; i < txOuts2.Length; i++)
                txOuts2[i] = txOut1;

            CoinbaseTransaction cTx2 = new CoinbaseTransaction();
            cTx2.LoadVersion0(txOuts2);

            if (cTx2.Verify())
                throw new Exception("test10_18");
            if (!cTx2.VerifyNotExistDustTxOutput())
                throw new Exception("test10_19");
            if (!cTx2.VerifyNumberOfTxInputs())
                throw new Exception("test10_20");
            if (cTx2.VerifyNumberOfTxOutputs())
                throw new Exception("test10_21");

            TransactionOutput[] txOuts3 = new TransactionOutput[] { txOut1, txOut2 };

            CoinbaseTransaction cTx3 = new CoinbaseTransaction();
            cTx3.LoadVersion0(txOuts3);

            if (!cTx3.Verify())
                throw new Exception("test10_22");
            if (!cTx3.VerifyNotExistDustTxOutput())
                throw new Exception("test10_23");
            if (!cTx3.VerifyNumberOfTxInputs())
                throw new Exception("test10_24");
            if (!cTx3.VerifyNumberOfTxOutputs())
                throw new Exception("test10_25");

            TransactionInput[] txIns = new TransactionInput[] { txIn1, txIn2, txIn3 };

            TransferTransaction tTx1 = new TransferTransaction();
            tTx1.LoadVersion0(txIns, txOuts);
            tTx1.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey });

            if (tTx1.TxInputs != txIns)
                throw new Exception("test10_26");
            if (tTx1.TxOutputs != txOuts)
                throw new Exception("test10_27");

            byte[] txInBytes = txIn1.ToBinary();

            if (txInBytes.Length != 153)
                throw new Exception("test10_28");

            TransactionInput txInRestore = SHAREDDATA.FromBinary<TransactionInput>(txInBytes, 0);

            if (txIn1.PrevTxBlockIndex != txInRestore.PrevTxBlockIndex)
                throw new Exception("test10_29");
            if (txIn1.PrevTxIndex != txInRestore.PrevTxIndex)
                throw new Exception("test10_30");
            if (txIn1.PrevTxOutputIndex != txInRestore.PrevTxOutputIndex)
                throw new Exception("test10_31");
            if (!txIn1.SenderPubKey.pubKey.BytesEquals(txInRestore.SenderPubKey.pubKey))
                throw new Exception("test10_32");
            if (!txIn1.SenderSignature.signature.BytesEquals(txInRestore.SenderSignature.signature))
                throw new Exception("test10_33");

            byte[] tTxBytes = tTx1.ToBinary();

            if (tTxBytes.Length != 557)
                throw new Exception("test10_34");

            TransferTransaction tTxRestore = SHAREDDATA.FromBinary<TransferTransaction>(tTxBytes);

            if (!tTx1.Id.Equals(tTxRestore.Id))
                throw new Exception("test10_35");

            if (tTx1.Verify(txOuts))
                throw new Exception("test10_36");
            if (tTx1.VerifyNotExistDustTxOutput())
                throw new Exception("test10_37");
            if (!tTx1.VerifyNumberOfTxInputs())
                throw new Exception("test10_38");
            if (!tTx1.VerifyNumberOfTxOutputs())
                throw new Exception("test10_39");
            if (!tTx1.VerifySignature(txOuts))
                throw new Exception("test10_40");
            if (!tTx1.VerifyPubKey(txOuts))
                throw new Exception("test10_41");
            if (!tTx1.VerifyAmount(txOuts))
                throw new Exception("test10_42");
            if (tTx1.GetFee(txOuts).rawAmount != 0)
                throw new Exception("test10_43");

            TransactionOutput[] txOuts4 = new TransactionOutput[] { txOut2, txOut1, txOut3 };

            if (tTx1.Verify(txOuts4))
                throw new Exception("test10_44");
            if (tTx1.VerifySignature(txOuts4))
                throw new Exception("test10_45");
            if (tTx1.VerifyPubKey(txOuts4))
                throw new Exception("test10_46");

            byte temp2 = tTx1.TxInputs[0].SenderSignature.signature[0];

            tTx1.TxInputs[0].SenderSignature.signature[0] = 0;

            if (tTx1.Verify(txOuts))
                throw new Exception("test10_47");
            if (tTx1.VerifySignature(txOuts))
                throw new Exception("test10_48");
            if (!tTx1.VerifyPubKey(txOuts))
                throw new Exception("test10_49");

            tTx1.TxInputs[0].SenderSignature.signature[0] = temp2;

            TransferTransaction tTx2 = new TransferTransaction();
            tTx2.LoadVersion0(txIns, txOuts);
            tTx2.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair2.privKey, keypair1.privKey, keypair3.privKey });

            if (tTx2.Verify(txOuts))
                throw new Exception("test10_50");
            if (tTx2.VerifySignature(txOuts))
                throw new Exception("test10_51");
            if (!tTx2.VerifyPubKey(txOuts))
                throw new Exception("test10_52");

            TransferTransaction tTx3 = new TransferTransaction();
            tTx3.LoadVersion0(txIns, txOuts);
            tTx3.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey });

            byte temp = tTx3.TxInputs[0].SenderPubKey.pubKey[0];

            tTx3.TxInputs[0].SenderPubKey.pubKey[0] = 0;

            if (tTx3.Verify(txOuts))
                throw new Exception("test10_50");
            if (tTx3.VerifySignature(txOuts))
                throw new Exception("test10_51");
            if (tTx3.VerifyPubKey(txOuts))
                throw new Exception("test10_52");

            tTx3.TxInputs[0].SenderPubKey.pubKey[0] = temp;

            TransferTransaction tTx4 = new TransferTransaction();
            tTx4.LoadVersion0(txIns, txOuts2);
            tTx4.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey });

            if (tTx4.Verify(txOuts))
                throw new Exception("test10_53");
            if (!tTx4.VerifyNotExistDustTxOutput())
                throw new Exception("test10_54");
            if (!tTx4.VerifyNumberOfTxInputs())
                throw new Exception("test10_55");
            if (tTx4.VerifyNumberOfTxOutputs())
                throw new Exception("test10_56");
            if (!tTx4.VerifySignature(txOuts))
                throw new Exception("test10_57");
            if (!tTx4.VerifyPubKey(txOuts))
                throw new Exception("test10_58");
            if (tTx4.VerifyAmount(txOuts))
                throw new Exception("test10_59");
            if (tTx4.GetFee(txOuts).rawAmount != -47499990000)
                throw new Exception("test10_60");

            TransferTransaction tTx5 = new TransferTransaction();
            tTx5.LoadVersion0(txIns, txOuts3);
            tTx5.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey });

            if (!tTx5.Verify(txOuts))
                throw new Exception("test10_61");
            if (!tTx5.VerifyNotExistDustTxOutput())
                throw new Exception("test10_62");
            if (!tTx5.VerifyNumberOfTxInputs())
                throw new Exception("test10_63");
            if (!tTx5.VerifyNumberOfTxOutputs())
                throw new Exception("test10_64");
            if (!tTx5.VerifySignature(txOuts))
                throw new Exception("test10_65");
            if (!tTx5.VerifyPubKey(txOuts))
                throw new Exception("test10_66");
            if (!tTx5.VerifyAmount(txOuts))
                throw new Exception("test10_67");
            if (tTx5.GetFee(txOuts).rawAmount != 10000)
                throw new Exception("test10_68");

            TransactionInput[] txIns2 = new TransactionInput[101];
            for (int i = 0; i < txIns2.Length; i++)
                txIns2[i] = txIn1;

            TransactionOutput[] txOuts5 = new TransactionOutput[txIns2.Length];
            for (int i = 0; i < txOuts5.Length; i++)
                txOuts5[i] = txOut1;

            Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[txIns2.Length];
            for (int i = 0; i < privKeys.Length; i++)
                privKeys[i] = keypair1.privKey;

            TransferTransaction tTx6 = new TransferTransaction();
            tTx6.LoadVersion0(txIns2, txOuts3);
            tTx6.Sign(txOuts5, privKeys);

            if (tTx6.Verify(txOuts5))
                throw new Exception("test10_61");
            if (!tTx6.VerifyNotExistDustTxOutput())
                throw new Exception("test10_62");
            if (tTx6.VerifyNumberOfTxInputs())
                throw new Exception("test10_63");
            if (!tTx6.VerifyNumberOfTxOutputs())
                throw new Exception("test10_64");
            if (!tTx6.VerifySignature(txOuts5))
                throw new Exception("test10_65");
            if (!tTx6.VerifyPubKey(txOuts5))
                throw new Exception("test10_66");
            if (!tTx6.VerifyAmount(txOuts5))
                throw new Exception("test10_67");
            if (tTx6.GetFee(txOuts5).rawAmount != 497500000000)
                throw new Exception("test10_68");

            byte[] cTxBytes2 = SHAREDDATA.ToBinary<Transaction>(cTx);

            if (cTxBytes2.Length != 117)
                throw new Exception("test10_69");

            CoinbaseTransaction cTxRestore2 = SHAREDDATA.FromBinary<Transaction>(cTxBytes2) as CoinbaseTransaction;

            if (!cTx.Id.Equals(cTxRestore2.Id))
                throw new Exception("test10_70");

            byte[] tTxBytes2 = SHAREDDATA.ToBinary<Transaction>(tTx6);

            if (tTxBytes2.Length != 15445)
                throw new Exception("test10_71");

            TransferTransaction tTxRestore2 = SHAREDDATA.FromBinary<Transaction>(tTxBytes2) as TransferTransaction;

            if (!tTx6.Id.Equals(tTxRestore2.Id))
                throw new Exception("test10_72");

            Sha256Sha256Hash ctxid = new Sha256Sha256Hash(cTxBytes);

            if (!ctxid.Equals(cTx.Id))
                throw new Exception("test10_73");

            Sha256Sha256Hash ttxid = new Sha256Sha256Hash(tTx6.ToBinary());

            if (!ttxid.Equals(tTx6.Id))
                throw new Exception("test10_74");

            Console.WriteLine("test10_succeeded");
        }
Exemple #43
0
        //Blockのテスト2
        public static void Test12()
        {
            BlockGenerator bg = new BlockGenerator();

            Block[] blks = new Block[10];
            BlockContext[] blkCons = new BlockContext[blks.Length];
            for (int i = 0; i < blks.Length; i++)
            {
                blkCons[i] = bg.CreateNextValidBlock();
                blks[i] = blkCons[i].block;

                if (i > 0)
                {
                    NormalBlock nblk = blks[i] as NormalBlock;

                    byte[] nblkBytes = nblk.ToBinary();

                    NormalBlock nblkRestore = SHAREDDATA.FromBinary<NormalBlock>(nblkBytes);

                    if (!nblk.Id.Equals(nblkRestore.Id))
                        throw new Exception("test12_1");

                    byte[] nblkBytes2 = SHAREDDATA.ToBinary<Block>(blks[i]);

                    NormalBlock nblkRestore2 = SHAREDDATA.FromBinary<Block>(nblkBytes2) as NormalBlock;

                    if (!nblk.Id.Equals(nblkRestore2.Id))
                        throw new Exception("test12_2");
                }
            }

            GenesisBlock gblk = blks[0] as GenesisBlock;

            Creahash gblkid = new Creahash(gblk.ToBinary());

            if (!gblk.Id.Equals(gblkid))
                throw new Exception("test12_3");

            NormalBlock nblk2 = blks[1] as NormalBlock;

            Creahash nblkid = new Creahash(nblk2.header.ToBinary());

            if (!nblk2.Id.Equals(nblkid))
                throw new Exception("test12_4");

            nblk2.UpdateTimestamp(DateTime.Now);

            Creahash nblkid2 = new Creahash(nblk2.header.ToBinary());

            if (!nblk2.Id.Equals(nblkid2))
                throw new Exception("test12_5");

            nblk2.UpdateNonce(new byte[10]);

            Creahash nblkid3 = new Creahash(nblk2.header.ToBinary());

            if (!nblk2.Id.Equals(nblkid3))
                throw new Exception("test12_6");

            nblk2.UpdateMerkleRootHash();

            Creahash nblkid4 = new Creahash(nblk2.header.ToBinary());

            if (!nblk2.Id.Equals(nblkid4))
                throw new Exception("test12_7");

            if (!nblk2.VerifyBlockType())
                throw new Exception("test12_8");

            FoundationalBlock fblk = new FoundationalBlock();
            fblk.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, nblk2.coinbaseTxToMiner, nblk2.transferTxs);

            byte[] fblkBytes = fblk.ToBinary();

            FoundationalBlock fblkRestore = SHAREDDATA.FromBinary<FoundationalBlock>(fblkBytes);

            if (!fblk.Id.Equals(fblkRestore.Id))
                throw new Exception("test12_9");

            byte[] fblkBytes2 = SHAREDDATA.ToBinary<Block>(fblk);

            FoundationalBlock fblkRestore2 = SHAREDDATA.FromBinary<Block>(fblkBytes2) as FoundationalBlock;

            if (!fblk.Id.Equals(fblkRestore2.Id))
                throw new Exception("test12_10");

            if (fblk.VerifyBlockType())
                throw new Exception("test12_11");

            if (!nblk2.VerifyMerkleRootHash())
                throw new Exception("test12_12");

            byte[] nblkBytes3 = nblk2.ToBinary();

            NormalBlock nblk3 = SHAREDDATA.FromBinary<NormalBlock>(nblkBytes3);

            nblk3.header.merkleRootHash.hash[0] ^= 255;

            if (nblk3.VerifyMerkleRootHash())
                throw new Exception("test12_13");

            byte[] nonce = new byte[10];
            while (true)
            {
                nblk2.UpdateNonce(nonce);

                if (nblk2.Id.hash[0] == 0 && nblk2.Id.hash[1] <= 127)
                {
                    if (!nblk2.VerifyId())
                        throw new Exception("test12_14");

                    break;
                }

                if (nblk2.VerifyId())
                    throw new Exception("test12_15");

                int index = nonce.Length.RandomNum();
                int value = 256.RandomNum();

                nonce[index] = (byte)value;
            }

            TransferTransaction[] transferTxs1 = new TransferTransaction[99];
            for (int i = 0; i < transferTxs1.Length; i++)
                transferTxs1[i] = (blks[2] as TransactionalBlock).transferTxs[0];

            TransferTransaction[] transferTxs2 = new TransferTransaction[100];
            for (int i = 0; i < transferTxs2.Length; i++)
                transferTxs2[i] = (blks[2] as TransactionalBlock).transferTxs[0];

            NormalBlock nblk4 = new NormalBlock();
            nblk4.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, transferTxs1);

            NormalBlock nblk5 = new NormalBlock();
            nblk5.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, transferTxs2);

            if (!nblk4.VerifyNumberOfTxs())
                throw new Exception("test12_16");

            if (nblk5.VerifyNumberOfTxs())
                throw new Exception("test12_17");

            for (int i = 1; i < blks.Length; i++)
            {
                TransactionalBlock tblk = blks[i] as TransactionalBlock;

                CurrencyUnit amount = tblk.GetActualRewardToMinerAndTxFee();
                CurrencyUnit amount2 = tblk.GetValidRewardToMinerAndTxFee(blkCons[i].prevTxOutss);
                CurrencyUnit amount3 = tblk.GetValidTxFee(blkCons[i].prevTxOutss);

                if (amount.rawAmount != (long)5400000000 + blkCons[i].feeRawAmount)
                    throw new Exception("test12_18");
                if (amount2.rawAmount != amount.rawAmount)
                    throw new Exception("test12_19");
                if (amount3.rawAmount != blkCons[i].feeRawAmount)
                    throw new Exception("test12_20");

                if (!tblk.VerifyRewardAndTxFee(blkCons[i].prevTxOutss))
                    throw new Exception("test12_21");
                if (!tblk.VerifyTransferTransaction(blkCons[i].prevTxOutss))
                    throw new Exception("test12_22");

                bool flag = false;
                TransactionOutput[][] invalidPrevTxOutss = new TransactionOutput[blkCons[i].prevTxOutss.Length][];
                for (int j = 0; j < invalidPrevTxOutss.Length; j++)
                {
                    invalidPrevTxOutss[j] = new TransactionOutput[blkCons[i].prevTxOutss[j].Length];
                    for (int k = 0; k < invalidPrevTxOutss[j].Length; k++)
                    {
                        if (j == 1 && k == 0)
                        {
                            invalidPrevTxOutss[j][k] = new TransactionOutput();
                            invalidPrevTxOutss[j][k].LoadVersion0(new Sha256Ripemd160Hash(), new CurrencyUnit(0));

                            flag = true;
                        }
                        else
                            invalidPrevTxOutss[j][k] = blkCons[i].prevTxOutss[j][k];
                    }
                }

                if (flag)
                {
                    if (tblk.VerifyRewardAndTxFee(invalidPrevTxOutss))
                        throw new Exception("test12_23");
                    if (tblk.VerifyTransferTransaction(invalidPrevTxOutss))
                        throw new Exception("test12_24");
                }
            }

            Console.WriteLine("test12_succeeded");
        }
Exemple #44
0
 public TransactionOutput GenerateTrasactionOutput()
 {
     TransactionOutput txOut = new TransactionOutput();
     txOut.LoadVersion0(address, amount);
     return txOut;
 }