public byte[] GenerateLoaderScriptFromInputs(DataNode inputs) { using (ScriptBuilder sb = new ScriptBuilder()) { var items = new Stack <object>(); if (inputs != null) { foreach (var item in inputs.Children) { var obj = Emulator.ConvertArgument(item); items.Push(obj); } } while (items.Count > 0) { var item = items.Pop(); NeoAPI.EmitObject(sb, item); } var loaderScript = sb.ToArray(); //System.IO.File.WriteAllBytes("loader.avm", loaderScript); return(loaderScript); } }
static void Main(string[] args) { if (args.Length < 5) { Console.WriteLine("neo-sender <Net> <PrivateKey> <DestAddress> <Symbol> <Amount>"); return; } var net = (NeoAPI.Net)Enum.Parse(typeof(NeoAPI.Net), args[0], true); var keyStr = args[1]; //fc1fa7c0d83426486373d9ce6eaca8adb506fc4ca25e89887c8eb5567f317a53" var outputAddress = args[2]; //"AanTL6pTTEdnphXpyPMgb7PSE8ifSWpcXU" var symbol = args[3]; //"GAS" var amount = decimal.Parse(args[4]); var myKey = keyStr.Length == 52 ? KeyPair.FromWIF(keyStr) : new KeyPair(keyStr.HexToBytes()); Console.WriteLine($"Sending {amount} {symbol} from {myKey.address} to {outputAddress}"); var result = NeoAPI.SendAsset(net, outputAddress, symbol, amount, myKey); Console.WriteLine(result); }
static void ExportChunk(uint chunkID, uint maxBlock, NeoAPI api) { var fileName = "chain/chunk" + chunkID; if (File.Exists(fileName)) { var blocks = LoadChunk(fileName); if (blocks.Count == chunkSize) { return; } } var lines = new List <string>(); uint startBlock = chunkID * chunkSize; uint endBlock = startBlock + (chunkSize - 1); for (uint i = startBlock; i <= endBlock; i++) { if (i > maxBlock) { break; } var response = api.QueryRPC("getblock", new object[] { i }); var blockData = response.GetString("result"); lines.Add(blockData); } ExportBlocks(chunkID, startBlock, lines); }
private IEnumerator TryClaimRewards(int amount) { yield return(null); try { Debug.Log("Start claim NEP5 token reward"); //var tx = neoManager.API.SendAsset(neoManager.MasterKeyPair, neoManager.PlayerKeyPair.Value.address, NEOManager.AssetSymbol, (decimal)amount); UInt160 scScriptHash = new UInt160(NeoAPI.GetScriptHashFromString(this.ContractHash)); byte[] addressBytes = LuxUtils.GetScriptHashFromAddress(neoManager.PlayerKeyPair.Value.address); BigInteger nepAmt = new BigInteger(amount); var tx = neoManager.API.CallContract(neoManager.PlayerKeyPair.Value, scScriptHash, "claimRewards", new object[] { addressBytes, nepAmt }); if (tx == null) { Debug.LogError("Null Transaction returned"); Time.timeScale = 1; } else { Debug.Log(tx); Observable.FromCoroutine(SyncBalance).Subscribe().AddTo(this); } } catch (NullReferenceException ee) { Debug.LogError("There was a problem..." + ee); Time.timeScale = 1; } catch (Exception ee) { Debug.LogError("There was a problem..." + ee); Time.timeScale = 1; } }
private bool CallContract(string method, object[] values) { //NOTE: NeoLux does not support CoZ testnet at the moment. //Modified source to add temporary support by hardcoding a single node. //Keep an eye out for updates. //Audit log Log.Info(string.Format("CallContract: CommitToBlockchain:{0}, method:{1}, params:{2}", Config.CommitToBlockchain.ToString(), method, String.Join(",", values))); if (Config.CommitToBlockchain) { try { var key = new KeyPair(ConvertUtility.HexToBytes(privateKey)); var result = NeoAPI.CallContract(environment, key, smartContractScriptHash, method, values); if (result == false) { Log.Error("CallContract: Received false on method " + method); } return(result); } catch (Exception ex) { Log.Error("CallContract: Failed on method " + method + ". " + ex.Message); return(false); } } else { return(true); } }
public bool SyncMessages() { if (!string.IsNullOrEmpty(this.name)) { var curTime = DateTime.Now; var diff = curTime - lastSync; if (diff.TotalSeconds < 20) { return(false); } var script = NeoAPI.GenerateScript(Protocol.scriptHash, "getMailCount", new object[] { System.Text.Encoding.ASCII.GetBytes(this.name) }); var invoke = NeoAPI.TestInvokeScript(Protocol.net, script); if (invoke.result is byte[]) { var count = new BigInteger((byte[])invoke.result); var oldCount = _messages.Count; for (int i = oldCount + 1; i <= count; i++) { var msg = FetchMessage(i); if (msg != null) { _messages.Add(msg); } } lastSync = curTime; return(oldCount != count); } } return(false); }
public ChainListener(NeoAPI api, Transaction deployTx, uint lastBlock, Logger logger) { this.neo_api = api; this.lastBlock = lastBlock; this.logger = logger; if (deployTx != null) { var code = NeoTools.Disassemble(deployTx.script); for (int i = 1; i < code.Count; i++) { var entry = code[i]; if (entry.opcode == OpCode.SYSCALL && entry.data != null) { var method = Encoding.ASCII.GetString(entry.data); if (method == "Neo.Contract.Create") { var prev = code[i - 1]; this.contract_bytecode = prev.data; this.contract_hash = contract_bytecode.ToScriptHash(); break; } } } } else { throw new Exception($"Invalid deploy transaction"); } }
public IActionResult Check(string checksum) { var model = new ChecksumViewModel(); model.Checksum = checksum; //Get checksum info from storage var checksumStorage = NeoAPI.getStorage(NeoAPI.Net.Test, _scriptHash, checksum); if (checksumStorage != null && checksumStorage.Value != null) { string checksumValue = checksumStorage.Value; ChecksumInfo checksumInfo = ChecksumInfo.FromBytes(Encoding.ASCII.GetBytes(checksumValue)); model.ChecksumInfo = checksumInfo; //Get address info from storage (based on address from checksum info) var addressStorage = NeoAPI.getStorage(NeoAPI.Net.Test, _scriptHash, checksumInfo.Address.AsString()); if (addressStorage != null && addressStorage.Value != null) { string value = addressStorage.Value; AddressInfo addressInfo = AddressInfo.FromBytes(Encoding.ASCII.GetBytes(value)); model.AddressInfo = addressInfo; } } return(View(model)); }
public NeoEventMonitor1(NeoAPI api, Transaction deployTx, uint startBlock) { this._api = api; this._startBlock = startBlock; this._listenerVM = new SnapshotVM(this); List <AVMInstruction> deployTxScript = NeoTools.Disassemble(deployTx.script); for (int i = 1; i < deployTxScript.Count; i++) { var instruction = deployTxScript[i]; if (instruction.opcode == OpCode.SYSCALL && instruction.data != null) { var method = Encoding.ASCII.GetString(instruction.data); if (method == "Neo.Contract.Create") { Console.WriteLine($"method == Neo.Contract.Create"); var prevInstruction = deployTxScript[i - 1]; this._contractBytecode = prevInstruction.data; this._contractScriptHash = _contractBytecode.ToScriptHash(); Console.WriteLine($"_contractBytecode: {_contractBytecode.Length}\tcontractScriptHash: {this._contractScriptHash.ToString()}"); break; } } } }
public override Dictionary <string, List <UnspentEntry> > GetUnspent(UInt160 hash) { var result = new Dictionary <string, List <UnspentEntry> >(); var account = Chain.GetAccount(hash); foreach (var entry in account.unspent) { var tx = Chain.GetTransaction(entry.prevHash); var output = tx.outputs[entry.prevIndex]; var unspent = new UnspentEntry() { index = entry.prevIndex, hash = entry.prevHash, value = output.value }; var symbol = NeoAPI.SymbolFromAssetID(output.assetID); List <UnspentEntry> list; if (result.ContainsKey(symbol)) { list = result[symbol]; } else { list = new List <UnspentEntry>(); result[symbol] = list; } list.Add(unspent); } return(result); }
public TokenSwapper(Spook node, PhantasmaKeys swapKey, NeoAPI neoAPI, EthAPI ethAPI, BigInteger minFee, string[] supportedPlatforms) { this.Node = node; this.SwapKeys = swapKey; this.OracleReader = Nexus.GetOracleReader(); this.MinimumFee = minFee; this.neoAPI = neoAPI; this.ethAPI = ethAPI; this.Storage = new KeyStoreStorage(Nexus.CreateKeyStoreAdapter("swaps")); this.interopBlocks = new Dictionary <string, BigInteger>(); interopBlocks[DomainSettings.PlatformName] = BigInteger.Parse(Settings.Oracle.PhantasmaInteropHeight); interopBlocks["neo"] = BigInteger.Parse(Settings.Oracle.NeoInteropHeight); interopBlocks["ethereum"] = BigInteger.Parse(Settings.Oracle.EthInteropHeight); _supportedPlatforms.Add(DomainSettings.PlatformName); foreach (var entry in supportedPlatforms) { if (_supportedPlatforms.Contains(entry)) { throw new SwapException($"Duplicated swap platform {entry}, check config"); } if (!interopBlocks.ContainsKey(entry)) { throw new SwapException($"Unknown swap platform {entry}, check config"); } _supportedPlatforms.Add(entry); } }
public static Tuple <InteropBlock, InteropTransaction[]> MakeInteropBlock(Logger logger, NeoBlock block, NeoAPI api, string[] swapAddresses, string coldStorage) { List <Hash> hashes = new List <Hash>(); //logger.Debug($"Read block {block.Height} with hash {block.Hash}"); // if the block has no swap tx, it's currently not of interest bool blockOfInterest = false; List <InteropTransaction> interopTransactions = new List <InteropTransaction>(); foreach (var tx in block.transactions) { if (tx.type == TransactionType.InvocationTransaction || tx.type == TransactionType.ContractTransaction) { var interopTx = MakeInteropTx(logger, tx, api, swapAddresses, coldStorage); if (interopTx.Hash != Hash.Null) { interopTransactions.Add(interopTx); hashes.Add(Hash.FromBytes(tx.Hash.ToArray())); blockOfInterest = true; } } } InteropBlock iBlock = (blockOfInterest) ? new InteropBlock("neo", "neo", Hash.Parse(block.Hash.ToString()), hashes.ToArray()) : new InteropBlock("neo", "neo", Hash.Null, hashes.ToArray()); return(Tuple.Create(iBlock, interopTransactions.ToArray())); }
public TokenSwapper(Spook node, PhantasmaKeys swapKey, NeoAPI neoAPI, EthAPI ethAPI, EthAPI bscAPI, BigInteger minFee) { this.Node = node; this.SwapKeys = swapKey; this.OracleReader = Nexus.GetOracleReader(); this.MinimumFee = minFee; this.neoAPI = neoAPI; this.ethAPI = ethAPI; this.bscAPI = bscAPI; this.Storage = new KeyStoreStorage(Nexus.CreateKeyStoreAdapter("swaps")); this._interopBlocks = new Dictionary <SwapPlatformChain, BigInteger>(); foreach (var platform in Settings.Oracle.SwapPlatforms) { _interopBlocks[platform.Chain] = platform.InteropHeight; } var inProgressMap = new StorageMap(InProgressTag, this.Storage); Console.WriteLine($"inProgress count: {inProgressMap.Count()}"); inProgressMap.Visit <Hash, string>((key, value) => { if (!string.IsNullOrEmpty(value)) { Console.WriteLine($"inProgress: {key} - {value}"); } }); }
void Start() { this.api = NeoRPC.ForTestNet(); this.keys = new KeyPair("a9e2b5436cab6ff74be2d5c91b8a67053494ab5b454ac2851f872fb0fd30ba5e".HexToBytes()); this.addressLabel.text = keys.address; this.balanceLabel.text = "Please wait, syncing balance..."; }
public NeoInterop(TokenSwapper swapper, string wif, BigInteger blockHeight, NeoAPI neoAPI, NeoScanAPI neoscanAPI, Logger logger) : base(swapper, wif, "neo") { this._blockHeight = blockHeight; this.neoscanAPI = neoscanAPI; this.neoAPI = neoAPI; this.logger = logger; }
IEnumerator SyncBalance() { yield return(new WaitForSeconds(2)); var balances = NeoAPI.GetBalance(NeoAPI.Net.Test, this.keys.address); this.balance = balances.ContainsKey(assetSymbol) ? balances[assetSymbol] : 0; this.state = WalletState.Update; }
public static uint FindBlock(NeoAPI api, DateTime date) { uint min = 0; var max = api.GetBlockHeight(); var timestamp = date.ToTimestamp(); return(FindBlock(api, timestamp, min, max)); }
/// <summary> /// Returns only the base64 string of an image /// </summary> /// <param name="id"></param> /// <returns></returns> public IActionResult Img(string id) { //Get base64string for this id from the NEO blockchain var image = NeoAPI.getStorage(NeoAPI.Net.Test, _scriptHash, id); //Check if we find an image if (image == null || image.Value == null) { return(new NotFoundResult()); } return(Content(image.Value)); }
public BridgeManager(NeoAPI api, ISwarm swarm, KeyPair owner_keys, UInt160 contract_hash, uint lastBlock) { this.neo_api = api; this.swarm = swarm; this.owner_keys = owner_keys; this.bluzelle_contract_hash = contract_hash; this.listenerVM = new SnapshotVM(this); // TODO: The last block should persistent between multiple sessions, in order to not miss any block this.lastBlock = lastBlock; }
public Mailbox(KeyPair keys) { this.name = null; this.keys = keys; var script = NeoAPI.GenerateScript(Protocol.scriptHash, "getMailboxFromAddress", new object[] { this.keys.CompressedPublicKey }); var invoke = NeoAPI.TestInvokeScript(Protocol.net, script); if (invoke.result is byte[]) { this.name = System.Text.Encoding.ASCII.GetString((byte[])invoke.result); } }
public IActionResult Upload(IFormFile formFile, UploadResultViewModel model) { if (model == null) { model = new UploadResultViewModel(); } //Check submitted file if (formFile != null && formFile.Length > 0) { using (var fileStream = formFile.OpenReadStream()) { using (Image <Rgba32> image = Image.Load(fileStream)) { //Resize and create Base64 string image.Mutate(x => x .Resize(80, 80)); model.Image = image.ToBase64String(ImageFormats.Png); } } } else if (!string.IsNullOrEmpty(model.Image) && !string.IsNullOrEmpty(model.Address)) { try { //Submit base64 image to smartcontract var script = NeoAPI.GenerateScript(_scriptHash, "add", new object[] { model.Address, model.Image }); var invoke = NeoAPI.TestInvokeScript(NeoAPI.Net.Test, script); //Check result if (invoke.result is byte[]) { var textresult = System.Text.Encoding.ASCII.GetString((byte[])invoke.result); } } catch { } //Get hash //string sha1hash = Sha1Hash(model.Address); //return RedirectToAction("Preview", new { id = sha1hash }); return(View("Preview", new PreviewViewModel() { Image = model.Image })); } return(View(model)); }
private void MergeTransaction(NeoAPI api, Transaction tx) { transactions[tx.Hash] = tx; foreach (var input in tx.inputs) { if (!transactions.ContainsKey(input.prevHash)) { var other = api.GetTransaction(input.prevHash); transactions[other.Hash] = other; external_txs.Add(other.Hash); } } }
IEnumerator SyncBalance() { if (loggedIn) { yield return(new WaitForSeconds(2)); Debug.Log("getting balance for address: " + keys.address); var balances = NeoAPI.GetBalance(NeoAPI.Net.Test, keys.address); balance = balances.ContainsKey(assetSymbol) ? balances [assetSymbol] : 0; state = WalletState.Update; } }
private Message FetchMessage(int index) { var script = NeoAPI.GenerateScript(Protocol.scriptHash, "getMailContent", new object[] { this.name, index }); var invoke = NeoAPI.TestInvokeScript(Protocol.net, script); if (invoke.result is byte[]) { var hash = System.Text.Encoding.ASCII.GetString((byte[])invoke.result); var msg = Message.FromHash(hash); return(msg); } return(null); }
public bool RegisterName(string name) { if (!string.IsNullOrEmpty(this.name)) { throw new Exception("Name already set"); } var result = NeoAPI.CallContract(NeoAPI.Net.Test, keys, Protocol.scriptHash, "registerMailbox", new object[] { this.keys.CompressedPublicKey, name }); if (result) { this.name = name; } return(result); }
private void OnEnable() { //this.key = KeyPair.FromWIF("KxGdjJNUn5zk7aG88LD1bmBrJx5HEJMLkStQ66i5kEZbPRKuExNn"); PlayerKeyPair.Value = KeyPair.FromWIF("KxGdjJNUn5zk7aG88LD1bmBrJx5HEJMLkStQ66i5kEZbPRKuExNn"); this.API = new GameRPC(30333, 4000, "http://" + RpcIP); this.nep5 = new NEP5(this.API, nep5ContractHash); this.PlayerKeyPair.DistinctUntilChanged().Where(kp => kp != null).Subscribe(keyPair => { this.addressText.text = keyPair.address; this.neoBalanceText.text = "Balance: Please wait, syncing balance..."; this.gasBalanceText.text = "Balance: Please wait, syncing balance..."; this.nep5BalanceText.text = "Balance: Please wait, syncing balance..."; StartCoroutine(SyncBalance()); }).AddTo(this); }
/// <summary> /// Preview an image /// </summary> /// <param name="id"></param> /// <returns></returns> public IActionResult Preview(string id) { //Get base64string for this id from the NEO blockchain var image = NeoAPI.getStorage(NeoAPI.Net.Test, _scriptHash, id); //Check if we find an image if (image == null || image.Value == null) { return(new NotFoundResult()); } PreviewViewModel model = new PreviewViewModel(); model.Image = image.Value; return(View(model)); }
public NeoInterop(TokenSwapper swapper, NeoAPI neoAPI, PBigInteger interopBlockHeight, bool quickSync) : base(swapper, NeoWallet.NeoPlatform) { string lastBlockHeight = OracleReader.GetCurrentHeight("neo", "neo"); if (string.IsNullOrEmpty(lastBlockHeight)) { OracleReader.SetCurrentHeight("neo", "neo", new BigInteger(interopBlockHeight.ToUnsignedByteArray()).ToString()); } this.quickSync = quickSync; Logger.Message($"interopHeight: {OracleReader.GetCurrentHeight("neo", "neo")}"); this.neoAPI = neoAPI; this.lastScan = DateTime.UtcNow.AddYears(-1);; }
public BridgeManager(NeoAPI api, ISwarm swarm, string ownerWIF, string contractPath) { this.neo_api = api; this.swarm = swarm; this.owner_keys = KeyPair.FromWIF(ownerWIF); if (File.Exists(contractPath)) { this.contract_bytecode = File.ReadAllBytes(contractPath); this.bluzelle_contract_hash = contract_bytecode.ToScriptHash(); } else { throw new Exception($"Could not find contract avm at location {contractPath}"); } this.listenerVM = new SnapshotVM(this); }
private void button1_Click(object sender, EventArgs e) { if (privateKeyInput.Text.Length == 52) { keyPair = KeyPair.FromWIF(privateKeyInput.Text); } else if (privateKeyInput.Text.Length == 64) { var keyBytes = privateKeyInput.Text.HexToBytes(); keyPair = new KeyPair(keyBytes); } else { MessageBox.Show("Invalid key input, must be 104 or 64 hexdecimal characters."); return; } var net = netComboBox.SelectedItem.ToString(); switch (net) { case "Test": api = NeoDB.ForTestNet(); break; case "Main": api = NeoDB.ForMainNet(); break; default: { MessageBox.Show("Invalid net."); return; } } tabs.TabPages.Remove(loginPage); tabs.TabPages.Add(loadingPage); timer1.Enabled = true; var task = new Task(() => OpenWallet()); task.Start(); }