Beispiel #1
0
        /// <inheritdoc />
        public IReadOnlyList <IDeposit> ExtractDepositsFromBlock(Block block, int blockHeight, DepositRetrievalType[] depositRetrievalTypes)
        {
            var deposits = new List <IDeposit>();

            // If it's an empty block (i.e. only the coinbase transaction is present), there's no deposits inside.
            if (block.Transactions.Count > 1)
            {
                uint256 blockHash = block.GetHash();

                foreach (Transaction transaction in block.Transactions)
                {
                    IDeposit deposit = this.ExtractDepositFromTransaction(transaction, blockHeight, blockHash);

                    if (deposit == null)
                    {
                        continue;
                    }

                    if (depositRetrievalTypes.Any(t => t == deposit.RetrievalType))
                    {
                        deposits.Add(deposit);
                    }
                }
            }

            return(deposits);
        }
Beispiel #2
0
        public AccountDepositResponse Deposit(string accountNumber, decimal amount)
        {
            AccountDepositResponse accountDepositResponse = new AccountDepositResponse
            {
                Account = _accountRepository.LoadAccount(accountNumber)
            };

            if (accountDepositResponse.Account == null)
            {
                Console.WriteLine(accountNumber + " is not an account number.");
                return(accountDepositResponse);
            }
            else
            {
                accountDepositResponse.Amount  = amount;
                accountDepositResponse.Success = true;
            }

            IDeposit depositRule = DepositRulesFactory.Create(accountDepositResponse.Account.Type);

            accountDepositResponse = depositRule.Deposit(accountDepositResponse.Account, amount);

            if (accountDepositResponse.Success)
            {
                _accountRepository.SaveAccount(accountDepositResponse.Account);
            }

            return(accountDepositResponse);
        }
Beispiel #3
0
        public AccountDepositResponse Deposit(string accountNumber, decimal amount)
        {
            AccountDepositResponse response = new AccountDepositResponse();

            response.Account = _accountRepository.LoadAccount(accountNumber);

            if (response.Account == null)
            {
                response.Success = false;
                response.Message = $"{accountNumber} is not a valid account.";
                return(response);
            }
            else
            {
                response.Success = true;
            }

            IDeposit depositRule = DepositRulesFactory.Create(response.Account.Type);

            response = depositRule.Deposit(response.Account, amount);

            if (response.Success)
            {
                _accountRepository.SaveAccount(response.Account);
            }

            return(response);
        }
Beispiel #4
0
        public AccountsController(
            IDeposit deposit,
            IWithdraw withdraw,
            IClose close,
            IAccountsQueries accountsQueries)
        {
            if (deposit == null)
            {
                throw new ArgumentNullException(nameof(deposit));
            }

            if (withdraw == null)
            {
                throw new ArgumentNullException(nameof(withdraw));
            }

            if (close == null)
            {
                throw new ArgumentNullException(nameof(close));
            }

            if (accountsQueries == null)
            {
                throw new ArgumentNullException(nameof(accountsQueries));
            }

            this.deposit         = deposit;
            this.withdraw        = withdraw;
            this.close           = close;
            this.accountsQueries = accountsQueries;
        }
        public void ExtractDepositsFromBlock_Should_Create_One_Deposit_Per_Transaction_To_Multisig()
        {
            Block block = this.network.Consensus.ConsensusFactory.CreateBlock();

            BitcoinPubKeyAddress targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress();

            byte[]      opReturnBytes      = Encoding.UTF8.GetBytes(targetAddress.ToString());
            long        depositAmount      = Money.COIN * 3;
            Transaction depositTransaction = this.transactionBuilder.BuildOpReturnTransaction(
                this.addressHelper.SourceChainMultisigAddress, opReturnBytes, depositAmount);

            block.AddTransaction(depositTransaction);

            this.opReturnDataReader.TryGetTargetAddress(depositTransaction, out string unused1).Returns(callInfo => { callInfo[1] = targetAddress.ToString(); return(true); });

            //add another deposit to the same address
            long        secondDepositAmount      = Money.COIN * 2;
            Transaction secondDepositTransaction = this.transactionBuilder.BuildOpReturnTransaction(
                this.addressHelper.SourceChainMultisigAddress, opReturnBytes, secondDepositAmount);

            block.AddTransaction(secondDepositTransaction);
            this.opReturnDataReader.TryGetTargetAddress(secondDepositTransaction, out string unused2).Returns(callInfo => { callInfo[1] = targetAddress.ToString(); return(true); });

            //add another deposit to a different address
            string newTargetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress().ToString();

            byte[]      newOpReturnBytes        = Encoding.UTF8.GetBytes(newTargetAddress);
            long        thirdDepositAmount      = Money.COIN * 34;
            Transaction thirdDepositTransaction = this.transactionBuilder.BuildOpReturnTransaction(
                this.addressHelper.SourceChainMultisigAddress, newOpReturnBytes, thirdDepositAmount);

            block.AddTransaction(thirdDepositTransaction);

            this.opReturnDataReader.TryGetTargetAddress(thirdDepositTransaction, out string unused3).Returns(callInfo => { callInfo[1] = newTargetAddress; return(true); });

            int blockHeight = 12345;
            IReadOnlyList <IDeposit> extractedDeposits = this.depositExtractor.ExtractDepositsFromBlock(block, blockHeight);

            extractedDeposits.Count.Should().Be(3);
            extractedDeposits.Select(d => d.BlockNumber).Should().AllBeEquivalentTo(blockHeight);
            extractedDeposits.Select(d => d.BlockHash).Should().AllBeEquivalentTo(block.GetHash());

            IDeposit extractedTransaction = extractedDeposits[0];

            extractedTransaction.Amount.Satoshi.Should().Be(depositAmount);
            extractedTransaction.Id.Should().Be(depositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should()
            .Be(targetAddress.ToString());

            extractedTransaction = extractedDeposits[1];
            extractedTransaction.Amount.Satoshi.Should().Be(secondDepositAmount);
            extractedTransaction.Id.Should().Be(secondDepositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should()
            .Be(targetAddress.ToString());

            extractedTransaction = extractedDeposits[2];
            extractedTransaction.Amount.Satoshi.Should().Be(thirdDepositAmount);
            extractedTransaction.Id.Should().Be(thirdDepositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should().Be(newTargetAddress);
        }
Beispiel #6
0
        public ProgramInvoke(byte[] address, byte[] origin, byte[] caller, long balance,
                             long call_value, long token_value, long token_id, byte[] msg,
                             byte[] last_hash, byte[] coinbase, long timestamp,
                             long number, IDeposit deposit, long vm_start, long vm_should_end, long energy_limit)
        {
            this.address     = new DataWord(address);
            this.origin      = new DataWord(origin);
            this.caller      = new DataWord(caller);
            this.balance     = new DataWord(balance);
            this.call_value  = new DataWord(call_value);
            this.token_value = new DataWord(token_value);
            this.token_id    = new DataWord(token_id);
            if (msg != null && msg.Length > 0)
            {
                Array.Copy(msg, 0, this.msg, 0, msg.Length);
            }

            this.prev_hash = new DataWord(last_hash);
            this.coinbase  = new DataWord(coinbase);
            this.timestamp = new DataWord(timestamp);
            this.number    = new DataWord(number);
            this.deposit   = deposit;

            this.vm_start      = vm_start;
            this.vm_should_end = vm_should_end;
            this.energy_limit  = energy_limit;
        }
Beispiel #7
0
        private RunTime(Transaction tx, BlockCapsule block, Deposit deposit, IProgramInvokeFactory invoke_factory)
        {
            this.transaction      = tx;
            this.deposit          = deposit;
            this.invoke_factory   = invoke_factory;
            this.executor_type    = ExecutorType.ET_PRE_TYPE;
            this.block            = block;
            this.energy_processor = new EnergyProcessor(deposit.DBManager);
            ContractType contract_type = tx.RawData.Contract[0].Type;

            switch (contract_type)
            {
            case ContractType.TriggerSmartContract:
            {
                this.transaction_type = TransactionType.TX_CONTRACT_CALL_TYPE;
            }
            break;

            case ContractType.CreateSmartContract:
            {
                this.transaction_type = TransactionType.TX_CONTRACT_CREATION_TYPE;
            }
            break;

            default:
            {
                this.transaction_type = TransactionType.TX_PRECOMPILED_TYPE;
            }
            break;
            }
        }
Beispiel #8
0
        /// <inheritdoc />
        public IReadOnlyList <IDeposit> ExtractDepositsFromBlock(Block block, int blockHeight, DepositRetrievalType depositRetrievalType)
        {
            var deposits = new List <IDeposit>();

            // If it's an empty block, there's no deposits inside.
            if (block.Transactions.Count <= 1)
            {
                return(deposits);
            }

            uint256 blockHash = block.GetHash();

            foreach (Transaction transaction in block.Transactions)
            {
                IDeposit deposit = this.ExtractDepositFromTransaction(transaction, blockHeight, blockHash, depositRetrievalType);
                if (deposit != null)
                {
                    if (depositRetrievalType == DepositRetrievalType.Faster && deposit.Amount <= this.federatedPegSettings.FasterDepositThresholdAmount)
                    {
                        deposits.Add(deposit);
                    }

                    if (depositRetrievalType == DepositRetrievalType.Normal && deposit.Amount > this.federatedPegSettings.FasterDepositThresholdAmount)
                    {
                        deposits.Add(deposit);
                    }
                }
            }

            return(deposits);
        }
Beispiel #9
0
        public ProgramInvoke(DataWord address, DataWord origin, DataWord caller, DataWord balance,
                             DataWord call_value, DataWord token_value, DataWord token_id, byte[] msg,
                             DataWord last_hash, DataWord coinbase, DataWord timestamp, DataWord number,
                             DataWord difficulty,
                             IDeposit deposit, int call_deep, bool is_static_call, bool is_testing_suite,
                             long vm_start, long vm_should_end, long energy_limit)
        {
            this.address     = address;
            this.origin      = origin;
            this.caller      = caller;
            this.balance     = balance;
            this.call_value  = call_value;
            this.token_value = token_value;
            this.token_id    = token_id;
            if (msg != null && msg.Length > 0)
            {
                Array.Copy(msg, 0, this.msg, 0, msg.Length);
            }

            this.prev_hash = last_hash;
            this.coinbase  = coinbase;
            this.timestamp = timestamp;
            this.number    = number;
            this.call_deep = call_deep;

            this.deposit          = deposit;
            this.by_transaction   = false;
            this.is_static_call   = is_static_call;
            this.is_testing_suite = is_testing_suite;
            this.vm_start         = vm_start;
            this.vm_should_end    = vm_should_end;
            this.energy_limit     = energy_limit;
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Owner   firstOwner   = new Owner("Gigi", "Becali", 1110569254156, "Bucuresti");
            Account firstAccount = new Account(firstOwner);

            Console.WriteLine(firstAccount.Withdraw(254875));
            Console.WriteLine(firstAccount.Deposit(1257489));
            Console.WriteLine(firstAccount.Withdraw(254));
            firstAccount.Closing();
            Console.WriteLine(firstAccount.Deposit(255));

            EconomyAccount economyAccount = new EconomyAccount(firstOwner);

            economyAccount.Deposit(100);
            Console.WriteLine(economyAccount.Sum);
            economyAccount.Withdraw(10);
            Console.WriteLine(economyAccount.Sum);

            SecretAccount secretAccount = new SecretAccount(firstOwner);

            secretAccount.Deposit(100);
            Console.WriteLine(secretAccount.Withdraw(10));

            IDeposit deposit = firstAccount;

            deposit = secretAccount;
            deposit = new GameAccount();
        }
 public BankAccountCommand(BankAccount account, DomainModels.Action action, BankCommandArguments bankCmdArgs,
                           IDeposit depositService, IWithdrawl withdrawlService)
 {
     _bankAcount       = account ?? throw new ArgumentNullException(nameof(account), $"cannot have null value for ${nameof(account)}");
     _action           = action;
     _bankCommandArgs  = bankCmdArgs ?? throw new ArgumentNullException(nameof(bankCmdArgs), $"cannot have null value for ${nameof(bankCmdArgs)}");
     _depositService   = depositService ?? throw new ArgumentNullException(nameof(depositService), $"cannot have null value for ${nameof(depositService)}");
     _withdrawlService = withdrawlService ?? throw new ArgumentNullException(nameof(withdrawlService), $"cannot have null value for ${nameof(withdrawlService)}");
 }
Beispiel #12
0
        public static bool ValidateForSmartContract(IDeposit deposit, byte[] owner_address, byte[] to_address, long amount)
        {
            if (!Wallet.IsValidAddress(owner_address))
            {
                throw new ContractValidateException("Invalid ownerAddress");
            }

            if (!Wallet.IsValidAddress(to_address))
            {
                throw new ContractValidateException("Invalid toAddress");
            }

            if (to_address.SequenceEqual(owner_address))
            {
                throw new ContractValidateException("Cannot transfer trx to yourself.");
            }

            AccountCapsule owner_account = deposit.GetAccount(owner_address);

            if (owner_account == null)
            {
                throw new ContractValidateException("Validate InternalTransfer error, no OwnerAccount.");
            }

            AccountCapsule to_account = deposit.GetAccount(to_address);

            if (to_account == null)
            {
                throw new ContractValidateException(
                          "Validate InternalTransfer error, no ToAccount. And not allowed to create account in smart contract.");
            }

            long balance = owner_account.Balance;

            if (amount < 0)
            {
                throw new ContractValidateException("Amount must greater than or equals 0.");
            }

            try
            {
                if (balance < amount)
                {
                    throw new ContractValidateException(
                              "Validate InternalTransfer error, balance is not sufficient.");
                }
            }
            catch (ArithmeticException e)
            {
                Logger.Debug(e.Message);
                throw new ContractValidateException(e.Message);
            }

            return(true);
        }
Beispiel #13
0
        public static void Transfer(IDeposit deposit, byte[] from_address, byte[] to_address, long amount)
        {
            if (amount == 0)
            {
                return;
            }

            TransferActuator.ValidateForSmartContract(deposit, from_address, to_address, amount);
            deposit.AddBalance(to_address, amount);
            deposit.AddBalance(from_address, -amount);
        }
Beispiel #14
0
        public static void TransferToken(IDeposit deposit, byte[] from_address, byte[] to_address, string token_id, long amount)
        {
            if (0 == amount)
            {
                return;
            }

            byte[] token = Encoding.UTF8.GetBytes(token_id);
            TransferAssetActuator.ValidateForSmartContract(deposit, from_address, to_address, token, amount);
            deposit.AddTokenBalance(to_address, token, amount);
            deposit.AddTokenBalance(from_address, token, -amount);
        }
Beispiel #15
0
 public Details(IDeposit deposit)
 {
     Deposit = new DepositDetailsModel
     {
         Income     = Math.Round(deposit.Calculate(), 2),
         Rate       = deposit.IncomeRate,
         TimeActive = deposit.EndDate == DateTime.MaxValue ? "Unlimited OnDemand" : Util.YearDiff(deposit.StartDate, deposit.EndDate).ToString(),
         Type       = GetDepositType(deposit)
     };
     InitializeComponent();
     detailsGrid.DataContext = Deposit;
 }
Beispiel #16
0
        private void CountVoteAccount(VoteWitnessContract contract, IDeposit deposit)
        {
            byte[] owner_address = contract.OwnerAddress.ToByteArray();

            VotesCapsule   votes   = null;
            AccountCapsule account = (Deposit == null) ? db_manager.Account.Get(owner_address) : Deposit.GetAccount(owner_address);

            if (Deposit != null)
            {
                if (Deposit.GetVotesCapsule(owner_address) == null)
                {
                    votes = new VotesCapsule(contract.OwnerAddress, account.GetVotesList());
                }
                else
                {
                    votes = Deposit.GetVotesCapsule(owner_address);
                }
            }
            else if (!db_manager.Votes.Contains(owner_address))
            {
                votes = new VotesCapsule(contract.OwnerAddress, account.GetVotesList());
            }
            else
            {
                votes = db_manager.Votes.Get(owner_address);
            }

            account.ClearVotes();
            votes.ClearNewVotes();

            foreach (Protocol.VoteWitnessContract.Types.Vote vote in contract.Votes)
            {
                Logger.Debug(
                    string.Format(
                        "CountVoteAccount, address[{0}]",
                        vote.VoteAddress.ToByteArray().ToHexString()));

                votes.AddNewVotes(vote.VoteAddress, vote.VoteCount);
                account.AddVotes(vote.VoteAddress, vote.VoteCount);
            }

            if (Deposit == null)
            {
                db_manager.Account.Put(account.CreateDatabaseKey(), account);
                db_manager.Votes.Put(owner_address, votes);
            }
            else
            {
                deposit.PutAccountValue(account.CreateDatabaseKey(), account);
                deposit.PutVoteValue(owner_address, votes);
            }
        }
 public static IDepositStateMachine CreateStateMachine(IDeposit deposit)
 {
     switch (deposit.State)
     {
         case DepositState.Pending:
             return new DepositWaitProcessStateMachine(deposit);
         case DepositState.Verify:
             return new DepositVerifyStateMachine(deposit);
         case DepositState.Complete:
             return new DepositCompleteStateMachine(deposit);
         default: return null;
     }
 }
Beispiel #18
0
        public AccountDepositResponse Deposit(string accountNumber, decimal amount)
        {
            AccountDepositResponse response = new AccountDepositResponse();

            try
            {
                response.Account = _accountRepository.LoadAccount(accountNumber);
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                return(response);
            }

            if (response.Account == null)
            {
                response.Success = false;
                response.Message = $"{accountNumber} is not a valid account.";
                return(response);
            }
            else if (response.Account.Name == "Error")
            {
                response.Success = false;
                response.Message = "Error: something went wrong while accessing the file repository. Contact IT.";
                return(response);
            }
            else
            {
                response.Success = true;
            }

            IDeposit depositRule = DepositRulesFactory.CreateDepositRule(response.Account.Type);

            response = depositRule.Deposit(response.Account, amount);
            if (response.Success)
            {
                try
                {
                    _accountRepository.SaveAccount(response.Account);
                }
                catch (Exception ex)
                {
                    response.Success = false;
                    response.Message = ex.Message;
                    return(response);
                }
            }

            return(response);
        }
        public IProgramInvoke CreateProgramInvoke(Program program,
                                                  DataWord to_adderess,
                                                  DataWord caller_address,
                                                  DataWord in_value,
                                                  DataWord token_value,
                                                  DataWord token_id,
                                                  long in_balance,
                                                  byte[] in_data,
                                                  IDeposit deposit,
                                                  bool is_static_call,
                                                  bool is_testing_suite,
                                                  long vm_start,
                                                  long vm_should_end,
                                                  long energy_limit)
        {
            DataWord address    = to_adderess;
            DataWord origin     = program.OriginAddress;
            DataWord caller     = caller_address;
            DataWord balance    = new DataWord(in_balance);
            DataWord call_value = in_value;

            byte[] data = null;
            Array.Copy(in_data, 0, data, 0, in_data.Length);

            DataWord last_hash  = program.PrevHash;
            DataWord coinbase   = program.Coinbase;
            DataWord timestamp  = program.Timestamp;
            DataWord number     = program.Number;
            DataWord difficulty = program.Difficulty;

            return(new ProgramInvoke(address,
                                     origin,
                                     caller,
                                     balance,
                                     call_value,
                                     token_value,
                                     token_id,
                                     data,
                                     last_hash,
                                     coinbase,
                                     timestamp,
                                     number,
                                     difficulty,
                                     deposit,
                                     program.CallDeep + 1,
                                     is_static_call,
                                     is_testing_suite,
                                     vm_start,
                                     vm_should_end,
                                     energy_limit));
        }
Beispiel #20
0
        public void PremiumAccountDepositTests(string accountNumber, string name, decimal balance, AccountType accountType, decimal amount, bool expectedResult)
        {
            IDeposit deposit = DepositRulesFactory.Create(AccountType.Premium);
            Account  account = new Account();

            account.AccountNumber = accountNumber;
            account.Name          = name;
            account.Balance       = balance;
            account.Type          = accountType;

            AccountDepositResponse response = deposit.Deposit(account, amount);

            Assert.AreEqual(expectedResult, response.Success);
        }
Beispiel #21
0
        public static void TransferAllToken(IDeposit deposit, byte[] from_address, byte[] to_address)
        {
            AccountCapsule from_account = deposit.GetAccount(from_address);
            AccountCapsule to_account   = deposit.GetAccount(to_address);

            foreach (var asset in from_account.AssetV2)
            {
                to_account.AssetV2.TryGetValue(asset.Key, out long value);
                to_account.AddAssetV2(asset.Key, value + asset.Value);
                from_account.AddAssetV2(asset.Key, 0);
            }

            deposit.PutAccountValue(from_address, from_account);
            deposit.PutAccountValue(to_address, to_account);
        }
Beispiel #22
0
        public void RewardClaimer_RetrieveDeposits_Scenario1()
        {
            // Create a "chain" of 30 blocks.
            this.blocks = ChainedHeadersHelper.CreateConsecutiveHeadersAndBlocks(30, true, network: this.network, chainIndexer: this.chainIndexer, withCoinbaseAndCoinStake: true, createCirrusReward: true);
            var rewardClaimer = new RewardClaimer(this.broadCasterManager, this.chainIndexer, this.consensusManager, this.loggerFactory, this.network, this.signals, this.initialBlockDownloadState);

            var depositExtractor = new DepositExtractor(this.federatedPegSettings, this.network, this.opReturnDataReader);

            // Add 5 distribution deposits from block 11 through to 15.
            for (int i = 11; i <= 15; i++)
            {
                Transaction rewardTransaction = rewardClaimer.BuildRewardTransaction();
                IDeposit    deposit           = depositExtractor.ExtractDepositFromTransaction(rewardTransaction, i, this.blocks[i].Block.GetHash());
                Assert.NotNull(deposit);
            }
        }
Beispiel #23
0
        /// <inheritdoc />
        public IReadOnlyList <IDeposit> ExtractDepositsFromBlock(Block block, int blockHeight)
        {
            var     deposits  = new List <IDeposit>();
            uint256 blockHash = block.GetHash();

            foreach (Transaction transaction in block.Transactions)
            {
                IDeposit deposit = ExtractDepositFromTransaction(transaction, blockHeight, blockHash);
                if (deposit != null)
                {
                    deposits.Add(deposit);
                }
            }

            return(deposits.AsReadOnly());
        }
        [TestCase("33333", "BasicAccount", 100, AccountType.Basic, 250, true)]     //Pass
        public void BasicAccount_DepositRuleTest(string accountNumber, string name, decimal balance, AccountType accountType, decimal amount, bool expectedResult)
        {
            IDeposit depositRule = DepositRulesFactory.Create(AccountType.Basic);

            Account account = new Account()
            {
                AccountNumber = accountNumber,
                Balance       = balance,
                Name          = name,
                Type          = accountType
            };

            AccountDepositResponse response = depositRule.Deposit(account, amount);

            Assert.AreEqual(expectedResult, response.Success);
        }
Beispiel #25
0
        public void Process(IDeposit deposit)
        {
            var asset = GetAsset(deposit.Asset);

            var fundsOriginAsset = GetFundOriginAsset(deposit.Asset);

            if (fundsOriginAsset.Amount >= deposit.Amount)
            {
                asset.TransferPosition(fundsOriginAsset, deposit.Amount, deposit.InsertTime, deposit);
                return;
            }

            var withdrawnAsset = GetWithdrawnAsset(deposit.Asset);

            asset.TransferPosition(withdrawnAsset, deposit.Amount, deposit.InsertTime, deposit);
        }
        public void ExtractDepositsFromBlock_Should_Only_Find_Deposits_To_Multisig()
        {
            Block block = this.network.Consensus.ConsensusFactory.CreateBlock();

            BitcoinPubKeyAddress targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress();

            byte[]      opReturnBytes      = Encoding.UTF8.GetBytes(targetAddress.ToString());
            long        depositAmount      = Money.COIN * 3;
            Transaction depositTransaction = this.transactionBuilder.BuildOpReturnTransaction(
                this.addressHelper.SourceChainMultisigAddress, opReturnBytes, depositAmount);

            block.AddTransaction(depositTransaction);

            this.opReturnDataReader.TryGetTargetAddress(depositTransaction)
            .Returns(targetAddress.ToString());

            Transaction nonDepositTransactionToMultisig = this.transactionBuilder.BuildTransaction(
                this.addressHelper.SourceChainMultisigAddress);

            block.AddTransaction(nonDepositTransactionToMultisig);

            BitcoinPubKeyAddress otherAddress = this.addressHelper.GetNewSourceChainPubKeyAddress();

            otherAddress.ToString().Should().NotBe(this.addressHelper.SourceChainMultisigAddress.ToString(),
                                                   "otherwise the next deposit should actually be extracted");
            Transaction depositTransactionToOtherAddress =
                this.transactionBuilder.BuildOpReturnTransaction(otherAddress, opReturnBytes);

            block.AddTransaction(depositTransactionToOtherAddress);

            Transaction nonDepositTransactionToOtherAddress = this.transactionBuilder.BuildTransaction(
                otherAddress);

            block.AddTransaction(nonDepositTransactionToOtherAddress);

            int blockHeight = 230;
            IReadOnlyList <IDeposit> extractedDeposits = this.depositExtractor.ExtractDepositsFromBlock(block, blockHeight);

            extractedDeposits.Count.Should().Be(1);
            IDeposit extractedTransaction = extractedDeposits[0];

            extractedTransaction.Amount.Satoshi.Should().Be(depositAmount);
            extractedTransaction.Id.Should().Be(depositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should().Be(targetAddress.ToString());
            extractedTransaction.BlockNumber.Should().Be(blockHeight);
            extractedTransaction.BlockHash.Should().Be(block.GetHash());
        }
Beispiel #27
0
        /// <inheritdoc />
        public IReadOnlyList <IDeposit> ExtractDepositsFromBlock(Block block, int blockHeight, DepositRetrievalType depositRetrievalType)
        {
            var deposits = new List <IDeposit>();

            // If it's an empty block (i.e. only the coinbase transaction is present), there's no deposits inside.
            if (block.Transactions.Count <= 1)
            {
                return(deposits);
            }

            uint256 blockHash = block.GetHash();

            foreach (Transaction transaction in block.Transactions)
            {
                IDeposit deposit = this.ExtractDepositFromTransaction(transaction, blockHeight, blockHash, depositRetrievalType);
                if (deposit == null)
                {
                    continue;
                }

                if (depositRetrievalType == DepositRetrievalType.Small && deposit.Amount <= this.federatedPegSettings.SmallDepositThresholdAmount)
                {
                    deposits.Add(deposit);
                    continue;
                }

                if (depositRetrievalType == DepositRetrievalType.Normal && deposit.Amount > this.federatedPegSettings.SmallDepositThresholdAmount && deposit.Amount <= this.federatedPegSettings.NormalDepositThresholdAmount)
                {
                    deposits.Add(deposit);
                    continue;
                }

                if (depositRetrievalType == DepositRetrievalType.Large && deposit.Amount > this.federatedPegSettings.NormalDepositThresholdAmount)
                {
                    deposits.Add(deposit);
                    continue;
                }

                if (depositRetrievalType == DepositRetrievalType.Distribution)
                {
                    deposits.Add(deposit);
                }
            }

            return(deposits);
        }
Beispiel #28
0
        public void FreeAccountDepositRuleTest(string accountNumber, string name, decimal balance, AccountType accountType, decimal amount, bool expectedResult)
        {
            FreeAccountDepositRule DepositRule = new FreeAccountDepositRule();
            Account account = new Account();

            IDeposit    deposit = DepositRule;
            AccountType type    = account.Type;

            account.AccountNumber = accountNumber;
            account.Type          = accountType;
            account.Name          = name;
            account.Balance       = balance;

            AccountDepositResponse response = deposit.Deposit(account, amount);

            Assert.AreEqual(expectedResult, response.Success);
        }
        public void ExtractNormalDeposits_ShouldCreate_OneDepositPerTransaction_ToMultisig()
        {
            Block block = this.network.Consensus.ConsensusFactory.CreateBlock();

            BitcoinPubKeyAddress targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress();

            byte[] opReturnBytes = Encoding.UTF8.GetBytes(targetAddress.ToString());

            // Create a "normal" deposit.
            Transaction depositTransaction = CreateDepositTransaction(targetAddress, block, Money.Coins(11), opReturnBytes);

            // Create another "normal" deposit to the same address.
            Transaction secondDepositTransaction = CreateDepositTransaction(targetAddress, block, Money.Coins(12), opReturnBytes);

            // Create another "normal" deposit to a different address.
            BitcoinPubKeyAddress newTargetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress();

            byte[]      newOpReturnBytes        = Encoding.UTF8.GetBytes(newTargetAddress.ToString());
            Transaction thirdDepositTransaction = CreateDepositTransaction(newTargetAddress, block, Money.Coins(12), newOpReturnBytes);

            int blockHeight = 12345;
            IReadOnlyList <IDeposit> extractedDeposits = this.depositExtractor.ExtractDepositsFromBlock(block, blockHeight, new[] { DepositRetrievalType.Normal });

            extractedDeposits.Count.Should().Be(3);
            extractedDeposits.Select(d => d.BlockNumber).Should().AllBeEquivalentTo(blockHeight);
            extractedDeposits.Select(d => d.BlockHash).Should().AllBeEquivalentTo(block.GetHash());

            IDeposit extractedTransaction = extractedDeposits[0];

            extractedTransaction.Amount.Satoshi.Should().Be(Money.Coins(11));
            extractedTransaction.Id.Should().Be(depositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should()
            .Be(targetAddress.ToString());

            extractedTransaction = extractedDeposits[1];
            extractedTransaction.Amount.Satoshi.Should().Be(Money.Coins(12));
            extractedTransaction.Id.Should().Be(secondDepositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should()
            .Be(targetAddress.ToString());

            extractedTransaction = extractedDeposits[2];
            extractedTransaction.Amount.Satoshi.Should().Be(Money.Coins(12));
            extractedTransaction.Id.Should().Be(thirdDepositTransaction.GetHash());
            extractedTransaction.TargetAddress.Should().Be(newTargetAddress.ToString());
        }
Beispiel #30
0
        public void DoTest()
        {
            var transactionRequest = new BuildTransactionRequest()
            {
                FeeAmount = "0.01",
                // Change this to the address that should receive the funds.
                OpReturnData     = "PLv2NAsyn22cNbk5veopWCkypaN6DBR27L",
                AccountName      = "account 0",
                AllowUnconfirmed = true,
                Recipients       = new List <RecipientModel> {
                    new RecipientModel {
                        DestinationAddress = "2MyKFLbvhSouDYeAHhxsj9a5A4oV71j7SPR",
                        Amount             = "1.1"
                    }
                },
                Password   = "******",
                WalletName = "test"
            };

            WalletBuildTransactionModel model = Post <BuildTransactionRequest, WalletBuildTransactionModel>(
                "http://127.0.0.1:38221/api/wallet/build-transaction", transactionRequest);

            var transaction = new PosTransaction(model.Hex);

            var      reader    = new OpReturnDataReader(this.loggerFactory, Networks.Stratis.Testnet());
            var      extractor = new DepositExtractor(this.loggerFactory, this.federationGatewaySettings, reader, this.fullNode);
            IDeposit deposit   = extractor.ExtractDepositFromTransaction(transaction, 2, 1);

            Assert.NotNull(deposit);
            Assert.Equal(transaction.GetHash(), deposit.Id);
            Assert.Equal(transactionRequest.OpReturnData, deposit.TargetAddress);
            Assert.Equal(Money.Parse(transactionRequest.Recipients[0].Amount), deposit.Amount);
            Assert.Equal((uint256)1, deposit.BlockHash);
            Assert.Equal(2, deposit.BlockNumber);

            // Post the transaction
            var sendRequest = new SendTransactionRequest()
            {
                Hex = model.Hex
            };

            WalletSendTransactionModel model2 = Post <SendTransactionRequest, WalletSendTransactionModel>(
                "http://127.0.0.1:38221/api/wallet/send-transaction", sendRequest);
        }
Beispiel #31
0
 private string GetDepositType(IDeposit deposit)
 {
     if (deposit is OnDemandDeposit)
     {
         return("OnDemand");
     }
     else if (deposit is SavingDeposit)
     {
         return("Saving");
     }
     else if (deposit is OnTermDeposit)
     {
         return("OnTerm");
     }
     else
     {
         throw new Exception("Not supported deposit type");
     }
 }
        public DepositWaitProcessStateMachine(IDeposit deposit)
        {
            Check.Argument.IsNotNull(deposit, "deposit");

            this._deposit = deposit;
        }
 public decimal Deposit(IDeposit account, decimal amount)
 {
     throw new NotImplementedException();
 }
        public DepositCompleteStateMachine(IDeposit deposit)
        {
            Check.Argument.IsNotNull(deposit, "deposit");

            this._deposit = deposit;
        }