public AccountCheck(string name, string pw, AccountState state, WebProxy proxy) { Username = name; Password = pw; State = state; Proxy = proxy; }
public void CheckAccount() { if (!_actualInfos.Contains("#1")) return; var infos = _actualInfos.Split('#'); var username = infos[0]; var password = infos[1]; var requestedAccount = Entities.Requests.AccountsRequests.LoadAccount(username); if (requestedAccount != null && Utilities.Basic.Encrypt(requestedAccount.Password, _key) == password) { Account = requestedAccount; Utilities.Loggers.InfosLogger.Write(string.Format("Client {0} authentified !", Account.Pseudo)); _state = AccountState.OnServersList; SendInformations(); } else { Send("AlEx"); this.Disconnect(); } }
public RedState(AccountState state) { Balance = state.Balance; Account = state.Account; upperLimit = 5000.0; }
public AccountTable(string username) { if (BannedIPs.Count == 0 && !LoadedIPs) { string[] lines = File.ReadAllLines(ServerBase.Constants.BannedPath); foreach (string line in lines) { if (line.Length >= 7) { BannedIPs.Add(line.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)[0]); } } LoadedIPs = true; } this.Username = username; this.Password = ""; this.IP = ""; this.LastCheck = DateTime.Now; this.State = AccountState.DoesntExist; this.EntityID = 0; MySqlCommand cmd = new MySqlCommand(MySqlCommandType.SELECT); cmd.Select("accounts").Where("Username", username); MySqlReader r = new MySqlReader(cmd); if (r.Read()) { exists = true; this.Password = r.ReadString("Password"); this.IP = r.ReadString("IP"); this.EntityID = r.ReadUInt32("EntityID"); this.LastCheck = DateTime.FromBinary(r.ReadInt64("LastCheck")); this.State = (AccountState)r.ReadByte("State"); this.Email = r.ReadString("Email"); } r.Close(); }
public GoldState(AccountState state) { Balance = state.Balance; Account = state.Account; //upperLimit = 5000.0; lowerLimit = 5000.0; }
public void UpdateAccountStateProperties(int requiredConfirmations, AccountState state) { RaisePropertyChanged(nameof(TotalBalance)); SpendableBalance = _wallet.CalculateSpendableBalance(_account, requiredConfirmations); ExternalAddressCount = state.ExternalKeyCount; InternalAddressCount = state.InternalKeyCount; ImportedAddressCount = state.ImportedKeyCount; }
public AccountInfo() { this.publicKey = new Hash(); this.money = 0; this.name = ""; this.accountState = AccountState.Normal; this.networkType = NetworkType.MainNet; this.accountType = AccountType.MainNormal; this.lastTransactionTime = 0; }
public Player(string id, string type, AccountState account) : base(type, id) { Scale = Settings.Scale; Tag = Tags.Player; AccState = account; Hp = new Stat(BaseHp); AttackDamage = BaseAd; Speed = BaseSpeed; AttackCooldownCounter = 0; AttackCooldown = 0.2f; }
public AccountInfo(Hash publicKey, long money) { this.publicKey = publicKey; this.money = money; this.name = ""; this.accountState = AccountState.Normal; this.networkType = NetworkType.MainNet; this.accountType = AccountType.MainNormal; this.lastTransactionTime = 0; updateInternalHash(); }
private void ShowState(AccountState state) { TableRow row = new TableRow(); TableHeaderCell cell = new TableHeaderCell(); cell.Width = new Unit(30, UnitType.Percentage); cell.Text = StringDef.AccountState; row.Cells.Add(cell); TableCell cell1 = new TableCell(); cell1.Text = state.ToString(); row.Cells.Add(cell1); TableResult.Rows.Add(row); }
public AccountInfo(Hash publicKey, long money, string name, AccountState accountState, NetworkType networkType, AccountType accountType, long lastTransactionTime) { if (!Utils.ValidateUserName(name)) throw new ArgumentException("Usernames should be lowercase and alphanumeric, _ is allowed"); this.publicKey = publicKey; this.money = money; this.name = name; this.accountState = accountState; this.networkType = networkType; this.accountType = accountType; this.lastTransactionTime = lastTransactionTime; updateInternalHash(); }
public void LoadDetailsFromDatabase(IDatabase database) { Dictionary<string, dynamic> obj; if (Id != 0) obj = database.ExecuteReader("SELECT * FROM accounts WHERE account_id=" + Id).ToDictionary(); else if (Name != null) obj = database.ExecuteReader("SELECT * FROM accounts WHERE username='******'").ToDictionary(); else throw new Exception("Id == 0 && Username == null"); if (obj.Count == 0) throw new Exception("obj.Count == 0"); Id = (UInt32) obj["account_id"]; Name = obj["username"]; Type = (AccountType) obj["type"]; State = (AccountState) obj["state"]; }
internal AcSessionState(IAcDomain acDomain, Guid sessionId, AccountState account) : this(acDomain) { if (account == null) { throw new ArgumentNullException("account"); } if (account == AccountState.Empty) { Identity = new UnauthenticatedIdentity(); } else { Identity = new AnycmdIdentity(account.LoginName); } _acDomain = acDomain; _id = sessionId; _account = account; _accountId = account.Id; }
public AccountTable(string username) { this.Username = username; this.Password = ""; this.IP = ""; this.LastCheck = DateTime.Now; this.State = AccountState.DoesntExist; this.EntityID = 0; MySqlCommand cmd = new MySqlCommand(MySqlCommandType.SELECT); cmd.Select("accounts").Where("Username", username); MySqlReader r = new MySqlReader(cmd); if (r.Read()) { exists = true; this.Password = r.ReadString("Password"); this.IP = r.ReadString("IP"); this.EntityID = r.ReadUInt32("EntityID"); this.LastCheck = DateTime.FromBinary(r.ReadInt64("LastCheck")); this.State = (AccountState)r.ReadByte("State"); this.Email = r.ReadString("Email"); } r.Close(); r.Dispose(); }
private void AddAccount(AccountState account) { DataClient.Upsert(CouchbaseConfigManager.Instance.AccountBucketName, account); }
private void Persist(Block block) { WriteBatch batch = new WriteBatch(); DbCache <UInt160, AccountState> accounts = new DbCache <UInt160, AccountState>(db, DataEntryPrefix.ST_Account); DbCache <UInt256, UnspentCoinState> unspentcoins = new DbCache <UInt256, UnspentCoinState>(db, DataEntryPrefix.ST_Coin); DbCache <UInt256, SpentCoinState> spentcoins = new DbCache <UInt256, SpentCoinState>(db, DataEntryPrefix.ST_SpentCoin); DbCache <ECPoint, ValidatorState> validators = new DbCache <ECPoint, ValidatorState>(db, DataEntryPrefix.ST_Validator); DbCache <UInt256, AssetState> assets = new DbCache <UInt256, AssetState>(db, DataEntryPrefix.ST_Asset); DbCache <UInt160, ContractState> contracts = new DbCache <UInt160, ContractState>(db, DataEntryPrefix.ST_Contract); DbCache <StorageKey, StorageItem> storages = new DbCache <StorageKey, StorageItem>(db, DataEntryPrefix.ST_Storage); long amount_sysfee = GetSysFeeAmount(block.PrevHash) + (long)block.Transactions.Sum(p => p.SystemFee); batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim())); foreach (Transaction tx in block.Transactions) { batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Index).Add(tx.ToArray())); unspentcoins.Add(tx.Hash, new UnspentCoinState { Items = Enumerable.Repeat(CoinState.Confirmed, tx.Outputs.Length).ToArray() }); foreach (TransactionOutput output in tx.Outputs) { AccountState account = accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash)); if (account.Balances.ContainsKey(output.AssetId)) { account.Balances[output.AssetId] += output.Value; } else { account.Balances[output.AssetId] = output.Value; } } foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash)) { int height; Transaction tx_prev = GetTransaction(ReadOptions.Default, group.Key, out height); foreach (CoinReference input in group) { unspentcoins.GetAndChange(input.PrevHash).Items[input.PrevIndex] |= CoinState.Spent; if (tx_prev.Outputs[input.PrevIndex].AssetId.Equals(GoverningToken.Hash)) { spentcoins.GetAndChange(input.PrevHash, () => new SpentCoinState { TransactionHash = input.PrevHash, TransactionHeight = (uint)height, Items = new Dictionary <ushort, uint>() }).Items.Add(input.PrevIndex, block.Index); } accounts.GetAndChange(tx_prev.Outputs[input.PrevIndex].ScriptHash).Balances[tx_prev.Outputs[input.PrevIndex].AssetId] -= tx_prev.Outputs[input.PrevIndex].Value; } } switch (tx.Type) { case TransactionType.RegisterTransaction: { #pragma warning disable CS0612 RegisterTransaction rtx = (RegisterTransaction)tx; assets.Add(tx.Hash, new AssetState { AssetId = rtx.Hash, AssetType = rtx.AssetType, Name = rtx.Name, Amount = rtx.Amount, Available = Fixed8.Zero, Precision = rtx.Precision, Fee = Fixed8.Zero, FeeAddress = new UInt160(), Owner = rtx.Owner, Admin = rtx.Admin, Issuer = rtx.Admin, Expiration = block.Index + 2 * 2000000, IsFrozen = false }); #pragma warning restore CS0612 } break; case TransactionType.IssueTransaction: foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero)) { assets.GetAndChange(result.AssetId).Available -= result.Amount; } break; case TransactionType.ClaimTransaction: foreach (CoinReference input in ((ClaimTransaction)tx).Claims) { if (spentcoins.TryGet(input.PrevHash)?.Items.Remove(input.PrevIndex) == true) { spentcoins.GetAndChange(input.PrevHash); } } break; case TransactionType.EnrollmentTransaction: { #pragma warning disable CS0612 EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx; validators.GetOrAdd(enroll_tx.PublicKey, () => new ValidatorState { PublicKey = enroll_tx.PublicKey }); #pragma warning restore CS0612 } break; case TransactionType.PublishTransaction: { #pragma warning disable CS0612 PublishTransaction publish_tx = (PublishTransaction)tx; contracts.GetOrAdd(publish_tx.ScriptHash, () => new ContractState { Script = publish_tx.Script, ParameterList = publish_tx.ParameterList, ReturnType = publish_tx.ReturnType, HasStorage = publish_tx.NeedStorage, Name = publish_tx.Name, CodeVersion = publish_tx.CodeVersion, Author = publish_tx.Author, Email = publish_tx.Email, Description = publish_tx.Description }); #pragma warning restore CS0612 } break; case TransactionType.InvocationTransaction: { InvocationTransaction itx = (InvocationTransaction)tx; CachedScriptTable script_table = new CachedScriptTable(contracts); StateMachine service = new StateMachine(accounts, validators, assets, contracts, storages); ApplicationEngine engine = new ApplicationEngine(TriggerType.Application, itx, script_table, service, itx.Gas); engine.LoadScript(itx.Script, false); if (engine.Execute()) { service.Commit(); if (service.Notifications.Count > 0) { OnNotify(service.Notifications.ToArray()); } } } break; } } accounts.DeleteWhere((k, v) => !v.IsFrozen && v.Votes.Length == 0 && v.Balances.All(p => p.Value <= Fixed8.Zero)); accounts.Commit(batch); unspentcoins.DeleteWhere((k, v) => v.Items.All(p => p.HasFlag(CoinState.Spent))); unspentcoins.Commit(batch); spentcoins.DeleteWhere((k, v) => v.Items.Count == 0); spentcoins.Commit(batch); validators.Commit(batch); assets.Commit(batch); contracts.Commit(batch); storages.Commit(batch); batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Index)); db.Write(WriteOptions.Default, batch); current_block_height = block.Index; }
/// <summary> /// Closes this account. /// </summary> public void ToClose() { this.state = AccountState.closed; }
public IEnumerable <ECPoint> GetValidators(IEnumerable <Transaction> others) { Snapshot snapshot = Clone(); foreach (Transaction tx in others) { foreach (TransactionOutput output in tx.Outputs) { AccountState account = snapshot.Accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash)); if (account.Balances.ContainsKey(output.AssetId)) { account.Balances[output.AssetId] += output.Value; } else { account.Balances[output.AssetId] = output.Value; } if (output.AssetId.Equals(Blockchain.GoverningToken.Hash) && account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) { snapshot.Validators.GetAndChange(pubkey, () => new ValidatorState(pubkey)).Votes += output.Value; } snapshot.ValidatorsCount.GetAndChange().Votes[account.Votes.Length - 1] += output.Value; } } foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash)) { Transaction tx_prev = snapshot.GetTransaction(group.Key); foreach (CoinReference input in group) { TransactionOutput out_prev = tx_prev.Outputs[input.PrevIndex]; AccountState account = snapshot.Accounts.GetAndChange(out_prev.ScriptHash); if (out_prev.AssetId.Equals(Blockchain.GoverningToken.Hash)) { if (account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) { ValidatorState validator = snapshot.Validators.GetAndChange(pubkey); validator.Votes -= out_prev.Value; if (!validator.Registered && validator.Votes.Equals(Fixed8.Zero)) { snapshot.Validators.Delete(pubkey); } } snapshot.ValidatorsCount.GetAndChange().Votes[account.Votes.Length - 1] -= out_prev.Value; } } account.Balances[out_prev.AssetId] -= out_prev.Value; } } switch (tx) { #pragma warning disable CS0612 case EnrollmentTransaction tx_enrollment: snapshot.Validators.GetAndChange(tx_enrollment.PublicKey, () => new ValidatorState(tx_enrollment.PublicKey)).Registered = true; break; #pragma warning restore CS0612 case StateTransaction tx_state: foreach (StateDescriptor descriptor in tx_state.Descriptors) { switch (descriptor.Type) { case StateType.Account: Blockchain.ProcessAccountStateDescriptor(descriptor, snapshot); break; case StateType.Validator: Blockchain.ProcessValidatorStateDescriptor(descriptor, snapshot); break; } } break; } } int count = (int)snapshot.ValidatorsCount.Get().Votes.Select((p, i) => new { Count = i, Votes = p }).Where(p => p.Votes > Fixed8.Zero).ToArray().WeightedFilter(0.25, 0.75, p => p.Votes.GetData(), (p, w) => new { p.Count, Weight = w }).WeightedAverage(p => p.Count, p => p.Weight); count = Math.Max(count, Blockchain.StandbyValidators.Length); HashSet <ECPoint> sv = new HashSet <ECPoint>(Blockchain.StandbyValidators); ECPoint[] pubkeys = snapshot.Validators.Find().Select(p => p.Value).Where(p => (p.Registered && p.Votes > Fixed8.Zero) || sv.Contains(p.PublicKey)).OrderByDescending(p => p.Votes).ThenBy(p => p.PublicKey).Select(p => p.PublicKey).Take(count).ToArray(); IEnumerable <ECPoint> result; if (pubkeys.Length == count) { result = pubkeys; } else { HashSet <ECPoint> hashSet = new HashSet <ECPoint>(pubkeys); for (int i = 0; i < Blockchain.StandbyValidators.Length && hashSet.Count < count; i++) { hashSet.Add(Blockchain.StandbyValidators[i]); } result = hashSet; } return(result.OrderBy(p => p)); }
private void ParseVersionPacket(string datas) { if (datas.Contains(Utilities.Config.GetStringElement("LOGIN_VERSION"))) State = AccountState.OnCheckingAccount; else { Send(string.Concat("AlEv", Utilities.Config.GetStringElement("LOGIN_VERSION"))); this.Disconnect(); } }
private void ParseVersionPacket(string datas) { if (datas.Contains(Utilities.Config.GetStringElement("Login_Version"))) { if (AuthQueue.GetClients.Count >= Utilities.Config.GetIntElement("Max_Clients_inQueue")) { Send("M00\0"); this.Disconnect(); } else { _state = AccountState.OnCheckingQueue; AuthQueue.AddinQueue(this); } } else { Send(string.Format("AlEv{0}", Utilities.Config.GetStringElement("Login_Version"))); this.Disconnect(); } }
private JObject Process(string method, JArray _params) { switch (method) { case "unlock": if (wallet == null) { return("wallet is null."); } if (_params.Count < 2) { return("parameter is error."); } string password = _params[0].AsString(); int duration = (int)_params[1].AsNumber(); bool ok = walletTimeLock.UnLock(password, duration); string result = ok ? "successfully" : "failed"; return($"Wallet unlocked {result}."); case "dumpprivkey": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { UInt160 scriptHash = _params[0].AsString().ToScriptHash(); WalletAccount account = wallet.GetAccount(scriptHash); return(account.GetKey().Export()); } case "getaccountstate": { UInt160 script_hash = _params[0].AsString().ToScriptHash(); AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(script_hash) ?? new AccountState(script_hash); return(account.ToJson()); } case "getassetstate": { UInt256 asset_id = UInt256.Parse(_params[0].AsString()); AssetState asset = Blockchain.Singleton.Store.GetAssets().TryGet(asset_id); return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset")); } case "getbalance": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { JObject json = new JObject(); switch (UIntBase.Parse(_params[0].AsString())) { case UInt160 asset_id_160: //BRC5 balance json["balance"] = wallet.GetAvailable(asset_id_160).ToString(); break; case UInt256 asset_id_256: //Global Assets balance IEnumerable <Coin> coins = wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256)); json["balance"] = coins.Sum(p => p.Output.Value).ToString(); json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString(); break; } return(json); } case "getbestblockhash": return(Blockchain.Singleton.CurrentBlockHash.ToString()); case "getblock": { Block block; if (_params[0] is JNumber) { uint index = (uint)_params[0].AsNumber(); block = Blockchain.Singleton.Store.GetBlock(index); } else { UInt256 hash = UInt256.Parse(_params[0].AsString()); block = Blockchain.Singleton.Store.GetBlock(hash); } if (block == null) { throw new RpcException(-100, "Unknown block"); } bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); if (verbose) { JObject json = block.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - block.Index + 1; UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(block.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(json); } return(block.ToArray().ToHexString()); } case "getblockcount": return(Blockchain.Singleton.Height + 1); case "getblockhash": { uint height = (uint)_params[0].AsNumber(); if (height <= Blockchain.Singleton.Height) { return(Blockchain.Singleton.GetBlockHash(height).ToString()); } throw new RpcException(-100, "Invalid Height"); } case "getblockheader": { Header header; if (_params[0] is JNumber) { uint height = (uint)_params[0].AsNumber(); header = Blockchain.Singleton.Store.GetHeader(height); } else { UInt256 hash = UInt256.Parse(_params[0].AsString()); header = Blockchain.Singleton.Store.GetHeader(hash); } if (header == null) { throw new RpcException(-100, "Unknown block"); } bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); if (verbose) { JObject json = header.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1; UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(header.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(json); } return(header.ToArray().ToHexString()); } case "getblocksysfee": { uint height = (uint)_params[0].AsNumber(); if (height <= Blockchain.Singleton.Height) { return(Blockchain.Singleton.Store.GetSysFeeAmount(height).ToString()); } throw new RpcException(-100, "Invalid Height"); } case "getconnectioncount": return(LocalNode.Singleton.ConnectedCount); case "getcontractstate": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractState contract = Blockchain.Singleton.Store.GetContracts().TryGet(script_hash); return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract")); } case "getnewaddress": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { WalletAccount account = wallet.CreateAccount(); if (wallet is BRC6Wallet BRC6) { BRC6.Save(); } return(account.Address); } case "getpeers": { JObject json = new JObject(); json["unconnected"] = new JArray(LocalNode.Singleton.GetUnconnectedPeers().Select(p => { JObject peerJson = new JObject(); peerJson["address"] = p.Address.ToString(); peerJson["port"] = p.Port; return(peerJson); })); json["bad"] = new JArray(); //badpeers has been removed json["connected"] = new JArray(LocalNode.Singleton.GetRemoteNodes().Select(p => { JObject peerJson = new JObject(); peerJson["address"] = p.Remote.Address.ToString(); peerJson["port"] = p.ListenerPort; return(peerJson); })); return(json); } case "getrawmempool": return(new JArray(Blockchain.Singleton.GetMemoryPool().Select(p => (JObject)p.Hash.ToString()))); case "getrawtransaction": { UInt256 hash = UInt256.Parse(_params[0].AsString()); bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); Transaction tx = Blockchain.Singleton.GetTransaction(hash); if (tx == null) { throw new RpcException(-100, "Unknown transaction"); } if (verbose) { JObject json = tx.ToJson(); uint? height = Blockchain.Singleton.Store.GetTransactions().TryGet(hash)?.BlockIndex; if (height != null) { Header header = Blockchain.Singleton.Store.GetHeader((uint)height); json["blockhash"] = header.Hash.ToString(); json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1; json["blocktime"] = header.Timestamp; } return(json); } return(tx.ToArray().ToHexString()); } case "getstorage": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); byte[] key = _params[1].AsString().HexToBytes(); StorageItem item = Blockchain.Singleton.Store.GetStorages().TryGet(new StorageKey { ScriptHash = script_hash, Key = key }) ?? new StorageItem(); return(item.Value?.ToHexString()); } case "gettxout": { UInt256 hash = UInt256.Parse(_params[0].AsString()); ushort index = (ushort)_params[1].AsNumber(); return(Blockchain.Singleton.Store.GetUnspent(hash, index)?.ToJson(index)); } case "createaddress": { byte[] privateKey = new byte[32]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(privateKey); KeyPair key = new KeyPair(privateKey); byte[] pubkey = Contract.CreateSignatureRedeemScript(key.PublicKey); JObject json = new JObject(); json["address"] = pubkey.ToScriptHash().ToAddress(); json["pubkey"] = key.PublicKey.EncodePoint(true).ToHexString(); json["prikey"] = key.PrivateKey.ToHexString(); json["wif"] = key.Export(); json["script"] = pubkey.ToHexString(); return(json); } } case "getutxos": { UInt160 script_hash = _params[0].AsString().ToScriptHash(); AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(script_hash) ?? new AccountState(script_hash); return(account.ToJson()); } case "getvalidators": using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot()) { var validators = snapshot.GetValidators(); return(snapshot.GetEnrollments().Select(p => { JObject validator = new JObject(); validator["publickey"] = p.PublicKey.ToString(); validator["votes"] = p.Votes.ToString(); validator["active"] = validators.Contains(p.PublicKey); return validator; }).ToArray()); } case "getversion": { JObject json = new JObject(); json["port"] = LocalNode.Singleton.ListenerPort; json["nonce"] = LocalNode.Nonce; json["useragent"] = LocalNode.UserAgent; return(json); } case "getwalletheight": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { return((wallet.WalletHeight > 0) ? wallet.WalletHeight - 1 : 0); } case "invoke": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractParameter[] parameters = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray(); byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, parameters).ToArray(); } return(GetInvokeResult(script)); } case "invokefunction": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); string operation = _params[1].AsString(); ContractParameter[] args = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0]; byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, operation, args).ToArray(); } return(GetInvokeResult(script)); } case "invokescript": { byte[] script = _params[0].AsString().HexToBytes(); return(GetInvokeResult(script)); } case "listaddress": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { return(wallet.GetAccounts().Select(p => { JObject account = new JObject(); account["address"] = p.Address; account["haskey"] = p.HasKey; account["label"] = p.Label; account["watchonly"] = p.WatchOnly; return account; }).ToArray()); } case "sendfrom": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { UIntBase assetId = UIntBase.Parse(_params[0].AsString()); AssetDescriptor descriptor = new AssetDescriptor(assetId); UInt160 from = _params[1].AsString().ToScriptHash(); UInt160 to = _params[2].AsString().ToScriptHash(); BigDecimal value = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals); if (value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 6 ? _params[5].AsString().ToScriptHash() : null; string remark = _params.Count >= 7 ? _params[6].AsString() : null; Transaction tx = wallet.MakeTransaction(null, new[] { new TransferOutput { AssetId = assetId, Value = value, ScriptHash = to } }, from: from, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } AddRemak(remark, tx); ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "transfer": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { UIntBase assetId = UIntBase.Parse(_params[0].AsString()); AssetDescriptor descriptor = new AssetDescriptor(assetId); UInt160 from = _params[1].AsString().ToScriptHash(); UInt160 to = _params[2].AsString().ToScriptHash(); BigDecimal value = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals); if (value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 6 ? _params[5].AsString().ToScriptHash() : from; string remark = _params.Count >= 7 ? _params[6].AsString() : null; Transaction tx = wallet.MakeTransaction(null, new[] { new TransferOutput { AssetId = assetId, Value = value, ScriptHash = to } }, from: from, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } AddRemak(remark, tx); ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "sendmany": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { JArray to = (JArray)_params[0]; if (to.Count == 0) { throw new RpcException(-32602, "Invalid params"); } TransferOutput[] outputs = new TransferOutput[to.Count]; for (int i = 0; i < to.Count; i++) { UIntBase asset_id = UIntBase.Parse(to[i]["asset"].AsString()); AssetDescriptor descriptor = new AssetDescriptor(asset_id); outputs[i] = new TransferOutput { AssetId = asset_id, Value = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals), ScriptHash = to[i]["address"].AsString().ToScriptHash() }; if (outputs[i].Value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } } Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 3 ? _params[2].AsString().ToScriptHash() : null; string remark = _params.Count >= 4 ? _params[3].AsString() : null; Transaction tx = wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } AddRemak(remark, tx); ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "sendrawtransaction": { Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes()); RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result; return(GetRelayResult(reason)); } case "sendtoaddress": if (wallet == null || walletTimeLock.IsLocked()) { throw new RpcException(-400, "wallet is null or locked."); } else { UIntBase assetId = UIntBase.Parse(_params[0].AsString()); AssetDescriptor descriptor = new AssetDescriptor(assetId); UInt160 scriptHash = _params[1].AsString().ToScriptHash(); BigDecimal value = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals); if (value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 5 ? _params[4].AsString().ToScriptHash() : null; string remark = _params.Count >= 6 ? _params[5].AsString() : null; Transaction tx = wallet.MakeTransaction(null, new[] { new TransferOutput { AssetId = assetId, Value = value, ScriptHash = scriptHash } }, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } AddRemak(remark, tx); ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "submitblock": { Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>(); RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(block).Result; return(GetRelayResult(reason)); } case "validateaddress": { JObject json = new JObject(); UInt160 scriptHash; try { scriptHash = _params[0].AsString().ToScriptHash(); } catch { scriptHash = null; } json["address"] = _params[0]; json["isvalid"] = scriptHash != null; return(json); } /* * case "backupwallet": * if (wallet == null || walletTimeLock.IsLocked()) * throw new RpcException(-400, "wallet is null or locked."); * else * { * return BackupWallet(); * } * * case "backupwallettosqlite": * if (wallet == null) * throw new RpcException(-400, "Access denied"); * else * { * try * { * string path = ((Bhp.Wallets.BRC6.BRC6Wallet)wallet).Path; * string WalletName = _params.Count >= 1 ? _params[0].AsString().Trim() : path.Substring(path.LastIndexOf("\\") + 1).Trim(); * * int nIndex = WalletName.LastIndexOf('.'); * if (nIndex >= 0) * { * WalletName = WalletName.Substring(0, nIndex).Trim(); * } * else * { * WalletName = WalletName.Trim(); * } * return "Backup Wallet Success! Name:" + SQLiteOperateForBackupWallet.BackupWalletToSQLite(WifToList(), WalletName); * } * catch (Exception ex) * { * throw new Exception(ex.ToString()); * //throw new RpcException(-401, "SQLite Exception"); * } * } * * case "recoverwalletfromsqlite": * if (wallet == null) * throw new RpcException(-400, "Access denied"); * else * { * if (_params.Count == 0) * { * return "Please Input BackupWalletName"; * } * string BackWalletName = _params[0].AsString().Trim(); * //System.IO.Path.GetExtension(BackWalletName) * * string FileName = "";//不含后缀 * int nIndex = BackWalletName.LastIndexOf('.'); * if (nIndex >= 0) * { * FileName = BackWalletName.Substring(0, nIndex) + ".sqlite"; * } * else * { * FileName = BackWalletName + ".sqlite"; * } * List<string> wifs = SQLiteOperateForBackupWallet.RecoverWalletFromSQLite(FileName); * foreach (string wif in wifs) * { * WalletAccount account; * try * { * account = wallet.Import(wif); * } * catch (FormatException) * { * continue; * } * } * if (wallet is BRC6Wallet walletBrc6) * walletBrc6.Save(); * return "Recover Wallet Success"; * } * * case "closewallet": * if (wallet == null) * throw new RpcException(-400, "Access denied"); * else * { * if (wallet is IDisposable disposable) * { * disposable.Dispose(); * wallet = null; * } * return "Close Wallet Success"; * } */ default: throw new RpcException(-32601, "Method not found"); } }
public AccountBalanceMustNotBeNegative(AccountState accountState) { this.accountState = accountState; }
public IActionResult GetContractInfo([FromQuery] string txHash) { try { uint256 txHashNum = new uint256(txHash); Receipt receipt = this.receiptRepository.Retrieve(txHashNum); if (receipt == null) { return(null); } uint160 address = receipt.NewContractAddress ?? receipt.To; string typeName = null; byte[] contractCode = null; uint256 codeHash = null; string csharpCode = null; ulong balance = 0; if (address != null) { IStateRepositoryRoot stateAtHeight = this.stateRoot.GetSnapshotTo(receipt.PostState.ToBytes()); AccountState accountState = stateAtHeight.GetAccountState(address); if (accountState != null) { typeName = accountState.TypeName; balance = stateAtHeight.GetCurrentBalance(address); if (receipt.NewContractAddress != null) { codeHash = new uint256(accountState.CodeHash); contractCode = this.stateRoot.GetCode(receipt.NewContractAddress); Result <string> sourceResult = this.contractDecompiler.GetSource(contractCode); csharpCode = sourceResult.IsSuccess ? sourceResult.Value : sourceResult.Error; } } else { typeName = this.stateRoot.GetAccountState(address)?.TypeName; } } List <LogResponse> logResponses = new List <LogResponse>(); if (receipt.Logs.Any()) { var deserializer = new ApiLogDeserializer(this.primitiveSerializer, this.network, this.stateRoot, this.contractAssemblyCache); logResponses = deserializer.MapLogResponses(receipt.Logs); } var logEnrichment = contractEnrichmentFactory.GetLogEnrichment(typeName); logEnrichment?.EnrichLogs(receipt, logResponses); return(this.Json(new ContractReceiptResponse(receipt, logResponses, this.network) { ContractCodeType = typeName, ContractBalance = balance, ContractCodeHash = codeHash?.ToString(), ContractBytecode = contractCode?.ToHexString(), ContractCSharp = csharpCode })); } catch (Exception e) { this.logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
public AUTH_LOGON_PROOF(AccountState accountState) => AccountState = accountState;
internal AsyncEvent(AccountState accountState) : this(NotificationManager.AsyncEventType.AccountTerminated) { this.accountState = accountState; }
// Overloaded constructors public GoldState(AccountState state) : this(state.Balance, state.Account) { }
public InterestAccountState(AccountState accountState) : this(accountState.Balance, accountState.Account) { }
public void SetState(AccountState state) { this.state = state; }
public AccountState PutAccountState(int AccountStateId, AccountState AccountState) { return(AccountState); }
public void ChangeStatus(AccountState TheState) { this.AccountStatus = TheState; }
private void Persist(Block block) { WriteBatch batch = new WriteBatch(); DbCache <UInt160, AccountState> accounts = new DbCache <UInt160, AccountState>(db, DataEntryPrefix.ST_Account, batch); DbCache <UInt256, UnspentCoinState> unspentcoins = new DbCache <UInt256, UnspentCoinState>(db, DataEntryPrefix.ST_Coin, batch); DbCache <UInt256, SpentCoinState> spentcoins = new DbCache <UInt256, SpentCoinState>(db, DataEntryPrefix.ST_SpentCoin, batch); DbCache <ECPoint, ValidatorState> validators = new DbCache <ECPoint, ValidatorState>(db, DataEntryPrefix.ST_Validator, batch); DbCache <UInt256, AssetState> assets = new DbCache <UInt256, AssetState>(db, DataEntryPrefix.ST_Asset, batch); DbCache <UInt160, ContractState> contracts = new DbCache <UInt160, ContractState>(db, DataEntryPrefix.ST_Contract, batch); DbCache <StorageKey, StorageItem> storages = new DbCache <StorageKey, StorageItem>(db, DataEntryPrefix.ST_Storage, batch); DbMetaDataCache <ValidatorsCountState> validators_count = new DbMetaDataCache <ValidatorsCountState>(db, DataEntryPrefix.IX_ValidatorsCount); CachedScriptTable script_table = new CachedScriptTable(contracts); long amount_sysfee = GetSysFeeAmount(block.PrevHash) + (long)block.Transactions.Sum(p => p.SystemFee); batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim())); foreach (Transaction tx in block.Transactions) { batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Index).Add(tx.ToArray())); unspentcoins.Add(tx.Hash, new UnspentCoinState { Items = Enumerable.Repeat(CoinState.Confirmed, tx.Outputs.Length).ToArray() }); foreach (TransactionOutput output in tx.Outputs) { AccountState account = accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash)); if (account.Balances.ContainsKey(output.AssetId)) { account.Balances[output.AssetId] += output.Value; } else { account.Balances[output.AssetId] = output.Value; } if (output.AssetId.Equals(GoverningToken.Hash) && account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) { validators.GetAndChange(pubkey, () => new ValidatorState(pubkey)).Votes += output.Value; } validators_count.GetAndChange().Votes[account.Votes.Length - 1] += output.Value; } } foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash)) { Transaction tx_prev = GetTransaction(ReadOptions.Default, group.Key, out int height); foreach (CoinReference input in group) { unspentcoins.GetAndChange(input.PrevHash).Items[input.PrevIndex] |= CoinState.Spent; TransactionOutput out_prev = tx_prev.Outputs[input.PrevIndex]; AccountState account = accounts.GetAndChange(out_prev.ScriptHash); if (out_prev.AssetId.Equals(GoverningToken.Hash)) { spentcoins.GetAndChange(input.PrevHash, () => new SpentCoinState { TransactionHash = input.PrevHash, TransactionHeight = (uint)height, Items = new Dictionary <ushort, uint>() }).Items.Add(input.PrevIndex, block.Index); if (account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) { ValidatorState validator = validators.GetAndChange(pubkey); validator.Votes -= out_prev.Value; if (!validator.Registered && validator.Votes.Equals(Fixed8.Zero)) { validators.Delete(pubkey); } } validators_count.GetAndChange().Votes[account.Votes.Length - 1] -= out_prev.Value; } } account.Balances[out_prev.AssetId] -= out_prev.Value; } } List <ApplicationExecutionResult> execution_results = new List <ApplicationExecutionResult>(); switch (tx) { #pragma warning disable CS0612 case RegisterTransaction tx_register: assets.Add(tx.Hash, new AssetState { AssetId = tx_register.Hash, AssetType = tx_register.AssetType, Name = tx_register.Name, Amount = tx_register.Amount, Available = Fixed8.Zero, Precision = tx_register.Precision, Fee = Fixed8.Zero, FeeAddress = new UInt160(), Owner = tx_register.Owner, Admin = tx_register.Admin, Issuer = tx_register.Admin, Expiration = block.Index + 2 * 2000000, IsFrozen = false }); break; #pragma warning restore CS0612 case IssueTransaction _: foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero)) { assets.GetAndChange(result.AssetId).Available -= result.Amount; } break; case ClaimTransaction _: foreach (CoinReference input in ((ClaimTransaction)tx).Claims) { if (spentcoins.TryGet(input.PrevHash)?.Items.Remove(input.PrevIndex) == true) { spentcoins.GetAndChange(input.PrevHash); } } break; #pragma warning disable CS0612 case EnrollmentTransaction tx_enrollment: validators.GetAndChange(tx_enrollment.PublicKey, () => new ValidatorState(tx_enrollment.PublicKey)).Registered = true; break; #pragma warning restore CS0612 case StateTransaction tx_state: foreach (StateDescriptor descriptor in tx_state.Descriptors) { switch (descriptor.Type) { case StateType.Account: ProcessAccountStateDescriptor(descriptor, accounts, validators, validators_count); break; case StateType.Validator: ProcessValidatorStateDescriptor(descriptor, validators); break; } } break; #pragma warning disable CS0612 case PublishTransaction tx_publish: contracts.GetOrAdd(tx_publish.ScriptHash, () => new ContractState { Script = tx_publish.Script, ParameterList = tx_publish.ParameterList, ReturnType = tx_publish.ReturnType, ContractProperties = (ContractPropertyState)Convert.ToByte(tx_publish.NeedStorage), Name = tx_publish.Name, CodeVersion = tx_publish.CodeVersion, Author = tx_publish.Author, Email = tx_publish.Email, Description = tx_publish.Description }); break; #pragma warning restore CS0612 case InvocationTransaction tx_invocation: using (StateMachine service = new StateMachine(block, accounts, assets, contracts, storages)) { ApplicationEngine engine = new ApplicationEngine(TriggerType.Application, tx_invocation, script_table, service, tx_invocation.Gas); engine.LoadScript(tx_invocation.Script); if (engine.Execute()) { service.Commit(); } execution_results.Add(new ApplicationExecutionResult { Trigger = TriggerType.Application, ScriptHash = tx_invocation.Script.ToScriptHash(), VMState = engine.State, GasConsumed = engine.GasConsumed, Stack = engine.ResultStack.ToArray(), Notifications = service.Notifications.ToArray() }); } break; } if (execution_results.Count > 0) { ApplicationExecuted?.Invoke(this, new ApplicationExecutedEventArgs { Transaction = tx, ExecutionResults = execution_results.ToArray() }); } } accounts.DeleteWhere((k, v) => !v.IsFrozen && v.Votes.Length == 0 && v.Balances.All(p => p.Value <= Fixed8.Zero)); accounts.Commit(); unspentcoins.DeleteWhere((k, v) => v.Items.All(p => p.HasFlag(CoinState.Spent))); unspentcoins.Commit(); spentcoins.DeleteWhere((k, v) => v.Items.Count == 0); spentcoins.Commit(); validators.Commit(); assets.Commit(); contracts.Commit(); storages.Commit(); validators_count.Commit(batch); batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Index)); db.Write(WriteOptions.Default, batch); current_block_height = block.Index; }
public void SetState(AccountState state, bool announce, object data) { if (this.State != state) { AccountState previousState = this.State; this.State = state; if (announce && AccountStateChanged != null) AccountStateChanged(this.Settings.UID, state, previousState, data); } }
private AccountState GetAccountState(int userid) { lock (m_Accounts) { if (!m_Accounts.ContainsKey(userid)) { m_Accounts[userid] = new AccountState(userid); } return m_Accounts[userid] as AccountState; } }
public NormalState(AccountState state) { this.Account = state.Account; }
public void UpdateAccountProperties(Account account, string name, uint externalKeyCount, uint internalKeyCount, uint importedKeyCount) { AccountState stats; if (!_accounts.TryGetValue(account, out stats)) { stats = new AccountState(); _accounts[account] = stats; } stats.AccountName = name; stats.ExternalKeyCount = externalKeyCount; stats.InternalKeyCount = internalKeyCount; stats.ImportedKeyCount = importedKeyCount; var eventArgs = new ChangesProcessedEventArgs(); eventArgs.ModifiedAccountStates[account] = stats; OnChangesProcessed(eventArgs); }
// Constructor public RedState(AccountState state) { this.balance = state.Balance; this.account = state.Account; Initialize(); }
/// <summary> /// Actives this account. /// </summary> public void ToActive() { this.state = AccountState.active; }
public void TestSetup() { uut = new AccountState(); }
/// <summary> /// Freezes this account. /// </summary> public void ToFreeze() { this.state = AccountState.freezed; }
public void SetState(AccountState state, bool announce) { SetState(state, announce, null); }
public static Option <AccountState> Debit(this AccountState account, decimal amount) => (account.Balance < amount) ? None : Some(new AccountState(account.Balance - amount));
public void Deserialize(byte[] Data) { List<ProtocolDataType> PDTs = ProtocolPackager.UnPackRaw(Data); int cnt = 0; while (cnt < (int)PDTs.Count) { ProtocolDataType PDT = PDTs[cnt++]; switch (PDT.NameType) { case 0: ProtocolPackager.UnpackHash(PDT, 0, out publicKey); break; case 1: ProtocolPackager.UnpackInt64(PDT, 1, ref money); break; case 2: ProtocolPackager.UnpackString(PDT, 2, ref name); break; case 3: byte _accountState = 0; ProtocolPackager.UnpackByte(PDT, 3, ref _accountState); accountState = (AccountState)_accountState; break; case 4: byte _networkType = 0; ProtocolPackager.UnpackByte(PDT, 4, ref _networkType); networkType = (NetworkType)_networkType; break; case 5: byte _accountType = 0; ProtocolPackager.UnpackByte(PDT, 5, ref _accountType); accountType = (AccountType)_accountType; break; case 6: ProtocolPackager.UnpackInt64(PDT, 6, ref lastTransactionTime); break; } } updateInternalHash(); }
protected virtual JObject Process(string method, JArray _params) { switch (method) { case "getaccountstate": { UInt160 script_hash = Wallet.ToScriptHash(_params[0].AsString()); AccountState account = Blockchain.Default.GetAccountState(script_hash) ?? new AccountState(script_hash); return(account.ToJson()); } case "getassetstate": { UInt256 asset_id = UInt256.Parse(_params[0].AsString()); AssetState asset = Blockchain.Default.GetAssetState(asset_id); return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset")); } case "getbestblockhash": return(Blockchain.Default.CurrentBlockHash.ToString()); case "getblock": { Block block; if (_params[0] is JNumber) { uint index = (uint)_params[0].AsNumber(); block = Blockchain.Default.GetBlock(index); } else { UInt256 hash = UInt256.Parse(_params[0].AsString()); block = Blockchain.Default.GetBlock(hash); } if (block == null) { throw new RpcException(-100, "Unknown block"); } bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); if (verbose) { JObject json = block.ToJson(); json["confirmations"] = Blockchain.Default.Height - block.Index + 1; UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(json); } else { return(block.ToArray().ToHexString()); } } case "getblockcount": return(Blockchain.Default.Height + 1); case "getblockhash": { uint height = (uint)_params[0].AsNumber(); if (height >= 0 && height <= Blockchain.Default.Height) { return(Blockchain.Default.GetBlockHash(height).ToString()); } else { throw new RpcException(-100, "Invalid Height"); } } case "getblocksysfee": { uint height = (uint)_params[0].AsNumber(); if (height >= 0 && height <= Blockchain.Default.Height) { return(Blockchain.Default.GetSysFeeAmount(height).ToString()); } else { throw new RpcException(-100, "Invalid Height"); } } case "getconnectioncount": return(LocalNode.RemoteNodeCount); case "getcontractstate": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractState contract = Blockchain.Default.GetContract(script_hash); return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract")); } case "getrawmempool": return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString()))); case "getrawtransaction": { UInt256 hash = UInt256.Parse(_params[0].AsString()); bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); int height = -1; Transaction tx = LocalNode.GetTransaction(hash); if (tx == null) { tx = Blockchain.Default.GetTransaction(hash, out height); } if (tx == null) { throw new RpcException(-100, "Unknown transaction"); } if (verbose) { JObject json = tx.ToJson(); if (height >= 0) { Header header = Blockchain.Default.GetHeader((uint)height); json["blockhash"] = header.Hash.ToString(); json["confirmations"] = Blockchain.Default.Height - header.Index + 1; json["blocktime"] = header.Timestamp; } return(json); } else { return(tx.ToArray().ToHexString()); } } case "getstorage": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); byte[] key = _params[1].AsString().HexToBytes(); StorageItem item = Blockchain.Default.GetStorageItem(new StorageKey { ScriptHash = script_hash, Key = key }) ?? new StorageItem(); return(item.Value?.ToHexString()); } case "gettxout": { UInt256 hash = UInt256.Parse(_params[0].AsString()); ushort index = (ushort)_params[1].AsNumber(); return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index)); } case "getvalidators": { var validators = Blockchain.Default.GetValidators(); return(Blockchain.Default.GetEnrollments().Select(p => { JObject validator = new JObject(); validator["publickey"] = p.PublicKey.ToString(); validator["votes"] = p.Votes.ToString(); validator["active"] = validators.Contains(p.PublicKey); return validator; }).ToArray()); } case "invoke": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractParameter[] parameters = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray(); byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, parameters).ToArray(); } return(GetInvokeResult(script)); } case "invokefunction": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); string operation = _params[1].AsString(); ContractParameter[] args = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0]; byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, operation, args).ToArray(); } return(GetInvokeResult(script)); } case "invokescript": { byte[] script = _params[0].AsString().HexToBytes(); return(GetInvokeResult(script)); } case "sendrawtransaction": { Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes()); return(LocalNode.Relay(tx)); } case "submitblock": { Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>(); return(LocalNode.Relay(block)); } case "validateaddress": { JObject json = new JObject(); UInt160 scriptHash; try { scriptHash = Wallet.ToScriptHash(_params[0].AsString()); } catch { scriptHash = null; } json["address"] = _params[0]; json["isvalid"] = scriptHash != null; return(json); } case "getpeers": { JObject json = new JObject(); { JArray unconnectedPeers = new JArray(); foreach (IPEndPoint peer in LocalNode.GetUnconnectedPeers()) { JObject peerJson = new JObject(); peerJson["address"] = peer.Address.ToString(); peerJson["port"] = peer.Port; unconnectedPeers.Add(peerJson); } json["unconnected"] = unconnectedPeers; } { JArray badPeers = new JArray(); foreach (IPEndPoint peer in LocalNode.GetBadPeers()) { JObject peerJson = new JObject(); peerJson["address"] = peer.Address.ToString(); peerJson["port"] = peer.Port; badPeers.Add(peerJson); } json["bad"] = badPeers; } { JArray connectedPeers = new JArray(); foreach (RemoteNode node in LocalNode.GetRemoteNodes()) { JObject peerJson = new JObject(); peerJson["address"] = node.RemoteEndpoint.Address.ToString(); peerJson["port"] = node.ListenerEndpoint?.Port ?? 0; connectedPeers.Add(peerJson); } json["connected"] = connectedPeers; } return(json); } case "getversion": { JObject json = new JObject(); json["port"] = LocalNode.Port; json["nonce"] = LocalNode.Nonce; json["useragent"] = LocalNode.UserAgent; return(json); } case "createwallet": { JObject json = new JObject(); return(json); } default: throw new RpcException(-32601, "Method not found"); } }
private AppState Reducer(AppState state, object action) { BaseState tmpBaseState = (action) as BaseState; switch (tmpBaseState.userOpCode) { case UserOpCodeEnum.None: break; case UserOpCodeEnum.Close: HelperWidgets.PopRoute(tmpBaseState.Context); break; case UserOpCodeEnum.GoToLoginPage: HelperWidgets.PushNewRoute(tmpBaseState.Context, new LoginPage.LoginPage()); break; case UserOpCodeEnum.GoToRegisterPage: HelperWidgets.PushNewRoute(tmpBaseState.Context, new RegisterPage()); break; case UserOpCodeEnum.SendVerfyCode: CountdownState tmpCountdownState = ((CountdownState)action); state.CountdownTime = tmpCountdownState.CountdownTime; break; case UserOpCodeEnum.TypingAccount: AccountState tmpAccountState = ((AccountState)action); state.Account = tmpAccountState.InputResult; break; case UserOpCodeEnum.TypingPassword: PasswordState tmpPasswordState = ((PasswordState)action); state.Password = tmpPasswordState.InputResult; break; case UserOpCodeEnum.TypingNickName: SetNickNameState tmpSetNickNameState = ((SetNickNameState)action); state.NickName = tmpSetNickNameState.InputResult; break; case UserOpCodeEnum.TypingVerfyCode: SetVerfyCodeState tmpSetVerfyCodeState = ((SetVerfyCodeState)action); state.VerfyCode = tmpSetVerfyCodeState.InputResult; break; case UserOpCodeEnum.SetupAvatar: SetRegisterAvatarState tmpSetRegisterAvatarState = ((SetRegisterAvatarState)action); state.RegisterAvatar = tmpSetRegisterAvatarState.InputResult; break; default: throw new ArgumentOutOfRangeException(); } switch (tmpBaseState.RequestResult) { case RequestResultEnum.None: break; case RequestResultEnum.LoginSuccessed: HelperWidgets.PopRoute(tmpBaseState.Context); HelperWidgets.PopRoute(tmpBaseState.Context); HelperWidgets.PushNewRoute(tmpBaseState.Context, new MainPage()); break; case RequestResultEnum.LoginFailed: state.FialedMsg = ((LoginState)action).FailedMsg; break; case RequestResultEnum.VerfyCodeSuccessed: break; case RequestResultEnum.VerfyCodeFailed: break; case RequestResultEnum.RegisterSuccessed: break; case RequestResultEnum.RegisterFailed: break; default: throw new ArgumentOutOfRangeException(); } return(state); }
public JS_AccountReply(AccountInfo accountInfo) { PublicKey = accountInfo.PublicKey.Hex; Money = accountInfo.Money; Name = accountInfo.Name; Address = accountInfo.GetAddress(); NetworkType = accountInfo.NetworkType; AccountType = accountInfo.AccountType; AccountState = accountInfo.AccountState; LastTransactionTime = accountInfo.LastTransactionTime; }
public void PostAccountState(AccountState AccountState) { unitOfWork.AccountStateRepository.Insert(AccountState); unitOfWork.Save(); }
// TODO: сделать в конструкторе /** AccState - если создается игрок, ему передается для связывания... (что плохо :( )*/ public void AddEntity(EntityState es, AccountState accState = null) { Entity entity = null; /* Получаем название объекта по изображению */ string textureName = es.TextureName; textureName = textureName.Replace("\\", "/").Split('/').Last(); /** TODO: можно ли вынести куда-нибудь? можно ли обойтись без этого? скорее всего в Resources, через словарь */ switch (textureName) { case Resources.ClassMystic: case Resources.ClassReaper: case Resources.ClassSniper: entity = new Player(es.Id, textureName, accState); break; case Resources.ItemGold: entity = new GoldStack(es.Id); break; case Resources.ItemGate: entity = new Gate(es.Id); break; case Resources.ItemHealpot: entity = new HealPot(es.Id); break; case Resources.ObjectSmith: entity = new Smith(es.Id); break; case Resources.ProjectileMystic: entity = new MysticProjectile(es.AttackDamage, es.Id); break; case Resources.ProjectileLaser: case Resources.ProjectileCardinalPulse: case Resources.ProjectileCardinalRocket: entity = new EnemyRangeProjectile(es.AttackDamage, textureName, es.Id); break; case Resources.ParticleMeleeSweepAttack: entity = new EnemyMeleeProjectile(es.AttackDamage, textureName, es.Id); break; case Resources.ParticleMeleeSweepStart: entity = new EnemyMeleeProjectileStart(es.AttackDamage, textureName, es.Id); break; case Resources.EnemyMeleeRobot: case Resources.EnemyMagicMelee: case Resources.EnemyPirate: entity = new MeleeEnemy(textureName, es.Id); break; case Resources.EnemyStinger: case Resources.EnemyMagicRange: entity = new RangeEnemy(textureName, es.Id); break; case Resources.BossEmperor: entity = new Emperor(es.Id); break; case Resources.BossCardinal: entity = new Cardinal(es.Id); break; case Resources.BossInteritus: entity = new Interitus(es.Id); break; case Resources.BossMossorus: entity = new Mossorus(es.Id); break; } if (entity != null) { EntityState.AppendStateToEntity(entity, es); AddEntity(entity); } else { Log.Print("Error! Entity isn't created, New entity will not be added. " + textureName, LogType.Error); } }
/** Вызывается на клиенте для обновления текущего состояния игры */ public void AppendGameState(GameState gs, string playerId) { /** Updating entities */ foreach (EntityState entity in gs.Entities.ToList()) { int index = Entities.FindIndex(x => x.Id == entity.Id); if (index != -1) { // У себя обновляем все, кроме местоположения if (entity.Id != playerId) { Entities[index].AppendState(entity); } else { // Наш персонаж CCPoint pos = Entities[index].Position; Entities[index].AppendState(entity); Entities[index].Position = pos; } } else { AddEntity(entity); } } /** Проверяем, если у нас есть на сцене объект, которого нет в новом состоянии - убираем его*/ foreach (Entity entity in Entities.ToList()) { if (gs.Entities.FindIndex(x => x.Id == entity.Id) == -1) { entity.Remove(); } } /** обновляем состояние аккаунта */ if (gs.Account != null && gs.Account.HeroId == playerId) { MyAccountState = gs.Account; } }
protected override void OnBalanceChanging(ApplicationEngine engine, UInt160 account, AccountState state, BigInteger amount) { DistributeGas(engine, account, state); if (amount.IsZero) { return; } if (state.Votes.Length == 0) { return; } foreach (ECPoint pubkey in state.Votes) { StorageItem storage_validator = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Validator, pubkey.ToArray())); ValidatorState state_validator = ValidatorState.FromByteArray(storage_validator.Value); state_validator.Votes += amount; storage_validator.Value = state_validator.ToByteArray(); } StorageItem storage_count = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_ValidatorsCount)); ValidatorsCountState state_count = ValidatorsCountState.FromByteArray(storage_count.Value); state_count.Votes[state.Votes.Length - 1] += amount; storage_count.Value = state_count.ToByteArray(); }
public ThisIsMyInfo(AccountState info) { this.Info = info; }
public IAcSession CreateSession(IAcSession subject, Guid sessionId, AccountState account) { var identity = new AnycmdIdentity(account.LoginName); var acSessionEntity = new AcSession { Id = sessionId, AccountId = account.Id, AuthenticationType = identity.AuthenticationType, Description = null, IsAuthenticated = identity.IsAuthenticated, IsEnabled = 1, LoginName = account.LoginName }; AcSessionState.AcMethod.AddAcSession(_acDomain, acSessionEntity); return new AcSessionState(_acDomain, sessionId, account); }
public void OnPersist(Snapshot snapshot, IReadOnlyList <Blockchain.ApplicationExecuted> applicationExecutedList) { // Console.WriteLine("OnPersist"); // Console.WriteLine("Settings.Default.Conn {0}", Settings.Default.Conn); //Console.WriteLine("OnPersist snapshot.PersistingBlock.Index index {0}", snapshot.PersistingBlock.Index); if (snapshot.PersistingBlock.Index == 0) { return; } //Console.WriteLine("11"); UInt256 hash = Blockchain.Singleton.GetBlockHash(snapshot.PersistingBlock.Index - 1); if (hash == null) { return; } var mIndex = GetMongoIndex(); // Console.WriteLine("OnPersist mIndex {0}", mIndex); if (snapshot.PersistingBlock.Index - 1 < mIndex) { return; } var block = Blockchain.Singleton.GetBlock(hash); // Console.WriteLine("OnPersist block index {0}", block.Index); // Console.WriteLine("this.settings: {0}", Settings.Default.Conn); /* * var block = snapshot.PersistingBlock; * Console.WriteLine("OnPersist block index {0}", block.ToJson()); * * if (block.Index == 0) * { * SaveMongo("0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b", * "AQVh2pG732YvtNaxEGkQUei3YA4cvo7d2i", decimal.Parse("100000000")); * } * */ foreach (Transaction tx in block.Transactions) { // Console.WriteLine("OnPersist Transaction {0}", tx.ToJson()); foreach (CoinReference vin in tx.Inputs) { // Console.WriteLine("OnPersist CoinReference vin {0}", vin.ToJson()); // OnPersist CoinReference vin {"txid":"0xc800cae5063ccb762d727e167911e65ab2aa489eaf5068f09153ea34188bee98","vout":0} // var json = new JObject(); // json = vin.ToJson(); // Console.WriteLine("OnPersist CoinReference vout {0} vin.PrevHash", vin.PrevHash); // Console.WriteLine("OnPersist CoinReference vout {0} vin.PrevIndex", vin.PrevIndex); var transactionState = snapshot.Transactions.TryGet(vin.PrevHash); // Console.WriteLine("OnPersist CoinReference vin transactionState {0}", transactionState.Transaction.Outputs[vin.PrevIndex]); // Console.WriteLine("OnPersist CoinReference vin transactionState {0}", transactionState.Transaction.Outputs[vin.PrevIndex].AssetId); // var utxo = transactionState.Transaction.Outputs[vin.PrevIndex]; // //json["utxo"] = utxo.ToJson(vin.PrevIndex); // Console.WriteLine("OnPersist CoinReference vin utxo {0}", utxo.ToJson()); AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(utxo.ScriptHash) ?? new AccountState(utxo.ScriptHash); // Console.WriteLine("OnPersist vin {0}", account.ToJson()); foreach (var b in account.Balances) { if (b.Key == utxo.AssetId) { SaveMongo(b.Key.ToString(), utxo.ScriptHash.ToAddress(), decimal.Parse(b.Value.ToString())); } } // Console.WriteLine("OnPersist vin account {0}", account.ToJson()); // OnPersist CoinReference vin {"txid":"0x6137e84e65b302eea351e76dc602e17c0417ba7920cc8a8303987f72a7004654","vout":0,"utxo":{"n":0,"asset":"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b","value":"19","address":"ALfnhLg7rUyL6Jr98bzzoxz5J7m64fbR4s"}} } // Console.WriteLine("2"); foreach (var vout in tx.Outputs) { // var address = vout.ScriptHash.; AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(vout.ScriptHash); // Console.WriteLine("4:{0}", account.ToJson()); foreach (var b in account.Balances) { if (b.Key == vout.AssetId) { // Console.WriteLine("5:{0}", b.Key); // Console.WriteLine("5:{0}", b.Value); SaveMongo(b.Key.ToString(), vout.ScriptHash.ToAddress(), decimal.Parse(b.Value.ToString())); } } // Console.WriteLine("OnPersist vout account {0}", account.ToJson()); } // Console.WriteLine("3"); foreach (var appExec in applicationExecutedList) { // Console.WriteLine("1"); JObject json = new JObject(); json["executions"] = appExec.ExecutionResults.Select(p => { JObject execution = new JObject(); execution["notifications"] = p.Notifications.Select(q => { JObject notification = new JObject(); try { notification["state"] = q.State.ToParameter().ToJson(); var value = notification["state"]["value"]; if (value is JArray) { var info = ((JArray)value); if (info.Count == 4) { if (info[0]["value"].AsString() == "7472616e73666572") { if (info[1]["type"].AsString() == "ByteArray" && !string.IsNullOrEmpty(info[1]["value"].AsString())) { var address = new UInt160(info[1]["value"].AsString().HexToBytes()) .ToAddress(); var bala = GetBalanceOf(q.ScriptHash.ToString(), info[1]["value"].AsString()); // Console.WriteLine("OnPersist from address {0},{1}", info[1]["value"], // bala); SaveMongo(q.ScriptHash.ToString(), address, bala); } if (info[2]["type"].AsString() == "ByteArray" && !string.IsNullOrEmpty(info[2]["value"].AsString())) { var address = new UInt160(info[2]["value"].AsString().HexToBytes()) .ToAddress(); var bala = GetBalanceOf(q.ScriptHash.ToString(), info[2]["value"].AsString()); // Console.WriteLine("OnPersist to address {0},{1}", info[2]["value"], // bala); SaveMongo(q.ScriptHash.ToString(), address, bala); } } } // } } catch (InvalidOperationException) { } return(notification); }).ToArray(); return(execution); }).ToArray(); } // UpdateMongoIndex(snapshot.PersistingBlock.Index - 1); } }
public void ChangeState(AccountState _newState) { state = _newState; }
private void CheckAccount(string datas) { if (!datas.Contains("#1")) return; var infos = datas.Split('#'); var username = infos[0]; var password = infos[1]; var requestedAccount = Entities.Requests.AccountsRequests.LoadAccount(username); if (requestedAccount != null && Utilities.Basic.Encrypt(requestedAccount.Password, key) == password) { Account = requestedAccount; Utilities.Loggers.Debug.Write(string.Format("Client <{0}> authentified !", Account.Pseudo)); if (AuthQueue.Clients.Count >= Utilities.Config.GetIntElement("MAX_CLIENTS_INQUEUE")) { Send("M00\0"); this.Disconnect(); } else if ((Environment.TickCount - AuthQueue.LastAction) < Utilities.Config.GetIntElement("TIME_BETWEEN_TWOCONNECTIONS")) { State = AccountState.OnCheckingQueue; AuthQueue.AddInQueue(this); SendQueuePacket(); } else { SendInformations(); State = AccountState.OnServersList; } AuthQueue.LastAction = Environment.TickCount; } else { Send("AlEx"); this.Disconnect(); } }
private JObject Process(string method, JArray _params) { switch (method) { case "dumpprivkey": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { UInt160 scriptHash = _params[0].AsString().ToScriptHash(); WalletAccount account = wallet.GetAccount(scriptHash); return(account.GetKey().Export()); } case "getaccountstate": { UInt160 script_hash = _params[0].AsString().ToScriptHash(); AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(script_hash) ?? new AccountState(script_hash); return(account.ToJson()); } case "getassetstate": { UInt256 asset_id = UInt256.Parse(_params[0].AsString()); AssetState asset = Blockchain.Singleton.Store.GetAssets().TryGet(asset_id); return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset")); } case "getbalance": if (wallet == null) { throw new RpcException(-400, "Access denied."); } else { JObject json = new JObject(); switch (UIntBase.Parse(_params[0].AsString())) { case UInt160 asset_id_160: //NEP-5 balance json["balance"] = wallet.GetAvailable(asset_id_160).ToString(); break; case UInt256 asset_id_256: //Global Assets balance IEnumerable <Coin> coins = wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256)); json["balance"] = coins.Sum(p => p.Output.Value).ToString(); json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString(); break; } return(json); } case "getbestblockhash": return(Blockchain.Singleton.CurrentBlockHash.ToString()); case "getblock": { Block block; if (_params[0] is JNumber) { uint index = (uint)_params[0].AsNumber(); block = Blockchain.Singleton.Store.GetBlock(index); } else { UInt256 hash = UInt256.Parse(_params[0].AsString()); block = Blockchain.Singleton.Store.GetBlock(hash); } if (block == null) { throw new RpcException(-100, "Unknown block"); } bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); if (verbose) { JObject json = block.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - block.Index + 1; UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(block.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(json); } return(block.ToArray().ToHexString()); } case "getblockcount": return(Blockchain.Singleton.Height + 1); case "getblockhash": { uint height = (uint)_params[0].AsNumber(); if (height <= Blockchain.Singleton.Height) { return(Blockchain.Singleton.GetBlockHash(height).ToString()); } throw new RpcException(-100, "Invalid Height"); } case "getblockheader": { Header header; if (_params[0] is JNumber) { uint height = (uint)_params[0].AsNumber(); header = Blockchain.Singleton.Store.GetHeader(height); } else { UInt256 hash = UInt256.Parse(_params[0].AsString()); header = Blockchain.Singleton.Store.GetHeader(hash); } if (header == null) { throw new RpcException(-100, "Unknown block"); } bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); if (verbose) { JObject json = header.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1; UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(header.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(json); } return(header.ToArray().ToHexString()); } case "getblocksysfee": { uint height = (uint)_params[0].AsNumber(); if (height <= Blockchain.Singleton.Height) { return(Blockchain.Singleton.Store.GetSysFeeAmount(height).ToString()); } throw new RpcException(-100, "Invalid Height"); } case "getconnectioncount": return(LocalNode.Singleton.ConnectedCount); case "getcontractstate": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractState contract = Blockchain.Singleton.Store.GetContracts().TryGet(script_hash); return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract")); } case "getnewaddress": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { WalletAccount account = wallet.CreateAccount(); if (wallet is TERC1Wallet nep6) { nep6.Save(); } return(account.Address); } case "getpeers": { JObject json = new JObject(); json["unconnected"] = new JArray(LocalNode.Singleton.GetUnconnectedPeers().Select(p => { JObject peerJson = new JObject(); peerJson["address"] = p.Address.ToString(); peerJson["port"] = p.Port; return(peerJson); })); json["bad"] = new JArray(); //badpeers has been removed json["connected"] = new JArray(LocalNode.Singleton.GetRemoteNodes().Select(p => { JObject peerJson = new JObject(); peerJson["address"] = p.Remote.Address.ToString(); peerJson["port"] = p.ListenerPort; return(peerJson); })); return(json); } case "getrawmempool": return(new JArray(Blockchain.Singleton.GetMemoryPool().Select(p => (JObject)p.Hash.ToString()))); case "getrawtransaction": { UInt256 hash = UInt256.Parse(_params[0].AsString()); bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false); Transaction tx = Blockchain.Singleton.GetTransaction(hash); if (tx == null) { throw new RpcException(-100, "Unknown transaction"); } if (verbose) { JObject json = tx.ToJson(); uint? height = Blockchain.Singleton.Store.GetTransactions().TryGet(hash)?.BlockIndex; if (height != null) { Header header = Blockchain.Singleton.Store.GetHeader((uint)height); json["blockhash"] = header.Hash.ToString(); json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1; json["blocktime"] = header.Timestamp; } return(json); } return(tx.ToArray().ToHexString()); } case "getstorage": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); byte[] key = _params[1].AsString().HexToBytes(); StorageItem item = Blockchain.Singleton.Store.GetStorages().TryGet(new StorageKey { ScriptHash = script_hash, Key = key }) ?? new StorageItem(); return(item.Value?.ToHexString()); } case "gettxout": { UInt256 hash = UInt256.Parse(_params[0].AsString()); ushort index = (ushort)_params[1].AsNumber(); return(Blockchain.Singleton.Store.GetUnspent(hash, index)?.ToJson(index)); } case "getvalidators": using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot()) { var validators = snapshot.GetValidators(); return(snapshot.GetEnrollments().Select(p => { JObject validator = new JObject(); validator["publickey"] = p.PublicKey.ToString(); validator["votes"] = p.Votes.ToString(); validator["active"] = validators.Contains(p.PublicKey); return validator; }).ToArray()); } case "getversion": { JObject json = new JObject(); json["port"] = LocalNode.Singleton.ListenerPort; json["nonce"] = LocalNode.Nonce; json["useragent"] = LocalNode.UserAgent; return(json); } case "getwalletheight": if (wallet == null) { throw new RpcException(-400, "Access denied."); } else { return((wallet.WalletHeight > 0) ? wallet.WalletHeight - 1 : 0); } case "invoke": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractParameter[] parameters = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray(); byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, parameters).ToArray(); } return(GetInvokeResult(script)); } case "invokefunction": { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); string operation = _params[1].AsString(); ContractParameter[] args = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0]; byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { script = sb.EmitAppCall(script_hash, operation, args).ToArray(); } return(GetInvokeResult(script)); } case "invokescript": { byte[] script = _params[0].AsString().HexToBytes(); return(GetInvokeResult(script)); } case "listaddress": if (wallet == null) { throw new RpcException(-400, "Access denied."); } else { return(wallet.GetAccounts().Select(p => { JObject account = new JObject(); account["address"] = p.Address; account["haskey"] = p.HasKey; account["label"] = p.Label; account["watchonly"] = p.WatchOnly; return account; }).ToArray()); } case "sendfrom": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { UIntBase assetId = UIntBase.Parse(_params[0].AsString()); AssetDescriptor descriptor = new AssetDescriptor(assetId); UInt160 from = _params[1].AsString().ToScriptHash(); UInt160 to = _params[2].AsString().ToScriptHash(); BigDecimal value = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals); if (value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 6 ? _params[5].AsString().ToScriptHash() : null; Transaction tx = wallet.MakeTransaction(null, new[] { new TransferOutput { AssetId = assetId, Value = value, ScriptHash = to } }, from: from, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "sendmany": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { JArray to = (JArray)_params[0]; if (to.Count == 0) { throw new RpcException(-32602, "Invalid params"); } TransferOutput[] outputs = new TransferOutput[to.Count]; for (int i = 0; i < to.Count; i++) { UIntBase asset_id = UIntBase.Parse(to[i]["asset"].AsString()); AssetDescriptor descriptor = new AssetDescriptor(asset_id); outputs[i] = new TransferOutput { AssetId = asset_id, Value = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals), ScriptHash = to[i]["address"].AsString().ToScriptHash() }; if (outputs[i].Value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } } Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 3 ? _params[2].AsString().ToScriptHash() : null; Transaction tx = wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "sendrawtransaction": { Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes()); RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result; return(GetRelayResult(reason)); } case "sendtoaddress": if (wallet == null) { throw new RpcException(-400, "Access denied"); } else { UIntBase assetId = UIntBase.Parse(_params[0].AsString()); AssetDescriptor descriptor = new AssetDescriptor(assetId); UInt160 scriptHash = _params[1].AsString().ToScriptHash(); BigDecimal value = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals); if (value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero; if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } UInt160 change_address = _params.Count >= 5 ? _params[4].AsString().ToScriptHash() : null; Transaction tx = wallet.MakeTransaction(null, new[] { new TransferOutput { AssetId = assetId, Value = value, ScriptHash = scriptHash } }, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } ContractParametersContext context = new ContractParametersContext(tx); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); wallet.ApplyTransaction(tx); system.LocalNode.Tell(new LocalNode.Relay { Inventory = tx }); return(tx.ToJson()); } else { return(context.ToJson()); } } case "submitblock": { Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>(); RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(block).Result; return(GetRelayResult(reason)); } case "validateaddress": { JObject json = new JObject(); UInt160 scriptHash; try { scriptHash = _params[0].AsString().ToScriptHash(); } catch { scriptHash = null; } json["address"] = _params[0]; json["isvalid"] = scriptHash != null; return(json); } default: throw new RpcException(-32601, "Method not found"); } }
/// <summary> /// 错误处理 /// </summary> /// <param name="lblError">错误标签</param> /// <param name="strError">错误信息</param> /// <param name="txtFocus">错误的文本框</param> private void DoWellError(Label lblError, AccountState state, TextBox txtFocus) { string strError = String.Empty; strError = ShineKJ.Model.Power.Account.GetEnumValue.GetDescription((ShineKJ.Model.Power.Account.AccountState)state); lblError.Text = strError; txtPassword.Text = ""; txtFocus.Focus(); }
public void ChangeState(AccountState state) { throw new NotImplementedException(); }