public IRpcMethodResult ImportAddresses(string jsontext) { try { List <Account> accounts = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Account> >(jsontext); AccountComponent component = new AccountComponent(); foreach (var item in accounts) { Account account = new Account(); account.Id = item.Id; account.Balance = 0; account.IsDefault = false; account.PrivateKey = ""; account.PublicKey = item.PublicKey; account.Tag = ""; account.Timestamp = Time.EpochTime; account.WatchedOnly = true; AccountDac.Default.Insert(account); } return(Ok()); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult SignMessage(string address, string message) { try { var account = new AccountComponent().GetAccountById(address); if (account == null || string.IsNullOrWhiteSpace(account.PrivateKey)) { throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND); } ECDsa dsa = ECDsa.ImportPrivateKey(Base16.Decode(DecryptPrivateKey(account.PrivateKey))); var signResult = Base16.Encode(dsa.SingnData(Encoding.UTF8.GetBytes(message))); var result = new { signature = signResult, publicKey = account.PublicKey }; return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public static AccountComponent GetAccountComponent(Database.Account account) { AccountComponent accountComponent = new AccountComponent() { AppliedEntitlements = new Dictionary <string, int>(), DailyQuestsAvailable = Config.ConfigManager.DailyQuestsAvailable, DisplayDevTag = false, FactionCompetitionData = new Dictionary <int, PlayerFactionCompetitionData>(), FreeRotationCharacters = new CharacterType[] { }, LastCharacter = account.LastCharacter, SelectedBackgroundBannerID = account.BannerID, SelectedForegroundBannerID = account.EmblemID, SelectedRibbonID = account.RibbonID, SelectedTitleID = account.TitleID, UnlockedBannerIDs = InventoryManager.GetUnlockedBannerIDs(account.AccountId), UIStates = new Dictionary <AccountComponent.UIStateIdentifier, int> { { AccountComponent.UIStateIdentifier.HasViewedFluxHighlight, 1 }, { AccountComponent.UIStateIdentifier.HasViewedGGHighlight, 1 } }, UnlockedEmojiIDs = InventoryManager.GetUnlockedEmojiIDs(account.AccountId), UnlockedLoadingScreenBackgroundIdsToActivatedState = InventoryManager.GetActivatedLoadingScreenBackgroundIds(account.AccountId), UnlockedOverconIDs = InventoryManager.GetUnlockedOverconIDs(account.AccountId), UnlockedTitleIDs = InventoryManager.GetUnlockedTitleIDs(account.AccountId), UnlockedRibbonIDs = InventoryManager.GetUnlockedRibbonIDs(account.AccountId) }; return(accountComponent); }
public IRpcMethodResult SetDefaultAccount(string address) { try { var accountComponent = new AccountComponent(); var account = accountComponent.GetAccountById(address); if (account != null) { accountComponent.SetDefaultAccount(account.Id); } else { throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND); } return(Ok()); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
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(); }
public async Task <ActionResult> ResetPsw(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var accountComponent = new AccountComponent(); var account = await accountComponent.GetAccountByIdAsync(AccountInfo.Id); try { SecurityVerify.Verify <PasswordVerification>(account.Id.ToString(), account.Password, model.OldPassword); } catch (ApplicationException ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } catch (Exception) { ModelState.AddModelError("", GeneralResource.SaveFailed); return(View(model)); } await accountComponent.ResetPasswordAsync(account.Id, PasswordHasher.HashPassword(model.NewPassword)); EmptyLoginInfo(); ViewBag.PasswordHasSet = "1"; ViewBag.PageName = MerchantIndex.Pagename; return(View(model)); }
public IRpcMethodResult GetAccountByAddress(string address) { try { var utxoComponent = new UtxoComponent(); var account = new AccountComponent().GetAccountById(address); if (account != null) { var result = new AccountOM(); result.Address = account.Id; result.PublicKey = account.PublicKey; result.Balance = utxoComponent.GetConfirmedBlanace(account.Id); result.IsDefault = account.IsDefault; result.WatchOnly = account.WatchedOnly; result.Tag = account.Tag; return(Ok(result)); } else { throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult GetAddressesByTag(string tag) { try { var accountComponent = new AccountComponent(); var accounts = accountComponent.GetAccountsByTag(tag); var result = new List <AccountOM>(); foreach (var account in accounts) { var item = new AccountOM(); item.Address = account.Id; item.PublicKey = account.PublicKey; item.Balance = account.Balance; item.IsDefault = account.IsDefault; item.WatchOnly = account.WatchedOnly; item.Tag = account.Tag; result.Add(item); } return(Ok(result.ToArray())); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
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)); } }
public OverlayInfo() { object[] o = { Properties.Settings.Default.APIKey }; InitializeComponent(); obj = new GW2Object(); apikey = obj.AddComponent <APIKeyInfoComponent>(o); permissions = obj.AddComponent <APIKeyPermissionsComponent>(null); accountInfo = obj.AddComponent <AccountComponent>(null); obj.AddComponent <ItemTradeComponent>(null); loadItemProjects(); }
public ActionResult Index() { ViewBag.PageName = MerchantIndex.Pagename; var account = new AccountComponent().GetAccountById(AccountInfo.Id); BaseInfomationModel info = new BaseInfomationModel { MerchantId = account.Username, Email = account.Email, Password = "******" }; return(View(info)); }
public IRpcMethodResult ValidateAddress(string address) { try { var result = new ValidateAddressOM(); var accountComponent = new AccountComponent(); result.address = address; if (AccountIdHelper.AddressVerify(address)) { result.isValid = true; var account = accountComponent.GetAccountById(address); if (account != null) { result.isMine = true; result.isWatchOnly = string.IsNullOrWhiteSpace(account.PrivateKey); } else { result.isMine = false; } result.scriptPubKey = Script.BuildLockScipt(address); result.isScript = false; result.script = "P2PKH"; result.hex = null; result.addresses = null; result.pubKey = account.PublicKey; result.isCompressed = false; result.account = account.Tag; result.hdKeyPath = null; result.hdMasterKeyId = null; } else { result.isValid = false; } return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public PersistedAccountData() { SchemaVersion = new SchemaVersion <AccountSchemaChange>(); AccountComponent = new AccountComponent(); AdminComponent = new AdminComponent(); BankComponent = new BankComponent(new List <CurrencyData>()); ExperienceComponent = new ExperienceComponent(); ExperienceComponent.Level = 0; InventoryComponent = new InventoryComponent(); SocialComponent = new SocialComponent(); CharacterData = new Dictionary <CharacterType, PersistedCharacterData>(); AddedMatchData = new List <PersistedCharacterMatchData>(); QuestComponent = new QuestComponent(); }
/// <summary> /// 分类获取账号,1:所有找零账户,2:所有创建账户,3:所有观察者账户,0或者其他:所有账户信息 /// </summary> /// <param name="category"></param> /// <returns></returns> public IRpcMethodResult GetAccountCategory(int category) { try { List <Account> result = new AccountComponent().GetAccountCategory(category); result.ForEach(x => x.PrivateKey = null); return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public static AccountComponent GetAccountComponent(ClientConnection connection) { AccountComponent accountComponent = new AccountComponent() { LastCharacter = connection.SelectedCharacter, LastRemoteCharacters = new List <CharacterType>(), UIStates = new Dictionary <AccountComponent.UIStateIdentifier, int> { { AccountComponent.UIStateIdentifier.HasViewedFluxHighlight, 1 }, { AccountComponent.UIStateIdentifier.HasViewedGGHighlight, 1 } }, UnlockedTitleIDs = GetUnlockedTitleIDs(connection.AccountId), UnlockedBannerIDs = GetUnlockedTitleIDs(connection.AccountId), UnlockedEmojiIDs = GetUnlockedTitleIDs(connection.AccountId), UnlockedOverconIDs = GetUnlockedTitleIDs(connection.AccountId), }; return(accountComponent); }
public IRpcMethodResult GetAddressInfo(string accountId) { try { AccountComponent component = new AccountComponent(); var result = component.GetAccountInfo(accountId); return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult AddWatchOnlyAddress(string publickey) { try { AccountComponent component = new AccountComponent(); Account result = component.GenerateWatchOnlyAddress(publickey); return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public static AccountComponent GetAccountComponent(LobbyServerConnection connection) { //TODO this looks awful AccountComponent accountComponent = new AccountComponent() { //LastCharacter = connection.PlayerInfo.GetCharacterType(), LastRemoteCharacters = new List <CharacterType>(), UIStates = new Dictionary <AccountComponent.UIStateIdentifier, int> { { AccountComponent.UIStateIdentifier.HasViewedFluxHighlight, 1 }, { AccountComponent.UIStateIdentifier.HasViewedGGHighlight, 1 } }, //UnlockedTitleIDs = GetUnlockedTitleIDs(connection.PlayerInfo.GetAccountId()), //UnlockedBannerIDs = GetUnlockedTitleIDs(connection.PlayerInfo.GetAccountId()), //UnlockedEmojiIDs = GetUnlockedTitleIDs(connection.PlayerInfo.GetAccountId()), //UnlockedOverconIDs = GetUnlockedTitleIDs(connection.PlayerInfo.GetAccountId()), }; return(accountComponent); }
/// <summary> /// /// </summary> /// <returns></returns> public IRpcMethodResult ExportAddresses() { try { AccountComponent component = new AccountComponent(); List <Account> accounts = component.GetAllAccounts(); var list = accounts.Select(q => new { Id = q.Id, PublicKey = q.PublicKey }); return(Ok(Newtonsoft.Json.JsonConvert.SerializeObject(list))); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
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(); }
public IRpcMethodResult GetDefaultAccount() { try { var component = new UserSettingComponent(); var id = component.GetDefaultAccount(); var accountComponent = new AccountComponent(); Account account = null; if (string.IsNullOrEmpty(id)) { account = accountComponent.GetAccountById(id); } else { account = accountComponent.GetDefaultAccount(); } if (account != null) { var 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)); } else { throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult GetPageAccountCategory(int category, int pageSize = 0, int pageCount = int.MaxValue, bool isSimple = true) { try { var accountCompent = new AccountComponent(); List <Account> result = accountCompent.GetAllAccounts();; switch (category) { case 1: result = result.Where(x => x.IsDefault).ToList(); break; case 2: result = result.Where(x => !x.IsDefault).ToList(); break; case 3: result = result.Where(x => string.IsNullOrEmpty(x.PrivateKey)).ToList(); break; default: break; } var accounts = result.OrderBy(x => x.Id).Skip(pageSize * pageCount).Take(pageCount); if (isSimple) { return(Ok(new { Count = result.Count.ToString(), Accounts = accounts.Select(x => new { x.Id, x.Tag }) })); } else { return(Ok(new { Count = result.Count.ToString(), Accounts = accounts })); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
/// <summary> /// 锁定未花费的输出 /// </summary> /// <param name="isLocked">true为已锁定,false为未锁定</param> /// <param name="transaction">需要锁定的交易</param> /// <returns></returns> public IRpcMethodResult LockUnspent(bool isLocked, ListLockUnspentOM[] transaction) { try { /* 1、把输入的参数用个静态变量存储起来 * 2、当转账或其他交易的时候先判断是否在静态变量中存在,如果存在就跳过, * 3、注意修改对应的转账接口 */ //根据Transaction的txid和vout获取outputList的ReceivedId TransactionComponent component = new TransactionComponent(); AccountComponent account = new AccountComponent(); List <string> accountIdList = AccountDac.Default.GetAccountBook(); foreach (var item in transaction) { string receivedId = component.GetUtxoSetByIndexAndTxHash(item.txid, item.vout)?.Account; //只锁定自己的账户 if (accountIdList.Contains(receivedId)) { if (isLocked) { Startup.lockUnspentList.Add(item); } else { Startup.lockUnspentList.Remove(Startup.lockUnspentList.FirstOrDefault(p => p.txid == item.txid && p.vout == item.vout)); } } } //去除重复数据 Startup.lockUnspentList = Startup.lockUnspentList.GroupBy(p => new { p.txid, p.vout }).Select(q => q.First()).ToList(); return(Ok(isLocked)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public async Task <ActionResult> FbPsw(FindBackPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { SecurityVerify.Verify <FbPswEmailVerification>(model.Email.Replace("@", "_"), null, model.Code); } catch (ApplicationException ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } catch (Exception) { ModelState.AddModelError("", GeneralResource.SaveFailed); return(View(model)); } var accountComponent = new AccountComponent(); var account = await accountComponent.GetAccountByEmailAsync(model.Email); if (account == null) { ModelState.AddModelError("", AccountFbPsw.EmailNotBind); return(View(model)); } if (account.Status != (byte)AccountStatus.Active) { ViewBag.PasswordHasSet = -1; return(View(model)); } await accountComponent.ResetPasswordAsync(account.Id, PasswordHasher.HashPassword(model.Password)); ViewBag.PasswordHasSet = 1; return(View(model)); }
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); } } } }
public IRpcMethodResult DumpPrivKey(string address) { try { var account = new AccountComponent().GetAccountById(address); if (account != null) { return(Ok(this.decryptPrivateKey(account.PrivateKey))); } else { return(Ok()); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
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(); }
public IRpcMethodResult ListTransactions(string account, int count, int skip = 0, bool includeWatchOnly = true) { try { var txComponent = new TransactionComponent(); var accountComponent = new AccountComponent(); var addressBookComponent = new AddressBookComponent(); var utxoComponent = new UtxoComponent(); var blockComponent = new BlockComponent(); var transactionCommentComponent = new TransactionCommentComponent(); List <PaymentOM> result = new List <PaymentOM>(); var accounts = accountComponent.GetAllAccounts(); var paymentAccountIds = accounts.Where(a => !string.IsNullOrWhiteSpace(a.PrivateKey)).Select(a => a.Id).ToList(); var allAccountIds = accounts.Select(a => a.Id).ToList(); var addressBook = addressBookComponent.GetWholeAddressBook(); var latestHeight = blockComponent.GetLatestHeight(); var data = txComponent.SearchTransactionEntities(account, count, skip, includeWatchOnly); foreach (var tx in data) { long totalInput = 0; long selfTotalOutput = 0; long otherUserTotalOutput = 0; bool coibase = false; if (tx.Inputs.Count == 1 && tx.Outputs.Count == 1 && tx.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash())) { coibase = true; } if (!coibase) { foreach (var input in tx.Inputs) { var oldOutput = txComponent.GetOutputEntiyByIndexAndTxHash(input.OutputTransactionHash, input.OutputIndex); if (oldOutput != null && paymentAccountIds.Contains(oldOutput.ReceiverId)) { totalInput += input.Amount; } else { totalInput = 0; break; } } } foreach (var output in tx.Outputs) { if (allAccountIds.Contains(output.ReceiverId)) { selfTotalOutput += output.Amount; } else { otherUserTotalOutput += output.Amount; } } BlockMsg block = null; if (tx.BlockHash != null) { block = blockComponent.GetBlockMsgByHash(tx.BlockHash); } if (coibase) { var payment = new PaymentOM(); payment.address = tx.Outputs[0].ReceiverId; payment.account = accounts.Where(a => a.Id == payment.address).Select(a => a.Tag).FirstOrDefault(); payment.category = "generate"; payment.totalInput = totalInput; payment.totalOutput = selfTotalOutput; payment.amount = selfTotalOutput; payment.fee = 0; payment.txId = tx.Hash; payment.vout = 0; payment.time = tx.Timestamp; payment.size = tx.Size; var txComment = transactionCommentComponent.GetByTransactionHashAndIndex(tx.Hash, 0); if (txComment != null) { payment.comment = txComment.Comment; } if (block != null) { payment.blockHash = tx.BlockHash; payment.blockIndex = 0;// block.Transactions.FindIndex(t=>t.Hash == tx.Hash); payment.blockTime = block.Header.Timestamp; payment.confirmations = latestHeight - block.Header.Height + 1; } else { payment.confirmations = 0; } result.Add(payment); } else if (totalInput > 0 && otherUserTotalOutput == 0) { var payment = new PaymentOM(); payment.address = null; payment.account = null; payment.category = "self"; payment.totalInput = totalInput; payment.totalOutput = tx.Outputs[0].Amount;// selfTotalOutput; payment.fee = totalInput - selfTotalOutput; payment.amount = payment.fee; payment.txId = tx.Hash; payment.vout = 0; payment.time = tx.Timestamp; payment.size = tx.Size; var txComments = transactionCommentComponent.GetByTransactionHash(tx.Hash); if (txComments.Count > 0) { payment.comment = ""; foreach (var item in txComments) { if (!string.IsNullOrWhiteSpace(item.Comment)) { payment.comment += item.Comment + ";"; } } } if (block != null) { payment.blockHash = tx.BlockHash; payment.blockIndex = block.Transactions.FindIndex(t => t.Hash == tx.Hash); payment.blockTime = block.Header.Timestamp; payment.confirmations = latestHeight - block.Header.Height + 1; } else { payment.confirmations = 0; } result.Add(payment); } else if (totalInput > 0) { for (int i = 0; i < tx.Outputs.Count; i++) { if (!allAccountIds.Contains(tx.Outputs[i].ReceiverId)) { var payment = new PaymentOM(); payment.address = tx.Outputs[i].ReceiverId; payment.account = addressBook.Where(a => a.Address == payment.address && !string.IsNullOrWhiteSpace(a.Tag)).Select(a => a.Tag).FirstOrDefault(); payment.category = "send"; payment.totalInput = totalInput; payment.totalOutput = tx.Outputs[i].Amount; payment.fee = totalInput - (selfTotalOutput + otherUserTotalOutput); payment.amount = (i == 0 ? tx.Outputs[i].Amount + payment.fee : tx.Outputs[i].Amount); payment.txId = tx.Hash; payment.vout = i; payment.time = tx.Timestamp; payment.size = tx.Size; var txComment = transactionCommentComponent.GetByTransactionHashAndIndex(tx.Hash, i); if (txComment != null) { payment.comment = txComment.Comment; } if (block != null) { payment.blockHash = tx.BlockHash; payment.blockIndex = block.Transactions.FindIndex(t => t.Hash == tx.Hash); payment.blockTime = block.Header.Timestamp; payment.confirmations = latestHeight - block.Header.Height + 1; } else { payment.confirmations = 0; } result.Add(payment); } } } else { for (int i = 0; i < tx.Outputs.Count; i++) { if (allAccountIds.Contains(tx.Outputs[i].ReceiverId)) { var payment = new PaymentOM(); payment.address = tx.Outputs[i].ReceiverId; payment.account = accounts.Where(a => a.Id == payment.address).Select(a => a.Tag).FirstOrDefault();; payment.category = "receive"; payment.totalInput = totalInput; payment.totalOutput = tx.Outputs[i].Amount; payment.fee = totalInput - (selfTotalOutput + otherUserTotalOutput); payment.amount = tx.Outputs[i].Amount; payment.txId = tx.Hash; payment.vout = i; payment.time = tx.Timestamp; payment.size = tx.Size; var txComment = transactionCommentComponent.GetByTransactionHashAndIndex(tx.Hash, i); if (txComment != null) { payment.comment = txComment.Comment; } if (block != null) { payment.blockHash = tx.BlockHash; payment.blockIndex = block.Transactions.FindIndex(t => t.Hash == tx.Hash); payment.blockTime = block.Header.Timestamp; payment.confirmations = latestHeight - block.Header.Height + 1; } else { payment.confirmations = 0; } result.Add(payment); } } } } return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult EstimateTxFeeForSendToAddress(string toAddress, long amount, string comment, string commentTo, bool deductFeeFromAmount) { try { EstimateTxFeeOM result = new EstimateTxFeeOM(); var utxoComponent = new UtxoComponent(); var txComponent = new TransactionComponent(); var settingComponent = new SettingComponent(); var addressBookComponent = new AddressBookComponent(); var accountComponent = new AccountComponent(); if (!AccountIdHelper.AddressVerify(toAddress)) { throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID); } var setting = settingComponent.GetSetting(); var utxos = utxoComponent.GetAllConfirmedOutputs(); var tx = new TransactionMsg(); var totalSize = tx.Serialize().Length; var output = new OutputMsg(); output.Amount = amount; output.Index = 0; output.LockScript = Script.BuildLockScipt(toAddress); output.Size = output.LockScript.Length; tx.Outputs.Add(output); totalSize += output.Serialize().Length; var blockComponent = new BlockComponent(); var lastBlockHeight = blockComponent.GetLatestHeight(); var totalInput = 0L; var index = 0; double totalAmount = amount; double totalFee = setting.FeePerKB * ((double)totalSize / 1024.0); 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 (!deductFeeFromAmount) { totalAmount = amount + totalFee; } if (totalInput >= (long)Math.Ceiling(totalAmount)) { var size = output.Serialize().Length; if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0)) { totalSize += size; totalFee += setting.FeePerKB * ((double)size / 1024.0); } break; } index++; } if (totalInput < totalAmount) { throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH); } if (deductFeeFromAmount) { output.Amount -= (long)Math.Ceiling(totalFee); if (output.Amount <= 0) { throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE); } } result.totalFee = Convert.ToInt64(totalFee); result.totalSize = Convert.ToInt32(totalSize); return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
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)); } }