public virtual byte[] GetScript(byte[] script_hash) { var hash = new UInt160(script_hash); var address = hash.ToAddress(); Logger($"Fetching contract at address {address}"); var account = GetAccount(hash); return(account != null && account.contract != null ? account.contract.script : null); }
private static (UnspentBalance, Fixed8) GetBalance(UInt160 account, UInt256 assetId) { var response = rpcClient.GetUnspents(account.ToAddress()); var balances = response.Balances; foreach (var balance in balances) { if ("0x" + balance.AssetHash == assetId.ToString()) { return(balance, balance.Amount); } } throw new Exception("Asset not found"); }
public JObject GetNep17Balances(JArray _params) { UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString()); JObject json = new(); JArray balances = new(); json["address"] = userScriptHash.ToAddress(_neoSystem.Settings.AddressVersion); json["balance"] = balances; int count = 0; byte[] prefix = Key(Nep17BalancePrefix, userScriptHash); foreach (var(key, value) in _db.FindPrefix <Nep17BalanceKey, TokenBalance>(prefix)) { if (NativeContract.ContractManagement.GetContract(_neoSystem.StoreView, key.AssetScriptHash) is null) { continue; } try { using var script = new ScriptBuilder(); script.EmitDynamicCall(key.AssetScriptHash, "decimals"); script.EmitDynamicCall(key.AssetScriptHash, "symbol"); var engine = ApplicationEngine.Run(script.ToArray(), _neoSystem.StoreView, settings: _neoSystem.Settings); var symbol = engine.ResultStack.Pop().GetString(); var decimals = engine.ResultStack.Pop().GetInteger(); var name = NativeContract.ContractManagement.GetContract(_neoSystem.StoreView, key.AssetScriptHash).Manifest.Name; balances.Add(new JObject { ["assethash"] = key.AssetScriptHash.ToString(), ["name"] = name, ["symbol"] = symbol, ["decimals"] = decimals.ToString(), ["amount"] = value.Balance.ToString(), ["lastupdatedblock"] = value.LastUpdatedBlock }); count++; if (count >= _maxResults) { break; } } catch { } } return(json); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } UInt160 data = (UInt160)value; var stringData = data.ToAddress(); writer.WriteValue(stringData); }
/// <summary> /// Create an unsigned Transaction object with given parameters. /// </summary> /// <param name="script">Transaction Script</param> /// <param name="attributes">Transaction Attributes</param> /// <param name="cosigners">Transaction Cosigners</param> /// <param name="networkFee">Transaction NetworkFee, will set to estimate value(with only basic signatures) when networkFee is 0</param> /// <returns></returns> public TransactionManager MakeTransaction(byte[] script, TransactionAttribute[] attributes = null, Cosigner[] cosigners = null, long networkFee = 0) { var random = new Random(); uint height = rpcClient.GetBlockCount() - 1; Tx = new Transaction { Version = 0, Nonce = (uint)random.Next(), Script = script, Sender = sender, ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement, Attributes = attributes ?? new TransactionAttribute[0], Cosigners = cosigners ?? new Cosigner[0], Witnesses = new Witness[0] }; // Add witness hashes parameter to pass CheckWitness UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); RpcInvokeResult result = rpcClient.InvokeScript(script, hashes); Tx.SystemFee = Math.Max(long.Parse(result.GasConsumed) - ApplicationEngine.GasFree, 0); if (Tx.SystemFee > 0) { long d = (long)NativeContract.GAS.Factor; long remainder = Tx.SystemFee % d; if (remainder > 0) { Tx.SystemFee += d - remainder; } else if (remainder < 0) { Tx.SystemFee -= remainder; } } context = new ContractParametersContext(Tx); // set networkfee to estimate value when networkFee is 0 Tx.NetworkFee = networkFee == 0 ? EstimateNetworkFee() : networkFee; var gasBalance = nep5API.BalanceOf(NativeContract.GAS.Hash, sender); if (gasBalance >= Tx.SystemFee + Tx.NetworkFee) { return(this); } throw new InvalidOperationException($"Insufficient GAS in address: {sender.ToAddress()}"); }
public virtual JObject ToJson() { JObject json = new JObject(); json["hash"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["previousblockhash"] = PrevHash.ToString(); json["merkleroot"] = MerkleRoot.ToString(); json["time"] = Timestamp; json["index"] = Index; json["nextconsensus"] = NextConsensus.ToAddress(); json["witnesses"] = new JArray(Witness.ToJson()); return(json); }
/// <summary> /// Constructor to set address /// </summary> /// <param name="address">String of public address or script hash</param> public NeoWallet(string loginValue) { if (loginValue.Substring(0, 1).Equals("A")) { this.address = loginValue; this.scriptHash = loginValue.ToScriptHash().ToString(); } else { this.scriptHash = loginValue; var valArray = _helper.ValueToByteArray(loginValue); var hash = new UInt160(valArray); this.address = hash.ToAddress(); } }
public JObject ToJson() { JObject json = new JObject(); json["txid"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["script"] = Script.ToHexString(); json["sender"] = Sender.ToAddress(); json["gas"] = new BigDecimal(Gas, (byte)NativeContract.GAS.Decimals).ToString(); json["net_fee"] = new BigDecimal(NetworkFee, (byte)NativeContract.GAS.Decimals).ToString(); json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray(); json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray(); return(json); }
public virtual JObject ToJson() { JObject json = new JObject(); json["hash"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["previousblockhash"] = PrevHash.ToString(); json["merkleroot"] = MerkleRoot.ToString(); json["time"] = Timestamp; json["index"] = Index; json["nonce"] = ConsensusData.ToString("x16"); json["nextconsensus"] = NextConsensus.ToAddress(); json["script"] = Witness.ToJson(); return json; }
public async Task <(Neo.Network.RPC.Models.RpcNep17Balance balance, Nep17Contract contract)[]> GetBalancesAsync(UInt160 address) { var contracts = ((Neo.IO.Json.JArray) await rpcClient.RpcSendAsync("expressgetnep17contracts")) .Select(json => Nep17Contract.FromJson(json)) .ToDictionary(c => c.ScriptHash); var balances = await rpcClient.GetNep17BalancesAsync(address.ToAddress()).ConfigureAwait(false); return(balances.Balances .Select(b => ( balance: b, contract: contracts.TryGetValue(b.AssetHash, out var value) ? value : Nep17Contract.Unknown(b.AssetHash))) .ToArray()); }
public override string GetNep5Transfers(UInt160 scriptHash, DateTime timestamp) { if (!HasPlugin("RpcNep5Tracker")) { return(null); } var unixTimestamp = (timestamp.ToUniversalTime() - (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalSeconds; var response = QueryRPC("getnep5transfers", new object[] { scriptHash.ToAddress(), unixTimestamp }); string json = JSONWriter.WriteToString(response); return(json); }
public bool Runtime_CheckWitness(ExecutionEngine engine) { byte[] hashOrPubkey = engine.EvaluationStack.Pop().GetByteArray(); bool result; var tx = (Transaction)engine.ScriptContainer; if (hashOrPubkey.Length == 20) // script hash { var hash = new UInt160(hashOrPubkey); var address = hash.ToAddress(); result = false; foreach (var input in tx.inputs) { var reference = GetTransaction(input.prevHash); var output = reference.outputs[input.prevIndex]; var other_address = output.scriptHash.ToAddress(); Logger($"Comparing {address} to {other_address}"); if (ValidateWitness(output.scriptHash, hash)) { result = true; break; } } } else if (hashOrPubkey.Length == 33) // public key { //hash = ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1); //result = CheckWitness(engine, Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash()); throw new Exception("ECPoint witness"); } else { result = false; } //DoLog($"Checking Witness [{matchType}]: {FormattingUtils.OutputData(hashOrPubkey, false)} => {result}"); engine.EvaluationStack.Push(new VM.Types.Boolean(result)); return(true); }
public void TestToScriptHash() { byte[] array = { 0x01 }; UInt160 scriptHash = new UInt160(Crypto.Hash160(array)); "NdtB8RXRmJ7Nhw1FPTm7E6HoDZGnDw37nf".ToScriptHash().Should().Be(scriptHash); Action action = () => "3vQB7B6MrGQZaxCuFg4oh".ToScriptHash(); action.Should().Throw <FormatException>(); var address = scriptHash.ToAddress(); Span <byte> data = stackalloc byte[21]; // NEO version is 0x17 data[0] = 0x01; scriptHash.ToArray().CopyTo(data[1..]);
public JObject ToJson() { JObject json = new JObject(); json["hash"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["nonce"] = Nonce; json["sender"] = Sender.ToAddress(); json["sys_fee"] = new BigDecimal(SystemFee, NativeContract.GAS.Decimals).ToString(); json["net_fee"] = new BigDecimal(NetworkFee, NativeContract.GAS.Decimals).ToString(); json["valid_until_block"] = ValidUntilBlock; json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray(); json["script"] = Script.ToHexString(); json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray(); return(json); }
public string Export(string passphrase, int N = 16384, int r = 8, int p = 8) { UInt160 script_hash = Contract.CreateSignatureRedeemScript(PublicKey).ToScriptHash(); string address = script_hash.ToAddress(); byte[] addresshash = Encoding.ASCII.GetBytes(address).Sha256().Sha256().Take(4).ToArray(); byte[] derivedkey = SCrypt.DeriveKey(Encoding.UTF8.GetBytes(passphrase), addresshash, N, r, p, 64); byte[] derivedhalf1 = derivedkey.Take(32).ToArray(); byte[] derivedhalf2 = derivedkey.Skip(32).ToArray(); byte[] encryptedkey = XOR(PrivateKey, derivedhalf1).AES256Encrypt(derivedhalf2); byte[] buffer = new byte[39]; buffer[0] = 0x01; buffer[1] = 0x42; buffer[2] = 0xe0; Buffer.BlockCopy(addresshash, 0, buffer, 3, addresshash.Length); Buffer.BlockCopy(encryptedkey, 0, buffer, 7, encryptedkey.Length); return(buffer.Base58CheckEncode()); }
public JObject ToJson() { JObject json = new JObject(); json["hash"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["nonce"] = Nonce; json["sender"] = Sender.ToAddress(); json["sys_fee"] = SystemFee.ToString(); json["net_fee"] = NetworkFee.ToString(); json["valid_until_block"] = ValidUntilBlock; json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray(); json["cosigners"] = Cosigners.Select(p => p.ToJson()).ToArray(); json["script"] = Convert.ToBase64String(Script); json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray(); return(json); }
public override Dictionary <string, decimal> GetAssetBalancesOf(UInt160 scriptHash) { var response = QueryRPC("getaccountstate", new object[] { scriptHash.ToAddress() }); var result = new Dictionary <string, decimal>(); var resultNode = response.GetNode("result"); var balances = resultNode.GetNode("balances"); foreach (var entry in balances.Children) { var assetID = entry.GetString("asset"); var amount = entry.GetDecimal("value"); var symbol = SymbolFromAssetID(assetID); result[symbol] = amount; } return(result); }
public override JObject ToJson() { JObject json = base.ToJson(); json["asset"] = new JObject(); json["asset"]["type"] = AssetType; try { json["asset"]["name"] = Name == "" ? null : JObject.Parse(Name); } catch (FormatException) { json["asset"]["name"] = Name; } json["asset"]["amount"] = Amount.ToString(); json["asset"]["precision"] = Precision; json["asset"]["owner"] = Owner.ToString(); json["asset"]["admin"] = Admin.ToAddress(); return(json); }
private static void UpdateResultFromFile(UInt160 hash) { string address = hash.ToAddress(); X509Certificate2 cert; try { cert = new X509Certificate2(Path.Combine(Settings.Default.Paths.CertCache, $"{address}.cer")); } catch (CryptographicException) { results[hash].Type = CertificateQueryResultType.Missing; return; } if (cert.PublicKey.Oid.Value != "1.2.840.10045.2.1") { results[hash].Type = CertificateQueryResultType.Missing; return; } if (!hash.Equals(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(cert.PublicKey.EncodedKeyValue.RawData, ECCurve.Secp256r1)).ToScriptHash())) { results[hash].Type = CertificateQueryResultType.Missing; return; } using (X509Chain chain = new X509Chain()) { results[hash].Certificate = cert; if (chain.Build(cert)) { results[hash].Type = CertificateQueryResultType.Good; } else if (chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.NotTimeValid) { results[hash].Type = CertificateQueryResultType.Expired; } else { results[hash].Type = CertificateQueryResultType.Invalid; } } }
private JObject GetNep5Balances(JArray _params) { UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString()); JObject json = new JObject(); JArray balances = new JArray(); json["balance"] = balances; json["address"] = userScriptHash.ToAddress(); var dbCache = new DbCache <Nep5BalanceKey, Nep5Balance>(_db, null, null, Nep5BalancePrefix); byte[] prefix = userScriptHash.ToArray(); foreach (var storageKeyValuePair in dbCache.Find(prefix)) { byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitAppCall(storageKeyValuePair.Key.AssetScriptHash, "decimals"); sb.EmitAppCall(storageKeyValuePair.Key.AssetScriptHash, "symbol"); sb.EmitAppCall(storageKeyValuePair.Key.AssetScriptHash, "name"); script = sb.ToArray(); } ApplicationEngine engine = ApplicationEngine.Run(script); JObject balance = new JObject(); balance["asset_hash"] = storageKeyValuePair.Key.AssetScriptHash.ToArray().Reverse().ToHexString(); if (!engine.State.HasFlag(VMState.FAULT)) { balance["asset_name"] = engine.ResultStack.Pop().GetString(); balance["asset_symbol"] = engine.ResultStack.Pop().GetString(); balance["asset_decimals"] = (byte)engine.ResultStack.Pop().GetBigInteger(); } balance["amount"] = storageKeyValuePair.Value.Balance.ToString(); balance["last_updated_block"] = storageKeyValuePair.Value.LastUpdatedBlock; balances.Add(balance); } return(json); }
public void TestGetScriptHash() { string nul = null; Assert.ThrowsException <ArgumentNullException>(() => Utility.GetScriptHash(nul)); string addr = scriptHash.ToAddress(); var result = Utility.GetScriptHash(addr); Assert.AreEqual(scriptHash, result); string hash = scriptHash.ToString(); result = Utility.GetScriptHash(hash); Assert.AreEqual(scriptHash, result); string publicKey = keyPair.PublicKey.ToString(); result = Utility.GetScriptHash(publicKey); Assert.AreEqual(scriptHash, result); }
public void TestToScriptHash() { byte[] array = { 0x01 }; UInt160 scriptHash = new UInt160(Crypto.Default.Hash160(array)); "AZk5bAanTtD6AvpeesmYgL8CLRYUt5JQsX".ToScriptHash().Should().Be(scriptHash); Action action = () => "3vQB7B6MrGQZaxCuFg4oh".ToScriptHash(); action.ShouldThrow <FormatException>(); var address = scriptHash.ToAddress(); byte[] data = new byte[21]; // NEO version is 0x17 data[0] = 0x01; Buffer.BlockCopy(scriptHash.ToArray(), 0, data, 1, 20); address = data.Base58CheckEncode(); action = () => address.ToScriptHash(); action.ShouldThrow <FormatException>(); }
public JObject GetNep17Balances(JArray _params) { UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString()); JObject json = new JObject(); JArray balances = new JArray(); json["balance"] = balances; json["address"] = userScriptHash.ToAddress(System.Settings.AddressVersion); using (Iterator it = _db.NewIterator(ReadOptions.Default)) { byte[] prefix = Key(Nep17BalancePrefix, userScriptHash); for (it.Seek(prefix); it.Valid(); it.Next()) { ReadOnlySpan <byte> key_bytes = it.Key(); if (!key_bytes.StartsWith(prefix)) { break; } Nep17BalanceKey key = key_bytes[1..].AsSerializable <Nep17BalanceKey>();
// Note: This current implementation requires NeoScan running at port 4000 public IEnumerator GetUnspent(UInt160 hash, Action <UnspentEntries> callback) { var url = this.neoscanUrl + "/api/main_net/v1/get_balance/" + hash.ToAddress(); return(ExecuteRequestWeb( (response) => { var unspents = new Dictionary <string, List <UnspentEntry> >(); response = response["balance"]; foreach (var child in response.Children) { var symbol = child.GetString("asset"); List <UnspentEntry> list = new List <UnspentEntry>(); unspents[symbol] = list; var unspentNode = child.GetNode("unspent"); foreach (var entry in unspentNode.Children) { var txid = entry.GetString("txid"); var val = entry.GetDecimal("value"); var temp = new UnspentEntry() { hash = new UInt256(NeoUtils.ReverseHex(txid).HexToBytes()), value = val, index = entry.GetUInt32("n") }; list.Add(temp); } } var result = new UnspentEntries() { entries = unspents }; callback(result); }, ErrorHandler, url)); }
private static Operation[] ConvertToTransferOperation(byte[] scripts) { var instructions = Parse(scripts); if (instructions.Count != 10 || instructions[^ 8].OpCode != OpCode.PUSHDATA1 || instructions[^ 7].OpCode != OpCode.PUSHDATA1 || instructions[^ 6].OpCode != OpCode.PUSH4 || instructions[^ 5].OpCode != OpCode.PACK || instructions[^ 4].OpCode != OpCode.PUSH15 || instructions[^ 3].OpCode != OpCode.PUSHDATA1 || instructions[^ 3].TokenString != "transfer" || instructions[^ 2].OpCode != OpCode.PUSHDATA1 || instructions[^ 1].OpCode != OpCode.SYSCALL) { return(new Operation[0]); } var from = new UInt160(instructions[3].Operand.ToArray()); var to = new UInt160(instructions[2].Operand.ToArray()); var amount = ConvertInteger(instructions[1]); var tokenhash = new UInt160(instructions[8].Operand.ToArray()); Operation fromOperation = new Operation(new OperationIdentifier(0), OperationType.Transfer, null, // vm state is HALT, FAULT transfer is ignored null, new AccountIdentifier(from.ToAddress(53)), (-amount).ToNEOorGASAmount(tokenhash), null ); Operation toOperation = new Operation(new OperationIdentifier(1), OperationType.Transfer, null, new OperationIdentifier[] { new OperationIdentifier(0) }, // related Operation is the fromOperation new AccountIdentifier(to.ToAddress(53)), (amount).ToNEOorGASAmount(tokenhash), null ); return(new Operation[] { fromOperation, toOperation }); }
private JObject GetNep5Balances(JArray _params) { UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString()); JObject json = new JObject(); JArray balances = new JArray(); json["balance"] = balances; json["address"] = userScriptHash.ToAddress(); var dbCache = new DbCache <Nep5BalanceKey, Nep5Balance>(_db, null, null, Nep5BalancePrefix); byte[] prefix = userScriptHash.ToArray(); foreach (var storageKeyValuePair in dbCache.Find(prefix)) { JObject balance = new JObject(); balance["asset_hash"] = storageKeyValuePair.Key.AssetScriptHash.ToArray().Reverse().ToHexString(); balance["amount"] = storageKeyValuePair.Value.Balance.ToString(); balance["last_updated_block"] = storageKeyValuePair.Value.LastUpdatedBlock; balances.Add(balance); } return(json); }
public IEnumerator GetAssetBalancesOf(UInt160 scriptHash, Action <Dictionary <string, decimal> > callback) { return(ExecuteRequestRPC( (response) => { var result = new Dictionary <string, decimal>(); var balances = response.GetNode("balances"); foreach (var entry in balances.Children) { var assetID = entry.GetString("asset"); var amount = entry.GetDecimal("value"); var symbol = SymbolFromAssetID(assetID); result[symbol] = amount; } callback(result); }, ErrorHandler, "getaccountstate", new object[] { scriptHash.ToAddress() })); }
private static void Web_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { using ((WebClient)sender) { UInt160 hash = (UInt160)e.UserState; if (e.Cancelled || e.Error != null) { lock (results) { results[hash].Type = CertificateQueryResultType.Missing; } } else { string address = hash.ToAddress(); string path = Path.Combine(Settings.Default.Paths.CertCache, $"{address}.cer"); File.WriteAllBytes(path, e.Result); lock (results) { UpdateResultFromFile(hash); } } } }
public static WalletInformations GetWalletInformations(SecureString privateKey, BlockchainType keyType) { WalletInformations walletInformations = new WalletInformations(); switch (keyType) { case BlockchainType.Neo: var keyPair = new KeyPair(privateKey.GetString().HexToBytes()); string publicKey = keyPair.PublicKey.ToString(); UInt160 scriptHash = Helper.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(); // This is a basic NEO address string address = scriptHash.ToAddress(); // This is a derivative of script hash (required by Switcheo) string fixedAddress = scriptHash.ToString().RemoveZeroX(); walletInformations = new WalletInformations() { Wif = keyPair.Export().ToSecureString(), PublicKey = publicKey, ScriptHash = scriptHash.ToString(), Address = address, FixedAddress = fixedAddress }; break; case BlockchainType.Qtum: throw new NotImplementedException(); case BlockchainType.Ethereum: throw new NotImplementedException(); } return(walletInformations); }
public override JObject ToJson() { JObject json = base.ToJson(); json["id"] = AssetId.ToString(); json["type"] = AssetType; try { json["name"] = Name == "" ? null : JObject.Parse(Name); } catch (FormatException) { json["name"] = Name; } json["amount"] = Amount.ToString(); json["available"] = Available.ToString(); json["precision"] = Precision; json["owner"] = Owner.ToString(); json["admin"] = Admin.ToAddress(); json["issuer"] = Issuer.ToAddress(); json["expiration"] = Expiration; json["frozen"] = IsFrozen; return(json); }