private static ImmutableHashSet <UInt160> UpdateExtensibleWitnessWhiteList(ProtocolSettings settings, DataCache snapshot) { uint currentHeight = NativeContract.Ledger.CurrentIndex(snapshot); var builder = ImmutableHashSet.CreateBuilder <UInt160>(); builder.Add(NativeContract.NEO.GetCommitteeAddress(snapshot)); var validators = NativeContract.NEO.GetNextBlockValidators(snapshot, settings.ValidatorsCount); builder.Add(Contract.GetBFTAddress(validators)); builder.UnionWith(validators.Select(u => Contract.CreateSignatureRedeemScript(u).ToScriptHash())); var oracles = NativeContract.RoleManagement.GetDesignatedByRole(snapshot, Role.Oracle, currentHeight); if (oracles.Length > 0) { builder.Add(Contract.GetBFTAddress(oracles)); builder.UnionWith(oracles.Select(u => Contract.CreateSignatureRedeemScript(u).ToScriptHash())); } var stateValidators = NativeContract.RoleManagement.GetDesignatedByRole(snapshot, Role.StateValidator, currentHeight); if (stateValidators.Length > 0) { builder.Add(Contract.GetBFTAddress(stateValidators)); builder.UnionWith(stateValidators.Select(u => Contract.CreateSignatureRedeemScript(u).ToScriptHash())); } return(builder.ToImmutable()); }
static bool TryGetNEP6Wallet(string path, string password, ProtocolSettings settings, [MaybeNullWhen(false)] out Wallet wallet, [MaybeNullWhen(false)] out UInt160 accountHash) { try { var nep6wallet = new Neo.Wallets.NEP6.NEP6Wallet(path, settings); using var unlock = nep6wallet.Unlock(password); var nep6account = nep6wallet.GetAccounts().SingleOrDefault(a => a.IsDefault) ?? nep6wallet.GetAccounts().SingleOrDefault() ?? throw new InvalidOperationException("Neo-express only supports NEP-6 wallets with a single default account or a single account"); if (nep6account.IsMultiSigContract()) { throw new Exception("Neo-express doesn't supports multi-sig NEP-6 accounts"); } var keyPair = nep6account.GetKey() ?? throw new Exception("account.GetKey() returned null"); wallet = new DevWallet(settings, string.Empty); var account = wallet.CreateAccount(keyPair.PrivateKey); accountHash = account.ScriptHash; return(true); } catch { wallet = null; accountHash = null; return(false); } }
/// <summary> /// Initializes a new instance of the <see cref="AssetDescriptor"/> class. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="settings">The <see cref="ProtocolSettings"/> used by the <see cref="ApplicationEngine"/>.</param> /// <param name="asset_id">The id of the asset.</param> public AssetDescriptor(DataCache snapshot, ProtocolSettings settings, UInt160 asset_id) { var contract = NativeContract.ContractManagement.GetContract(snapshot, asset_id); if (contract is null) { throw new ArgumentException(null, nameof(asset_id)); } byte[] script; using (ScriptBuilder sb = new()) { sb.EmitDynamicCall(asset_id, "decimals", CallFlags.ReadOnly); sb.EmitDynamicCall(asset_id, "symbol", CallFlags.ReadOnly); script = sb.ToArray(); } using ApplicationEngine engine = ApplicationEngine.Run(script, snapshot, settings: settings, valt: 0_10000000); if (engine.State != VMState.HALT) { throw new ArgumentException(null, nameof(asset_id)); } this.AssetId = asset_id; this.AssetName = contract.Manifest.Name; this.Symbol = engine.ResultStack.Pop().GetString(); this.Decimals = (byte)engine.ResultStack.Pop().GetInteger(); }
public OnlineNode(ProtocolSettings settings, ExpressChain chain, ExpressConsensusNode node) { this.ProtocolSettings = settings; this.chain = chain; rpcClient = new RpcClient(new Uri($"http://localhost:{node.RpcPort}"), protocolSettings: settings); consensusNodesKeys = new Lazy <KeyPair[]>(() => chain.GetConsensusNodeKeys()); }
public static void SignOracleResponseTransaction(ProtocolSettings settings, ExpressChain chain, Transaction tx, IReadOnlyList <ECPoint> oracleNodes) { var signatures = new Dictionary <ECPoint, byte[]>(); for (int i = 0; i < chain.ConsensusNodes.Count; i++) { var account = chain.ConsensusNodes[i].Wallet.DefaultAccount ?? throw new Exception("Invalid DefaultAccount"); var key = DevWalletAccount.FromExpressWalletAccount(settings, account).GetKey() ?? throw new Exception("Invalid KeyPair"); if (oracleNodes.Contains(key.PublicKey)) { signatures.Add(key.PublicKey, tx.Sign(key, chain.Network)); } } int m = oracleNodes.Count - (oracleNodes.Count - 1) / 3; if (signatures.Count < m) { throw new Exception("Insufficient oracle response signatures"); } var contract = Contract.CreateMultiSigContract(m, oracleNodes); var sb = new ScriptBuilder(); foreach (var kvp in signatures.OrderBy(p => p.Key).Take(m)) { sb.EmitPush(kvp.Value); } var index = tx.GetScriptHashesForVerifying(null)[0] == contract.ScriptHash ? 0 : 1; tx.Witnesses[index].InvocationScript = sb.ToArray(); }
/// <summary> /// Constructs a Protocol object. /// </summary> /// <param name="treeView">TreeViewEx object which holds the contact list for the application</param> /// <param name="taskbarNotify">TaskbarNotify object which pops up on certain events</param> /// <param name="fileName">Filename of the plugin assembly</param> /// <param name="mainStorage">IStorage instance where the application's settings are stored</param> public Protocol(TreeViewEx treeView, TaskbarNotifier taskbarNotify, string fileName, IStorage mainStorage) { this.treeView = treeView; this.taskbarNotify = taskbarNotify; this.classFactory = new ClassFactory(fileName); // create plugin constants class IConstants constants = classFactory.CreateConstants(); this.localStorage = mainStorage.CreateSubSection(constants.Name); // create registry key for this protocol to store the settings this.settings = classFactory.CreateSettings(constants, this.localStorage, this.optionsList); this.settings.Load(); // create protocol control and register this class to be an event listener this.protocolServer = new ProtocolServer(); this.protocolServer.AddListener(this); this.protocolControl = new ProtocolControl(this.protocolServer); this.reporter = new NBM.Diagnostics.ProtocolReporter(this); }
internal bool Verify(ProtocolSettings settings, DataCache snapshot, HeaderCache headerCache) { Header prev = headerCache.Last; if (prev is null) { return(Verify(settings, snapshot)); } if (PrimaryIndex >= settings.ValidatorsCount) { return(false); } if (prev.Hash != PrevHash) { return(false); } if (prev.Index + 1 != Index) { return(false); } if (prev.Timestamp >= Timestamp) { return(false); } return(this.VerifyWitness(settings, snapshot, prev.NextConsensus, Witness, 1_00000000, out _)); }
internal bool Verify(ProtocolSettings settings, DataCache snapshot) { if (PrimaryIndex >= settings.ValidatorsCount) { return(false); } TrimmedBlock prev = NativeContract.Ledger.GetTrimmedBlock(snapshot, PrevHash); if (prev is null) { return(false); } if (prev.Index + 1 != Index) { return(false); } if (prev.Header.Timestamp >= Timestamp) { return(false); } if (!this.VerifyWitnesses(settings, snapshot, 1_00000000)) { return(false); } return(true); }
/// <summary> /// Create a new wallet /// </summary> /// <param name="path">Path</param> /// <param name="passwordKey">Password Key</param> /// <param name="scrypt">Scrypt initialization value</param> private UserWallet(string path, byte[] passwordKey, ProtocolSettings settings, ScryptParameters scrypt) : base(path, settings) { this.iv = new byte[16]; this.salt = new byte[20]; this.masterKey = new byte[32]; this.scrypt = scrypt; this.accounts = new Dictionary <UInt160, UserWalletAccount>(); using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(iv); rng.GetBytes(salt); rng.GetBytes(masterKey); } Version version = Assembly.GetExecutingAssembly().GetName().Version; byte[] versionBuffer = new byte[sizeof(int) * 4]; BinaryPrimitives.WriteInt32LittleEndian(versionBuffer, version.Major); BinaryPrimitives.WriteInt32LittleEndian(versionBuffer.AsSpan(4), version.Minor); BinaryPrimitives.WriteInt32LittleEndian(versionBuffer.AsSpan(8), version.Build); BinaryPrimitives.WriteInt32LittleEndian(versionBuffer.AsSpan(12), version.Revision); BuildDatabase(); SaveStoredData("IV", iv); SaveStoredData("Salt", salt); SaveStoredData("PasswordHash", passwordKey.Concat(salt).ToArray().Sha256()); SaveStoredData("MasterKey", Encrypt(masterKey, passwordKey, iv)); SaveStoredData("Version", versionBuffer); SaveStoredData("ScryptN", this.scrypt.N); SaveStoredData("ScryptR", this.scrypt.R); SaveStoredData("ScryptP", this.scrypt.P); }
public static bool TryLoad(ProtocolSettings settings, DataCache snapshot, UInt160 scriptHash, out Nep17Contract contract) { if (scriptHash == NativeContract.NEO.Hash) { contract = Nep17Contract.Create(NativeContract.NEO); return(true); } if (scriptHash == NativeContract.GAS.Hash) { contract = Nep17Contract.Create(NativeContract.GAS); return(true); } var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); if (contractState != null) { using var sb = new ScriptBuilder(); sb.EmitDynamicCall(scriptHash, "symbol"); sb.EmitDynamicCall(scriptHash, "decimals"); using var engine = sb.Invoke(settings, snapshot); if (engine.State != VMState.FAULT && engine.ResultStack.Count >= 2) { var decimals = (byte)engine.ResultStack.Pop <Neo.VM.Types.Integer>().GetInteger(); var symbol = Encoding.UTF8.GetString(engine.ResultStack.Pop().GetSpan()); contract = new Nep17Contract(symbol, decimals, scriptHash); return(true); } } contract = default; return(false); }
internal FileServiceData(ResourceIdentifier id, string name, ResourceType type, Models.Sku sku, CorsRules cors, DeleteRetentionPolicy shareDeleteRetentionPolicy, ProtocolSettings protocolSettings) : base(id, name, type) { Sku = sku; Cors = cors; ShareDeleteRetentionPolicy = shareDeleteRetentionPolicy; ProtocolSettings = protocolSettings; }
public static JObject BlockToJson(Block block, ProtocolSettings settings) { JObject json = block.ToJson(settings); json["tx"] = block.Transactions.Select(p => TransactionToJson(p, settings)).ToArray(); return(json); }
public static bool VerifyWitnesses(this IVerifiable verifiable, ProtocolSettings settings, DataCache snapshot, long gas) { if (gas < 0) { return(false); } if (gas > MaxVerificationGas) { gas = MaxVerificationGas; } UInt160[] hashes; try { hashes = verifiable.GetScriptHashesForVerifying(snapshot); } catch (InvalidOperationException) { return(false); } if (hashes.Length != verifiable.Witnesses.Length) { return(false); } for (int i = 0; i < hashes.Length; i++) { if (!verifiable.VerifyWitness(settings, snapshot, hashes[i], verifiable.Witnesses[i], gas, out long fee)) { return(false); } gas -= fee; } return(true); }
public static UInt160 ToScriptHash(this JObject value, ProtocolSettings protocolSettings) { var addressOrScriptHash = value.AsString(); return(addressOrScriptHash.Length < 40 ? addressOrScriptHash.ToScriptHash(protocolSettings.AddressVersion) : UInt160.Parse(addressOrScriptHash)); }
static bool UpdateDefault(IConfiguration configuration) { var settings = new CliSettings(configuration.GetSection("ApplicationConfiguration")); settings.Protocol = ProtocolSettings.Load("config".GetEnvConfigPath()); return(null == Interlocked.CompareExchange(ref _default, settings, null)); }
private void RunTest(CardAndPhoneUsage policyValue, bool expectedValid, string card, string phone) { var protocolSettings = ProtocolSettings.CreateEmpty(); protocolSettings.CardAndPhoneUsage = policyValue; var sampleRequest = new ConfirmPurchaseRequest { PosId = "12345", CardNumber = card, PhoneNumber = phone, Transactions = { "12345" }, }; var isValid = new LikePharmaValidator(protocolSettings).TryValidateObject(sampleRequest, out var results); if (expectedValid) { Assert.True(isValid); Assert.Empty(results); } else { Assert.False(isValid); Assert.Single(results); } }
internal FileServiceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, StorageSku sku, CorsRules cors, DeleteRetentionPolicy shareDeleteRetentionPolicy, ProtocolSettings protocolSettings) : base(id, name, resourceType, systemData) { Sku = sku; Cors = cors; ShareDeleteRetentionPolicy = shareDeleteRetentionPolicy; ProtocolSettings = protocolSettings; }
private static Signers SignersFromJson(JArray _params, ProtocolSettings settings) { var ret = new Signers(_params.Select(u => new Signer() { Account = AddressToScriptHash(u["account"].AsString(), settings.AddressVersion), Scopes = (WitnessScope)Enum.Parse(typeof(WitnessScope), u["scopes"]?.AsString()), AllowedContracts = ((JArray)u["allowedcontracts"])?.Select(p => UInt160.Parse(p.AsString())).ToArray(), AllowedGroups = ((JArray)u["allowedgroups"])?.Select(p => ECPoint.Parse(p.AsString(), ECCurve.Secp256r1)).ToArray(), Rules = ((JArray)u["rules"])?.Select(WitnessRule.FromJson).ToArray(), }).ToArray()) { Witnesses = _params .Select(u => new { Invocation = u["invocation"]?.AsString(), Verification = u["verification"]?.AsString() }) .Where(x => x.Invocation != null || x.Verification != null) .Select(x => new Witness() { InvocationScript = Convert.FromBase64String(x.Invocation ?? string.Empty), VerificationScript = Convert.FromBase64String(x.Verification ?? string.Empty) }).ToArray() }; // Validate format _ = IO.Helper.ToByteArray(ret.GetSigners()).AsSerializableArray <Signer>(); return(ret); }
/// <summary> /// Create a new wallet /// </summary> /// <param name="path">Path</param> /// <param name="passwordKey">Password Key</param> /// <param name="scrypt">Scrypt initialization value</param> private UserWallet(string path, byte[] passwordKey, ProtocolSettings settings, ScryptParameters scrypt) : base(path, settings) { this.iv = new byte[16]; this.salt = new byte[20]; this.masterKey = new byte[32]; this.scrypt = scrypt; this.accounts = new Dictionary <UInt160, UserWalletAccount>(); using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(iv); rng.GetBytes(salt); rng.GetBytes(masterKey); } Version version = Assembly.GetExecutingAssembly().GetName().Version; BuildDatabase(); SaveStoredData("IV", iv); SaveStoredData("Salt", salt); SaveStoredData("PasswordHash", passwordKey.Concat(salt).ToArray().Sha256()); SaveStoredData("MasterKey", masterKey.AesEncrypt(passwordKey, iv)); SaveStoredData("Version", new[] { version.Major, version.Minor, version.Build, version.Revision }.Select(p => BitConverter.GetBytes(p)).SelectMany(p => p).ToArray()); SaveStoredData("ScryptN", BitConverter.GetBytes(this.scrypt.N)); SaveStoredData("ScryptR", BitConverter.GetBytes(this.scrypt.R)); SaveStoredData("ScryptP", BitConverter.GetBytes(this.scrypt.P)); }
/// <summary> /// Parse address, scripthash or public key string to UInt160 /// </summary> /// <param name="account">account address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575")</param> /// <returns></returns> public static UInt160 GetScriptHash(string account, ProtocolSettings protocolSettings) { if (string.IsNullOrEmpty(account)) { throw new ArgumentNullException(nameof(account)); } if (account.StartsWith("0x")) { account = account.Substring(2); } if (account.Length == 34) { return(Wallets.Helper.ToScriptHash(account, protocolSettings.AddressVersion)); } else if (account.Length == 40) { return(UInt160.Parse(account)); } else if (account.Length == 66) { var pubKey = ECPoint.Parse(account, ECCurve.Secp256r1); return(Contract.CreateSignatureRedeemScript(pubKey).ToScriptHash()); } throw new FormatException(); }
public NullCheckpointStore(uint?network = null, byte?addressVersion = null) { this.Settings = ProtocolSettings.Default with { Network = network ?? ProtocolSettings.Default.Network, AddressVersion = addressVersion ?? ProtocolSettings.Default.AddressVersion, }; }
public override bool Verify(ProtocolSettings protocolSettings) { if (!base.Verify(protocolSettings)) { return(false); } return(TransactionHashes.Length <= protocolSettings.MaxTransactionsPerBlock); }
public JObject ToJson(ProtocolSettings protocolSettings) { JObject json = new(); json["balance"] = Balances.Select(p => p.ToJson()).ToArray(); json["address"] = UserScriptHash.ToAddress(protocolSettings.AddressVersion); return(json); }
public static JObject TransactionToJson(Transaction tx, ProtocolSettings settings) { JObject json = tx.ToJson(settings); json["sysfee"] = tx.SystemFee.ToString(); json["netfee"] = tx.NetworkFee.ToString(); return(json); }
public static RpcApplicationLog FromJson(JObject json, ProtocolSettings protocolSettings) { return(new RpcApplicationLog { TxId = json["txid"] is null ? null : UInt256.Parse(json["txid"].AsString()), BlockHash = json["blockhash"] is null ? null : UInt256.Parse(json["blockhash"].AsString()), Executions = ((JArray)json["executions"]).Select(p => Execution.FromJson(p, protocolSettings)).ToList(), });
public static Block BlockFromJson(JObject json, ProtocolSettings protocolSettings) { return(new Block() { Header = HeaderFromJson(json, protocolSettings), Transactions = ((JArray)json["tx"]).Select(p => TransactionFromJson(p, protocolSettings)).ToArray() }); }
private Timer pingTimer = new Timer(60 * 1000); // ping timer, ping every minute public Protocol(ProtocolControl control, ProtocolSettings settings) { this.control = control; this.settings = (Settings)settings; this.pingTimer.AutoReset = true; this.pingTimer.Elapsed += new ElapsedEventHandler(OnPingTimerElapse); }
public JObject ToJson(ProtocolSettings protocolSettings) { JObject json = Utility.BlockToJson(Block, protocolSettings); json["confirmations"] = Confirmations; json["nextblockhash"] = NextBlockHash?.ToString(); return(json); }
public static RpcBlock FromJson(JObject json, ProtocolSettings protocolSettings) { return(new RpcBlock { Block = Utility.BlockFromJson(json, protocolSettings), Confirmations = (uint)json["confirmations"].AsNumber(), NextBlockHash = json["nextblockhash"] is null ? null : UInt256.Parse(json["nextblockhash"].AsString()) });
public static RpcTransferOut FromJson(JObject json, ProtocolSettings protocolSettings) { return(new RpcTransferOut { Asset = json["asset"].ToScriptHash(protocolSettings), Value = json["value"].AsString(), ScriptHash = json["address"].ToScriptHash(protocolSettings), }); }
public static ProtocolSettings ParseHandshake(byte[] bytes) { if (bytes == null || bytes.Length < 32) { throw new ArgumentException("Expected 32 bytes for Rserve identification"); } var protocol = new ProtocolSettings { Signature = Encoding.UTF8.GetString(bytes, 0, 4), Version = Encoding.UTF8.GetString(bytes, 4, 4), Name = Encoding.UTF8.GetString(bytes, 8, 4) }; for (int i = 12; i < 32; i += 4) { string attribute = Encoding.UTF8.GetString(bytes, i, 4); // don't bother parsing for R version; shouldn't see this // attribute any more (versions are too high to be represented // now in "R" attribute's remaining 3 bytes) // if (attribute.StartsWith("R")) // { // _rVersion = attribute; // } if (attribute.StartsWith("AR")) { protocol.IsAuthorizationRequired = true; if (attribute.EndsWith("pt")) protocol.PasswordEncryption = PasswordEncryption.PlainText; else if (attribute.EndsWith("uc")) protocol.PasswordEncryption = PasswordEncryption.UnixCrypt; } if (attribute.StartsWith("K")) { protocol.PasswordEncryptionKey = attribute.Substring(1, 3); } } return protocol; }