Exemplo n.º 1
0
        public IRpcMethodResult GetNewAddress(string tag)
        {
            try
            {
                var       accountComponent = new AccountComponent();
                Account   account          = null;
                var       setting          = new SettingComponent().GetSetting();
                AccountOM result           = null;

                if (setting.Encrypt)
                {
                    if (!string.IsNullOrWhiteSpace(_cache.Get <string>("WalletPassphrase")))
                    {
                        account            = accountComponent.GenerateNewAccount();
                        account.IsDefault  = true;
                        account.PrivateKey = AES128.Encrypt(account.PrivateKey, _cache.Get <string>("WalletPassphrase"));
                        accountComponent.UpdatePrivateKeyAr(account);
                    }
                    else
                    {
                        throw new CommonException(ErrorCode.Service.Wallet.WALLET_HAS_BEEN_LOCKED);
                    }
                }
                else
                {
                    account           = accountComponent.GenerateNewAccount();
                    account.IsDefault = true;
                }

                if (account != null)
                {
                    account.Tag = tag;
                    accountComponent.UpdateTag(account.Id, tag);

                    result           = new AccountOM();
                    result.Address   = account.Id;
                    result.PublicKey = account.PublicKey;
                    result.Balance   = account.Balance;
                    result.IsDefault = account.IsDefault;
                    result.WatchOnly = account.WatchedOnly;
                    result.Tag       = account.Tag;
                }

                return(Ok(result));
            }
            catch (CommonException ce)
            {
                return(Error(ce.ErrorCode, ce.Message, ce));
            }
            catch (Exception ex)
            {
                return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
            }
        }
Exemplo n.º 2
0
        public static void Initialize()
        {
            var notify = new NotifyComponent();
            BlockchainComponent blockChainComponent = new BlockchainComponent();
            AccountComponent    accountComponent    = new AccountComponent();
            UtxoComponent       utxoComponent       = new UtxoComponent();

            //从配置文件中读取
            ConfigurationTool tool   = new ConfigurationTool();
            NodeConfig        config = tool.GetAppSettings <NodeConfig>("NodeConfig");

            notify.SetCallbackApp(config.WalletNotify);

            if (GlobalActions.TransactionNotifyAction == null)
            {
                GlobalActions.TransactionNotifyAction = NewTransactionNotify;
            }

            blockChainComponent.Initialize();
            var accounts = accountComponent.GetAllAccounts();

            if (accounts.Count == 0)
            {
                var account = accountComponent.GenerateNewAccount();
                accountComponent.SetDefaultAccount(account.Id);
            }

            BlockchainJob.Current = new BlockchainJob();
            utxoComponent.Initialize();
        }
Exemplo n.º 3
0
        public static void Initialize()
        {
            BlockchainComponent blockChainComponent = new BlockchainComponent();
            AccountComponent    accountComponent    = new AccountComponent();
            UtxoComponent       utxoComponent       = new UtxoComponent();

            blockChainComponent.Initialize();
            var accounts = accountComponent.GetAllAccounts();

            if (accounts.Count == 0)
            {
                var account = accountComponent.GenerateNewAccount();
                accountComponent.SetDefaultAccount(account.Id);
            }

            BlockchainJob.Current = new BlockchainJob();
            utxoComponent.Initialize();
        }
Exemplo n.º 4
0
        private void transactionTest()
        {
            var utxoComponent        = new UtxoComponent();
            var transactionComponent = new TransactionComponent();
            var accountComponent     = new AccountComponent();

            if (string.IsNullOrWhiteSpace(this.newAccountId))
            {
                var newAccount = accountComponent.GenerateNewAccount();
                this.newAccountId = newAccount.Id;
            }

            var defaultAccount = accountComponent.GetDefaultAccount();

            if (defaultAccount != null)
            {
                var balance = utxoComponent.GetConfirmedBlanace(defaultAccount.Id);
                var amount  = 50000000000L;
                var fee     = 1000000L;

                if (balance > (amount + fee))
                {
                    var dict = new Dictionary <string, long>();
                    dict.Add(newAccountId, amount);

                    var txMsg = transactionComponent.CreateNewTransactionMsg(defaultAccount.Id, dict, fee);
                    transactionComponent.AddTransactionToPool(txMsg);

                    LogHelper.Debug("====== A New transaction has been created. " + txMsg.Hash);

                    if (BlockchainJob.Current.P2PJob != null)
                    {
                        BlockchainJob.Current.P2PJob.BroadcastNewTransactionMessage(txMsg.Hash);
                    }
                }
            }
        }
Exemplo n.º 5
0
        public static void Initialize()
        {
            var notify = new NotifyComponent();
            BlockchainComponent blockChainComponent = new BlockchainComponent();
            AccountComponent    accountComponent    = new AccountComponent();

            BlockchainJob.Current = new BlockchainJob();

            BlockDac.Default.GetAccountByLockScript = BlockchainJob.Current.GetAccountByLockScript;

            //从配置文件中读取
            ConfigurationTool tool = new ConfigurationTool();

            config = tool.GetAppSettings <NodeConfig>("NodeConfig");
            if (config == null)
            {
                GlobalParameters.IsPool = false;
                config = new NodeConfig();
            }
            else
            {
                notify.SetCallbackApp(config.WalletNotify);
                BlockchainJob.Current.P2PJob.LocalIP = config.LocalIP;
                GlobalParameters.IsPool = config.IsPool;
            }

            ConfigCenter.ConfigNode = config;



            //TODO 待验证删除
            //if (config != null)
            //{
            //    notify.SetCallbackApp(config.WalletNotify);
            //    BlockchainJob.Current.P2PJob.IPAddress = config.Ip;
            //    GlobalParameters.IsPool = config.IsPool;
            //}
            //else
            //{
            //    GlobalParameters.IsPool = false;
            //}

            if (GlobalActions.TransactionNotifyAction == null)
            {
                GlobalActions.TransactionNotifyAction = NewTransactionNotify;
            }

            blockChainComponent.Initialize();
            var accounts = AccountDac.Default.GetAccountBook();

            if (accounts.Count == 0)
            {
                var account = accountComponent.GenerateNewAccount(false);
                accountComponent.SetDefaultAccount(account.Id);
            }

            var defaultAccount = AppDac.Default.GetDefaultAccount();

            if (string.IsNullOrEmpty(defaultAccount))
            {
                var first = AccountDac.Default.GetAccountBook().FirstOrDefault();
                UserSettingComponent component = new UserSettingComponent();
                component.SetDefaultAccount(first);
            }

            TransactionPool.Instance.Load();
        }
Exemplo n.º 6
0
        public IRpcMethodResult SendMany(string fromAccount, SendManyOutputIM[] receivers, string[] feeDeductAddresses)
        {
            try
            {
                string result                      = null;
                var    utxoComponent               = new UtxoComponent();
                var    txComponent                 = new TransactionComponent();
                var    settingComponent            = new SettingComponent();
                var    addressBookComponent        = new AddressBookComponent();
                var    accountComponent            = new AccountComponent();
                var    transactionCommentComponent = new TransactionCommentComponent();
                var    blockComponent              = new BlockComponent();
                var    lastBlockHeight             = blockComponent.GetLatestHeight();

                var    setting     = settingComponent.GetSetting();
                var    utxos       = utxoComponent.GetAllConfirmedOutputs();
                var    tx          = new TransactionMsg();
                double totalOutput = 0;
                var    totalSize   = tx.Serialize().Length;

                if (receivers == null || receivers.Length == 0)
                {
                    throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID);
                }

                foreach (var receiver in receivers)
                {
                    if (!AccountIdHelper.AddressVerify(receiver.address))
                    {
                        throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID);
                    }

                    var output = new OutputMsg();
                    output.Amount     = receiver.amount;
                    output.Index      = tx.Outputs.Count;
                    output.LockScript = Script.BuildLockScipt(receiver.address);
                    output.Size       = output.LockScript.Length;
                    tx.Outputs.Add(output);

                    totalSize   += output.Serialize().Length;
                    totalOutput += receiver.amount;
                }

                foreach (var address in feeDeductAddresses)
                {
                    if (receivers.Where(r => r.address == address).Count() == 0)
                    {
                        throw new CommonException(ErrorCode.Service.Transaction.FEE_DEDUCT_ADDRESS_INVALID);
                    }
                }

                var    totalInput  = 0L;
                var    index       = 0;
                double totalFee    = setting.FeePerKB * ((double)totalSize / 1024.0);
                double totalAmount = totalOutput;

                while (index < utxos.Count)
                {
                    var account = accountComponent.GetAccountById(utxos[index].AccountId);

                    if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                    {
                        var   utxoTX    = txComponent.GetTransactionMsgByHash(utxos[index].TransactionHash);
                        Block utxoBlock = blockComponent.GetBlockEntiytByHash(utxos[index].BlockHash);

                        if (utxoTX == null || utxoBlock == null)
                        {
                            index++;
                            continue;
                        }

                        if (!utxoBlock.IsVerified)
                        {
                            index++;
                            continue;
                        }

                        if (Time.EpochTime < utxoTX.Locktime)
                        {
                            index++;
                            continue;
                        }

                        if (utxoTX.InputCount == 1 && utxoTX.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash()))
                        {
                            var blockHeight = utxoBlock.Height;

                            if (lastBlockHeight - blockHeight < 100L)
                            {
                                index++;
                                continue;
                            }
                        }

                        var input = new InputMsg();
                        input.OutputTransactionHash = utxos[index].TransactionHash;
                        input.OutputIndex           = utxos[index].OutputIndex;
                        input.UnlockScript          = Script.BuildUnlockScript(input.OutputTransactionHash, input.OutputIndex, Base16.Decode(decryptPrivateKey(account.PrivateKey)), Base16.Decode(account.PublicKey));
                        input.Size = input.UnlockScript.Length;
                        tx.Inputs.Add(input);

                        var size = input.Serialize().Length;
                        totalSize  += size;
                        totalFee   += setting.FeePerKB * ((double)size / 1024.0);
                        totalInput += utxos[index].Amount;
                    }
                    else
                    {
                        index++;
                        continue;
                    }

                    if (feeDeductAddresses == null || feeDeductAddresses.Length == 0)
                    {
                        totalAmount = totalOutput + totalFee;
                    }

                    if (totalInput >= (long)Math.Ceiling(totalAmount))
                    {
                        var size = tx.Outputs[0].Serialize().Length;

                        if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0))
                        {
                            totalSize += size;
                            totalFee  += setting.FeePerKB * ((double)size / 1024.0);

                            if (feeDeductAddresses == null || feeDeductAddresses.Length == 0)
                            {
                                totalAmount = totalOutput + totalFee;
                            }


                            var newAccount = accountComponent.GenerateNewAccount();

                            if (setting.Encrypt)
                            {
                                if (!string.IsNullOrWhiteSpace(_cache.Get <string>("WalletPassphrase")))
                                {
                                    newAccount.PrivateKey = AES128.Encrypt(newAccount.PrivateKey, _cache.Get <string>("WalletPassphrase"));
                                    accountComponent.UpdatePrivateKeyAr(newAccount);
                                }
                                else
                                {
                                    throw new CommonException(ErrorCode.Service.Wallet.WALLET_HAS_BEEN_LOCKED);
                                }
                            }

                            var newOutput = new OutputMsg();
                            newOutput.Amount     = totalInput - (long)Math.Ceiling(totalAmount);
                            newOutput.Index      = tx.Outputs.Count;
                            newOutput.LockScript = Script.BuildLockScipt(newAccount.Id);
                            newOutput.Size       = newOutput.LockScript.Length;
                            tx.Outputs.Add(newOutput);
                        }

                        break;
                    }

                    index++;
                }

                if (totalInput < totalAmount)
                {
                    throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH);
                }

                if (feeDeductAddresses != null && feeDeductAddresses.Length > 0)
                {
                    var averageFee = totalFee / feeDeductAddresses.Length;

                    for (int i = 0; i < receivers.Length; i++)
                    {
                        if (feeDeductAddresses.Contains(receivers[i].address))
                        {
                            tx.Outputs[i].Amount -= (long)Math.Ceiling(averageFee);

                            if (tx.Outputs[i].Amount <= 0)
                            {
                                throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE);
                            }
                        }
                    }
                }

                tx.Timestamp = Time.EpochTime;
                tx.Hash      = tx.GetHash();
                txComponent.AddTransactionToPool(tx);
                Startup.P2PBroadcastTransactionAction(tx.Hash);
                result = tx.Hash;

                for (int i = 0; i < receivers.Length; i++)
                {
                    var receiver = receivers[i];

                    if (!string.IsNullOrWhiteSpace(receiver.tag))
                    {
                        addressBookComponent.SetTag(receiver.address, receiver.tag);
                    }

                    if (!string.IsNullOrWhiteSpace(receiver.comment))
                    {
                        transactionCommentComponent.Add(tx.Hash, i, receiver.comment);
                    }
                }

                return(Ok(result));
            }
            catch (CommonException ce)
            {
                return(Error(ce.ErrorCode, ce.Message, ce));
            }
            catch (Exception ex)
            {
                return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
            }
        }