Example #1
0
        private void LoadDataFromFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (File.Exists(path))
            {
                MainForm.targetAVMPath = path;

                var bytes = File.ReadAllBytes(path);

                var mapFileName = path.Replace(".avm", ".neomap");

                debugMode      = DebugMode.Assembly;
                sourceLanguage = SourceLanguageKind.Other;

                if (File.Exists(mapFileName))
                {
                    map = new NeoMapFile();
                    map.LoadFromFile(mapFileName);
                }
                else
                {
                    map = null;
                }

                this.debugger = new NeoDebugger(bytes);
                this.avm_asm  = NeoDisassembler.Disassemble(bytes);

                if (map != null && map.Entries.Any())
                {
                    var srcFile = map.Entries.FirstOrDefault().url;

                    FileName.Text = srcFile;

                    sourceLanguage = LanguageSupport.DetectLanguage(srcFile);

                    debugMode = DebugMode.Source;
                    debugContent[DebugMode.Source] = File.ReadAllText(srcFile);
                }

                debugContent[DebugMode.Assembly] = avm_asm.ToString();
                FileName.Text = Path.GetFileName(path);

                ReloadTextArea();

                StorageLoad();

                UpdateSourceViewMenus();

                shouldReset = true;
            }
        }
        private void LoadDataFromFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (File.Exists(path))
            {
                var bytes = File.ReadAllBytes(path);

                var mapFileName = path.Replace(".avm", ".neomap");

                debugMode = DebugMode.Assembly;

                if (File.Exists(mapFileName))
                {
                    map = new NeoMapFile();
                    map.LoadFromFile(mapFileName);
                }
                else
                {
                    map = null;
                }

                this.debugger = new NeoDebugger(bytes);
                this.avm_asm  = NeoDisassembler.Disassemble(bytes);


                if (map != null && map.Entries.Any())
                {
                    var srcFile = map.Entries.FirstOrDefault().url;
                    FileName.Text = srcFile;
                    debugMode     = DebugMode.Source;
                    debugContent[DebugMode.Source] = File.ReadAllText(srcFile);
                }

                debugContent[DebugMode.Assembly] = avm_asm.ToString();
                FileName.Text = Path.GetFileName(path);

                TextArea.Text     = debugContent[debugMode];
                TextArea.ReadOnly = true;

                shouldReset = true;
            }
        }
Example #3
0
        public int ResolveLine(int ofs, bool useMap, out string filePath)
        {
            if (useMap)
            {
                var line = _map.ResolveLine(ofs, out filePath);
                return(line - 1);
            }
            else
            {
                AVMDisassemble disasm;

                var executingBytecode = _emulator.GetExecutingByteCode();
                if (executingBytecode == null)
                {
                    throw new Exception("Cannot resolve line");
                }

                if (executingBytecode.SequenceEqual(_emulator.ContractByteCode))
                {
                    filePath = AvmFilePath;
                }
                else
                {
                    filePath = inputAVMPath;
                }

                if (_disassembles.ContainsKey(executingBytecode))
                {
                    disasm = _disassembles[executingBytecode];
                }
                else
                {
                    disasm = NeoDisassembler.Disassemble(executingBytecode);
                    _disassembles[executingBytecode] = disasm;
                    _debugContent[filePath]          = disasm.ToString();
                }

                var line = disasm.ResolveLine(ofs);

                return(line);
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine($"{AppDomain.CurrentDomain.FriendlyName} <filename.avm>");
                Environment.Exit(-1);
            }

            var fileName = args[0];

            if (!File.Exists(fileName))
            {
                Console.WriteLine($"{fileName} was not found");
                Environment.Exit(-1);
            }

            var bytes   = File.ReadAllBytes(fileName);
            var avm_asm = NeoDisassembler.Disassemble(bytes);

            var output = avm_asm.ToString();

            Console.WriteLine(output);
        }
Example #5
0
        public bool LoadAvmFile(string avmPath)
        {
            //Decide what we need to open
            if (!String.IsNullOrEmpty(avmPath)) //use the explicit file provided
            {
                _avmFilePath = avmPath;
            }
            else if (!String.IsNullOrEmpty(Settings.lastOpenedFile)) //fallback to last opened
            {
                _avmFilePath = Settings.lastOpenedFile;
            }
            else
            {
                return(false); //We don't know what to open, just let the user specify with another call
            }
            //Housekeeping - let's find out what files we have and make sure we're good
            if (!File.Exists(_avmFilePath))
            {
                Log("File not found. " + avmPath);
                return(false);
            }

            _debugContent.Clear();

            _contractName     = Path.GetFileNameWithoutExtension(_avmFilePath);
            _contractByteCode = File.ReadAllBytes(_avmFilePath);
            _map = new NeoMapFile();
            try
            {
                avmDisassemble = NeoDisassembler.Disassemble(_contractByteCode);
                _disassembles[_contractByteCode] = avmDisassemble;
            }
            catch (DisassembleException e)
            {
                Log($"Disassembler Error: {e.Message}");
                return(false);
            }

            if (File.Exists(_abiFilePath))
            {
                _ABI = new ABI(_abiFilePath);
            }
            else
            {
                _ABI = new ABI();
                Log($"Warning: {_abiFilePath} was not found. Please recompile your AVM with the latest compiler.");
            }

            //Let's see if we have source code we can map
            if (File.Exists(_mapFilePath))
            {
                _map.LoadFromFile(_mapFilePath, _contractByteCode);
            }
            else
            {
                _map = null;

                if (File.Exists(_oldMapFilePath))
                {
                    Log("Old map file format found.  Please recompile your avm with the latest compiler.");
                }
                else
                {
                    Log($"Warning: Could not find {_mapFilePath}");
                }
            }

            if (_map != null)
            {
                foreach (var entry in _map.FileNames)
                {
                    if (string.IsNullOrEmpty(entry))
                    {
                        continue;
                    }

                    if (!File.Exists(entry))
                    {
                        Log($"Warning: Could not load the source code, check that this file exists: {entry}");
                        continue;
                    }

                    var sourceCode = File.ReadAllText(entry);
                    _debugContent[entry] = sourceCode;
                }
            }

            //We always should have the assembly content
            _debugContent[_avmFilePath] = avmDisassemble.ToString();

            //Save the settings
            Settings.lastOpenedFile = avmPath;
            Settings.Save();
            _avmFileLoaded = true;

            //Force a reset now that we're loaded
            _resetFlag = true;

            _currentFilePath = avmPath;

            return(true);
        }
Example #6
0
        public static InteropTransaction MakeInteropTx(Logger logger, NeoTx tx, NeoAPI api, string[] origSwapAddresses,
                                                       string coldStorage)
        {
            logger.Debug("checking tx: " + tx.Hash);
            var swapAddresses = new List <Address>();

            foreach (var addr in origSwapAddresses)
            {
                swapAddresses.Add(NeoWallet.EncodeAddress(addr));
            }

            List <InteropTransfer> interopTransfers = new List <InteropTransfer>();

            var emptyTx = new InteropTransaction(Hash.Null, interopTransfers.ToArray());

            PBigInteger amount;
            var         witness = tx.witnesses.ElementAtOrDefault(0);

            if (witness == null)
            {
                // tx has no witness
                return(emptyTx);
            }

            var interopAddress = witness.ExtractAddress();

            if (tx.witnesses.Length != 1 || interopAddress == Address.Null || interopAddress == null)
            {
                //currently only one witness allowed
                // if ExtractAddress returns Address.Null, the tx is not properly signed
                return(emptyTx);
            }

            var sourceScriptHash = witness.verificationScript.Sha256().RIPEMD160();
            var sourceAddress    = NeoWallet.EncodeByteArray(sourceScriptHash);
            var sourceDecoded    = NeoWallet.DecodeAddress(sourceAddress);

            if (sourceAddress == interopAddress || sourceDecoded == coldStorage)
            {
                logger.Warning("self send tx or cold storage transfer found, ignoring: " + tx.Hash);
                // self send, probably consolidation tx, ignore
                return(emptyTx);
            }

            //logger.Debug("interop address: " + interopAddress);
            //logger.Debug("xswapAddress: " + swapAddress);
            //logger.Debug("interop sourceAddress: " + sourceAddress);
            //logger.Debug("neo sourceAddress: " + NeoWallet.DecodeAddress(sourceAddress));

            if (tx.attributes != null && tx.attributes.Length > 0)
            {
                foreach (var attr in tx.attributes)
                {
                    if (attr.Usage == TransactionAttributeUsage.Description)
                    {
                        try
                        {
                            var text = Encoding.UTF8.GetString(attr.Data);
                            if (Address.IsValidAddress(text))
                            {
                                interopAddress = Address.FromText(text);
                                //logger.Debug("new interop address: " + interopAddress);
                            }
                        }
                        catch {}
                    }
                }
            }

            if (tx.outputs.Length > 0)
            {
                foreach (var output in tx.outputs)
                {
                    var targetAddress = NeoWallet.EncodeByteArray(output.scriptHash.ToArray());
                    //logger.Debug("interop targetAddress : " + targetAddress);
                    //logger.Debug("neo targetAddress: " + NeoWallet.DecodeAddress(targetAddress));
                    //logger.Debug("interopSwapAddress: " + interopSwapAddress);
                    //logger.Debug("targetAddress: " + targetAddress);

                    //var swpAddress = NeoWallet.EncodeAddress(swapAddress);
                    //logger.Debug("interop swpAddress: " + swpAddress);
                    //logger.Debug("neo swpAddress: " + NeoWallet.DecodeAddress(swpAddress));
                    //if (targetAddress.ToString() == swapAddress)
                    if (swapAddresses.Contains(targetAddress))
                    {
                        var token = FindSymbolFromAsset(new UInt256(output.assetID).ToString());
                        CryptoCurrencyInfo tokenInfo;
                        if (NeoTokenInfo.TryGetValue(token, out tokenInfo))
                        {
                            amount = Phantasma.Numerics.UnitConversion.ToBigInteger(
                                output.value, tokenInfo.Decimals);
                        }
                        else
                        {
                            // asset not swapable at the moment...
                            //logger.Debug("Asset not swapable");
                            return(emptyTx);
                        }

                        //logger.Debug("UTXO " + amount);
                        interopTransfers.Add
                        (
                            new InteropTransfer
                            (
                                NeoWallet.NeoPlatform,
                                sourceAddress,
                                DomainSettings.PlatformName,
                                targetAddress,
                                interopAddress, // interop address
                                token.ToString(),
                                amount
                            )
                        );
                    }
                }
            }

            if (tx.script != null && tx.script.Length > 0) // NEP5 transfers
            {
                var script = NeoDisassembler.Disassemble(tx.script, true);

                //logger.Debug("SCRIPT ====================");
                //foreach (var entry in script.lines)
                //{
                //    logger.Debug($"{entry.name} : { entry.opcode }");
                //}
                //logger.Debug("SCRIPT ====================");

                if (script.lines.Count() < 7)
                {
                    //logger.Debug("NO SCRIPT!!!!");
                    return(emptyTx);
                }

                var disasmEntry = script.lines.ElementAtOrDefault(6);

                //if ( disasmEntry == null )
                //{
                //    logger.Debug("disasmEntry is null");
                //}
                //if ( disasmEntry != null )
                //{
                //    if ( disasmEntry.data == null)
                //        logger.Debug("disasmEntry.data is 0");
                //}

                if (disasmEntry.name != "APPCALL" || disasmEntry.data == null || disasmEntry.data.Length == 0)
                {
                    //logger.Debug("NO APPCALL");
                    return(emptyTx);
                }
                else
                {
                    var assetString = new UInt160(disasmEntry.data).ToString();
                    if (string.IsNullOrEmpty(assetString) || FindSymbolFromAsset(assetString) == null)
                    {
                        //logger.Debug("Ignore TX due to non swapable token.");
                        return(emptyTx);
                    }
                }

                int pos = 0;
                foreach (var entry in script.lines)
                {
                    pos++;
                    if (pos > 3)
                    {
                        // we are only interested in the first three elements
                        break;
                    }

                    if (entry.data == null || entry.data.Length == 0)
                    {
                        logger.Debug("Ignore tx, invalid data field: " + tx);
                        return(emptyTx);
                    }

                    if (pos == 1)
                    {
                        amount = PBigInteger.FromUnsignedArray(entry.data, true);
                    }
                    if (pos == 2 || pos == 3)
                    {
                        if (pos == 2)
                        {
                            if (entry.data == null || entry.data.Length == 0)
                            {
                                logger.Debug("Invalid op on pos 2, ignoring tx: " + tx);
                                return(emptyTx);
                            }
                            var targetScriptHash = new UInt160(entry.data);
                            //logger.Debug("neo targetAddress: " + targetScriptHash.ToAddress());
                            var targetAddress = NeoWallet.EncodeByteArray(entry.data);
                            //logger.Debug("targetAddress : " + targetAddress);
                            //logger.Debug("interopSwapAddress: " + interopSwapAddress);
                            //logger.Debug("SwapAddress: " + swapAddress);
                            if (swapAddresses.Contains(targetAddress))
                            {
                                // found a swap, call getapplicationlog now to get transaction details and verify the tx was actually processed.
                                ApplicationLog[] appLogs = null;
                                try
                                {
                                    appLogs = api.GetApplicationLog(tx.Hash);
                                }
                                catch (Exception e)
                                {
                                    logger.Error("Getting application logs failed: " + e.Message);
                                    return(new InteropTransaction(Hash.Null, interopTransfers.ToArray()));
                                }

                                if (appLogs != null)
                                {
                                    for (var i = 0; i < appLogs.Length; i++)
                                    {
                                        //logger.Debug("appLogs[i].contract" + appLogs[i].contract);
                                        var token = FindSymbolFromAsset(appLogs[i].contract);
                                        //logger.Debug("TOKEN::::::::::::::::::: " + token);
                                        //logger.Debug("amount: " + appLogs[i].amount + " " + token);
                                        var sadd = NeoWallet.EncodeByteArray(appLogs[i].sourceAddress.ToArray());
                                        var tadd = NeoWallet.EncodeByteArray(appLogs[i].targetAddress.ToArray());


                                        interopTransfers.Add
                                        (
                                            new InteropTransfer
                                            (
                                                "neo", // todo Pay.Chains.NeoWallet.NeoPlatform
                                                       //NeoWallet.EncodeByteArray(appLogs[i].sourceAddress.ToArray()),
                                                sourceAddress,
                                                DomainSettings.PlatformName,
                                                targetAddress,
                                                interopAddress, // interop address
                                                token,
                                                appLogs[i].amount
                                            )
                                        );
                                    }
                                }
                                else
                                {
                                    logger.Warning("Neo swap is found but application log is not available for tx " + tx.Hash);
                                }
                            }
                        }
                        else
                        {
                            //TODO reverse swap
                            sourceScriptHash = new UInt160(entry.data).ToArray();
                            sourceAddress    = NeoWallet.EncodeByteArray(sourceScriptHash.ToArray());
                        }
                    }
                }
            }

            var total = interopTransfers.Count();

            if (total > 0)
            {
                logger.Message($"Found {total} swaps in neo tx {tx.Hash}");
            }
            else
            {
                logger.Debug($"No swaps in neo tx {tx.Hash}");
            }

            return((interopTransfers.Count() > 0)
                ? new InteropTransaction(Hash.Parse(tx.Hash.ToString()), interopTransfers.ToArray())
                : new InteropTransaction(Hash.Null, interopTransfers.ToArray()));
        }
Example #7
0
        public void LoadDataFromFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (!File.Exists(path))
            {
                MessageBox.Show("Can't find '" + (String.IsNullOrEmpty(path) ? "(null)" : path + "'"), this.Text + " - " + Environment.CurrentDirectory);
            }
            else
            {
                MainForm.targetAVMPath = path;

                this.contractName = Path.GetFileNameWithoutExtension(path);

                this.contractBytecode = File.ReadAllBytes(path);

                var oldMapFileName = path.Replace(".avm", ".neomap");
                var newMapFileName = path.Replace(".avm", ".debug.json");

                debugMode      = DebugMode.Assembly;
                sourceLanguage = SourceLanguageKind.Other;

                if (File.Exists(newMapFileName))
                {
                    map = new NeoMapFile();
                    map.LoadFromFile(newMapFileName, contractBytecode);

                    this.contractName = map.contractName;
                }
                else
                {
                    if (File.Exists(oldMapFileName))
                    {
                        MessageBox.Show("Warning: The file format of debug map changed. Please recompile your AVM with the latest compiler.");
                    }
                    map = null;
                }

                string abiFilename = path.Replace(".avm", ".abi.json");
                if (File.Exists(abiFilename))
                {
                    abi = new ABI(abiFilename);
                }
                else
                {
                    MessageBox.Show($"Error: {abiFilename} was not found. Please recompile your AVM with the latest compiler.");
                    return;
                }

                this.debugger = null;
                this.avm_asm  = NeoDisassembler.Disassemble(contractBytecode);

                if (map != null && map.Entries.Any())
                {
                    var srcFile = map.Entries.FirstOrDefault().url;

                    if (string.IsNullOrEmpty(srcFile))
                    {
                        MessageBox.Show("Error: Could not load the debug map correct, no file entries.");
                        return;
                    }

                    if (!File.Exists(srcFile))
                    {
                        MessageBox.Show("Error: Could not load the source code, check that this file exists:" + srcFile);
                        return;
                    }

                    FileName.Text = srcFile;

                    sourceLanguage = LanguageSupport.DetectLanguage(srcFile);

                    debugMode = DebugMode.Source;
                    debugContent[DebugMode.Source] = File.ReadAllText(srcFile);
                }

                debugContent[DebugMode.Assembly] = avm_asm.ToString();
                FileName.Text = Path.GetFileName(path);

                ReloadTextArea();

                BlockchainLoad();

                UpdateSourceViewMenus();

                shouldReset = true;

                settings.lastOpenedFile = path;
                settings.Save();
            }
        }
        public bool LoadAvmFile(string avmPath)
        {
            //Decide what we need to open
            if (!String.IsNullOrEmpty(avmPath)) //use the explicit file provided
            {
                _avmFilePath = avmPath;
            }
            else if (!String.IsNullOrEmpty(_settings.lastOpenedFile)) //fallback to last opened
            {
                _avmFilePath = _settings.lastOpenedFile;
            }
            else
            {
                return(false); //We don't know what to open, just let the user specify with another call
            }
            //Housekeeping - let's find out what files we have and make sure we're good
            if (!File.Exists(_avmFilePath))
            {
                Log("File not found. " + avmPath);
                return(false);
            }
            else if (File.Exists(_oldMapFilePath))
            {
                Log("Old map file format found.  Please recompile your avm with the latest compiler.");
                return(false);
            }

            _debugContent     = new Dictionary <DebugMode, string>();
            _mode             = DebugMode.Assembly;
            _language         = SourceLanguage.Other;
            _contractName     = Path.GetFileNameWithoutExtension(_avmFilePath);
            _contractByteCode = File.ReadAllBytes(_avmFilePath);
            _map = new NeoMapFile();
            try
            {
                _avmAsm = NeoDisassembler.Disassemble(_contractByteCode);
            }
            catch (DisassembleException e)
            {
                Log($"Disassembler Error: {e.Message}");
                return(false);
            }

            if (File.Exists(_abiFilePath))
            {
                _aBI = new ABI(_abiFilePath);
            }
            else
            {
                _aBI = new ABI();
                Log($"Warning: {_abiFilePath} was not found. Please recompile your AVM with the latest compiler.");
            }

            //We always should have the assembly content
            _debugContent[DebugMode.Assembly] = _avmAsm.ToString();

            //Let's see if we have source code we can map
            if (File.Exists(_mapFilePath))
            {
                _map.LoadFromFile(_mapFilePath, _contractByteCode);
            }
            else
            {
                _map = null;
                Log($"Warning: Could not find {_mapFilePath}");
                //return false;
            }

            if (_map != null && _map.Entries.Any())
            {
                _srcFileName = _map.Entries.FirstOrDefault().url;
                if (string.IsNullOrEmpty(_srcFileName))
                {
                    throw new Exception("Error: Could not load the debug map correctly, no source file specified in map.");
                }
                if (!File.Exists(_srcFileName))
                {
                    throw new Exception($"Error: Could not load the source code, check that this file exists: {_srcFileName}");
                }

                _debugContent[DebugMode.Source] = File.ReadAllText(_srcFileName);
                _language = LanguageSupport.DetectLanguage(_srcFileName);
                _mode     = DebugMode.Source;
            }

            //Save the settings
            _settings.lastOpenedFile = avmPath;
            _settings.Save();
            _avmFileLoaded = true;

            //Force a reset now that we're loaded
            _resetFlag = true;

            return(true);
        }