示例#1
0
        public void OptimizerRuns(Legacy.SolcVersion solcVersion)
        {
            var libPath     = Legacy.LibPath.GetLibPath(solcVersion);
            var libProvider = new SolcLibDefaultProvider(libPath);
            var solcLib     = new SolcLib(libProvider);

            OutputDescription CompileWithRuns(Optimizer optimizer)
            {
                var exampleContract = "TestContracts/ExampleContract.sol";
                var sourceContent   = new Dictionary <string, string>();
                var output          = solcLib.Compile(exampleContract, OutputType.EvmBytecodeObject, optimizer: optimizer, soliditySourceFileContent: sourceContent);

                return(output);
            }

            var runs1 = CompileWithRuns(new Optimizer {
                Enabled = true, Runs = 1
            });
            var sizeRuns1 = runs1.ContractsFlattened[0].Contract.Evm.Bytecode.Object.Length;

            var runs200 = CompileWithRuns(new Optimizer {
                Enabled = true, Runs = 200
            });
            var sizeRuns200 = runs200.ContractsFlattened[0].Contract.Evm.Bytecode.Object.Length;

            var runsDisabled = CompileWithRuns(new Optimizer {
                Enabled = false
            });
            var sizeRunsDisabled = runsDisabled.ContractsFlattened[0].Contract.Evm.Bytecode.Object.Length;

            Assert.IsTrue(sizeRunsDisabled > sizeRuns200);
            Assert.IsTrue(sizeRuns1 < sizeRuns200);
        }
示例#2
0
 public void CompileAll()
 {
     var sourceContent = new Dictionary <string, string>();
     var contractFiles = Directory.GetFiles("OpenZeppelin", "*.sol", SearchOption.AllDirectories);
     var solc          = new SolcLib();
     var output        = solc.Compile(contractFiles, OutputType.EvmDeployedBytecodeSourceMap, errorHandling: CompileErrorHandling.ThrowOnError, soliditySourceFileContent: sourceContent);
 }
示例#3
0
        private CodebaseGenerator(CommandArgs appArgs, bool returnFullSources, LoggerDelegate logger)
        {
            _logger            = logger;
            _assemblyVersion   = typeof(Program).Assembly.GetName().Version.ToString();
            _returnFullSources = returnFullSources;
            _genResults        = new SolCodeGenResults();

            // Normalize source directory
            _solSourceDirectory = Path.GetFullPath(appArgs.SolSourceDirectory);

            // If we were passed a single sol file rather than a source directory
            if (_solSourceDirectory.EndsWith(".sol", StringComparison.OrdinalIgnoreCase) && File.Exists(_solSourceDirectory))
            {
                _solSourceSingleFile = _solSourceDirectory;
                _solSourceDirectory  = Path.GetDirectoryName(_solSourceDirectory);
            }

            // Match the solc file path output format which replaces Windows path separator characters with unix style.
            if (Path.DirectorySeparatorChar == '\\')
            {
                _solSourceDirectory = _solSourceDirectory.Replace('\\', '/');
            }

            if (string.IsNullOrWhiteSpace(appArgs.OutputDirectory))
            {
                string sourceFilesParentDir = Directory.GetParent(_solSourceDirectory).FullName;
                _generatedContractsDirectory = Path.Combine(sourceFilesParentDir, GeneratedContractsDefaultDirectory);
            }
            else
            {
                _generatedContractsDirectory = Path.GetFullPath(appArgs.OutputDirectory);
            }

            if (string.IsNullOrWhiteSpace(appArgs.AssemblyOutputDirectory))
            {
                string sourceFilesParentDir = Directory.GetParent(_solSourceDirectory).FullName;
                _generatedAssemblyDirectory = Path.Combine(sourceFilesParentDir, GeneratedAssemblyDefaultDirectory);
            }
            else
            {
                _generatedAssemblyDirectory = Path.GetFullPath(appArgs.AssemblyOutputDirectory);
            }

            if (_solSourceSingleFile != null)
            {
                _solSourceDirectory = string.Empty;
            }

            if (!string.IsNullOrEmpty(appArgs.LegacySolcPath))
            {
                _legacySolcPath = Path.GetFullPath(appArgs.LegacySolcPath);
            }

            _namespace               = appArgs.Namespace;
            _solcVersion             = appArgs.SolcVersion;
            _solcOptimzer            = appArgs.SolcOptimizer;
            _solcLib                 = SetupSolcLib();
            _solidityCompilerVersion = _solcLib.Version.ToString(3);
        }
示例#4
0
        public void NativeLibPathTests(IInteropLibProvider nativeSolcLib)
        {
            var solcLib       = new SolcLib(nativeSolcLib.InteropLib, CONTRACT_SRC_DIR);
            var nativeLibPath = solcLib.NativeLibFilePath;

            Assert.IsTrue(!string.IsNullOrEmpty(nativeLibPath));
            Assert.IsTrue(File.Exists(nativeLibPath));
        }
示例#5
0
        SolcLib SetupSolcLib()
        {
            SolcLibDefaultProvider solcNativeLibProvider = null;

            if (_solcVersion != null)
            {
                if (!string.IsNullOrEmpty(_legacySolcPath))
                {
                    try
                    {
                        var legacyNativeLibPath = LegacySolcNet.ResolveNativeLibPath(_legacySolcPath, _solcVersion);
                        solcNativeLibProvider = new SolcLibDefaultProvider(legacyNativeLibPath);
                        var resultSolcVersion = SolcLib.ParseVersionString(solcNativeLibProvider.GetVersion());
                        if (_solcVersion != resultSolcVersion)
                        {
                            throw new Exception($"A legacy solc version ({_solcVersion}) is specified but resolver returned a different version ({resultSolcVersion})");
                        }
                    }
                    catch
                    {
                        // There was an error trying to use the specific solcversion with the legacy package,
                        // for giving up lets check if the specified solcversion is valid in the latest solcnet
                        // lib.
                        solcNativeLibProvider = new SolcLibDefaultProvider();
                        var defaultSolcVersion = SolcLib.ParseVersionString(solcNativeLibProvider.GetVersion());
                        if (_solcVersion != defaultSolcVersion)
                        {
                            // Latest version is not valid, so throw the original exception.
                            throw;
                        }
                    }
                }
                else
                {
                    solcNativeLibProvider = new SolcLibDefaultProvider();
                    var defaultSolcVersion = SolcLib.ParseVersionString(solcNativeLibProvider.GetVersion());
                    if (_solcVersion != defaultSolcVersion)
                    {
                        throw new Exception("A legacy solc version is specified but resolver lib path is not specified. Is the SolcNet.Legacy package not installed?");
                    }
                }
            }

            SolcLib solcLib;
            string  sourceDir = string.IsNullOrEmpty(_solSourceSingleFile) ? _solSourceDirectory : null;

            if (solcNativeLibProvider != null)
            {
                solcLib = new SolcLib(solcNativeLibProvider, sourceDir);
            }
            else
            {
                solcLib = SolcLib.Create(sourceDir);
            }

            _logger($"Using native libsolc version {solcLib.VersionDescription} at {solcLib.NativeLibFilePath}");
            return(solcLib);
        }
示例#6
0
        static void CompileSeveralContracts(SolcLib solcLib)
        {
            var srcs = new[] {
                "contracts/crowdsale/validation/WhitelistedCrowdsale.sol",
                "contracts/token/ERC20/StandardBurnableToken.sol"
            };

            solcLib.Compile(srcs);
        }
示例#7
0
        public void ReportedVersion(Legacy.SolcVersion solcVersion)
        {
            var libPath     = Legacy.LibPath.GetLibPath(solcVersion);
            var libProvider = new SolcLibDefaultProvider(libPath);
            var solc        = new SolcLib(libProvider);
            var ver         = solc.Version;
            var verString   = solcVersion.ToString().Replace('_', '.').TrimStart('v');

            Assert.AreEqual(verString, ver.ToString());
        }
示例#8
0
        public void Compile(Legacy.SolcVersion solcVersion)
        {
            const string CONTRACT_SRC_DIR = "LegacyContracts";
            var          libPath          = Legacy.LibPath.GetLibPath(solcVersion);
            var          libProvider      = new SolcLibDefaultProvider(libPath);
            var          solcLib          = new SolcLib(libProvider, CONTRACT_SRC_DIR);
            var          srcs             = new[] {
                "token/ERC20/StandardToken.sol"
            };

            solcLib.Compile(srcs);
        }
示例#9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Init");

            const string OPEN_ZEP_DIR = "OpenZeppelin";

            var solcLib = SolcLib.Create(OPEN_ZEP_DIR);

            var ver = solcLib.VersionDescription;

            Console.WriteLine("Loaded solc lib version: " + ver);

            var license = solcLib.License;

            var outputSelection = new[] {
                OutputType.Abi,
                OutputType.Ast,
                OutputType.EvmMethodIdentifiers,
                OutputType.EvmAssembly,
                OutputType.EvmBytecode,
                OutputType.IR,
                OutputType.DevDoc,
                OutputType.UserDoc,
                OutputType.Metadata
            };

            var srcs = new[] {
                "contracts/AddressUtils.sol",
                "contracts/Bounty.sol",
                "contracts/DayLimit.sol",
                "contracts/ECRecovery.sol",
                "contracts/LimitBalance.sol",
                "contracts/MerkleProof.sol",
                "contracts/ReentrancyGuard.sol",
                "contracts/crowdsale/Crowdsale.sol",
                "contracts/examples/SampleCrowdsale.sol",
                "contracts/examples/SimpleSavingsWallet.sol",
                "contracts/examples/SimpleToken.sol",
                "contracts/token/ERC20/StandardBurnableToken.sol",
                "contracts/token/ERC721/ERC721Token.sol",
                "contracts/token/ERC827/ERC827Token.sol"
            };

            int runs = 0;

            while (true)
            {
                var compiled = solcLib.Compile(srcs, outputSelection);
                //GC.Collect(GC.MaxGeneration);
                runs++;
                Console.WriteLine(runs);
            }
        }
示例#10
0
        public async Task <IActionResult> Deploy(DeployRequest model)
        {
            try
            {
                var gitHubClient = new GitHubClient(new ProductHeaderValue(client_id));
                gitHubClient.Credentials = new Credentials(HttpContext.Session.GetString("githubtoken"));

                IReadOnlyList <RepositoryContent> contents = await gitHubClient.Repository.Content.GetAllContentsByRef(model.Username, model.Repo, model.ContractPath, model.Branch);

                String temp = Path.GetTempPath();

                foreach (RepositoryContent content in contents.Where(c => c.Name.EndsWith(".sol")))
                {
                    using (var client = new HttpClient())
                    {
                        var stream = await client.GetStreamAsync(content.DownloadUrl);

                        using (var fileStream = System.IO.File.Create(temp + content.Name))
                            using (var reader = new StreamReader(stream))
                            {
                                stream.CopyTo(fileStream);
                                fileStream.Flush();
                            }
                    }

                    //String hash = CheckHash(temp + content.Name);
                }

                var solcLib  = SolcLib.Create("");
                var compiled = solcLib.Compile(temp + model.Contract + ".sol", outputSelection);

                var output = compiled.Contracts[temp + model.Contract + ".sol"][model.Contract];

                DeployResult result = new DeployResult()
                {
                    JSON = output.AbiJsonString,
                    ABI  = "",
                    Bin  = BitConverter.ToString(output.Evm.Bytecode.ObjectBytes).Replace("-", String.Empty)
                };

                var account = new Wallet(model.Password, null).GetAccount(Convert.ToInt32(model.KeyFile));
                var web3    = new Nethereum.Web3.Web3(account, model.Node);

                result.TxID = await web3.Eth.DeployContract.SendRequestAsync(result.Bin, model.KeyFile, new Nethereum.Hex.HexTypes.HexBigInteger(model.Gas));

                return(View(result));
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw ex;
            }
        }
示例#11
0
        public void IsReleaseVersion(IInteropLibProvider nativeSolcLib)
        {
            var solcLib = new SolcLib(nativeSolcLib.InteropLib, CONTRACT_SRC_DIR);
            var version = solcLib.VersionDescription;

            // Prerelease/develop compiled libs have a version that looks like: 0.4.24-develop.2018.7.5+commit.346b21c8
            // Release compiled libs have a version that looks like: 0.4.24+commit.8025b766
            if (version.Contains("develop") || version.Contains("night"))
            {
                Assert.Fail("Lib version is not develop / nightly: " + version);
            }
        }
示例#12
0
        public void MemLeak()
        {
            var solcLib = new SolcLib("OpenZeppelin");

            for (var j = 0; j < 1000; j++)
            {
                var srcs = new[] {
                    "contracts/crowdsale/validation/WhitelistedCrowdsale.sol",
                    "contracts/token/ERC20/StandardBurnableToken.sol"
                };
                solcLib.Compile(srcs);
            }
        }
示例#13
0
        public void IsReleaseVersion(Legacy.SolcVersion solcVersion)
        {
            var libPath     = Legacy.LibPath.GetLibPath(solcVersion);
            var libProvider = new SolcLibDefaultProvider(libPath);
            var solcLib     = new SolcLib(libProvider);
            var version     = solcLib.VersionDescription;

            // Prerelease/develop compiled libs have a version that looks like: 0.4.24-develop.2018.7.5+commit.346b21c8
            // Release compiled libs have a version that looks like: 0.4.24+commit.8025b766
            if (version.Contains("develop") || version.Contains("night"))
            {
                Assert.Fail("Lib version is not develop / nightly: " + version);
            }
        }
示例#14
0
        public JsonResult Compile(string source)
        {
            var compiler = new SolcLib();

            var input = new InputDescription
            {
                Language = Language.Solidity,
                Settings = new Settings
                {
                    OutputSelection = new Dictionary <string, Dictionary <string, OutputType[]> >
                    {
                        { "*", new Dictionary <string, OutputType[]> {
                              {
                                  "*",
                                  new[]
                                  {
                                      OutputType.Abi,
                                      OutputType.EvmBytecodeObject
                                  }
                              }
                          } }
                    },
                    EvmVersion = EvmVersion.Byzantium,
                    Optimizer  = new Optimizer
                    {
                        Enabled = false,
                        Runs    = 200
                    }
                },
                Sources = new Dictionary <string, Source>
                {
                    { "comiled.sol", new Source {
                          Content = source
                      } }
                }
            };

            var output = compiler.Compile(input);
            var regex  = new Regex("contract[ ]*.*_xtemplate");
            var name   = regex.Match(source).Value.Split(" ")[1];

            var result = new object[]
            {
                output.Contracts["comiled.sol"][name].Abi,
                output.Contracts["comiled.sol"][name].Evm.Bytecode.Object
            };

            return(new JsonResult(result));
        }
示例#15
0
        private CodebaseGenerator(CommandArgs appArgs, bool returnFullSources)
        {
            _assemblyVersion   = typeof(Program).Assembly.GetName().Version.ToString();
            _returnFullSources = returnFullSources;
            _genResults        = new SolCodeGenResults();

            // Normalize source directory
            _solSourceDirectory = Path.GetFullPath(appArgs.SolSourceDirectory);

            // Match the solc file path output format which replaces Windows path separator characters with unix style.
            if (Path.DirectorySeparatorChar == '\\')
            {
                _solSourceDirectory = _solSourceDirectory.Replace('\\', '/');
            }

            if (string.IsNullOrWhiteSpace(appArgs.OutputDirectory))
            {
                string sourceFilesParentDir = Directory.GetParent(_solSourceDirectory).FullName;
                _generatedContractsDirectory = Path.Combine(sourceFilesParentDir, GeneratedContractsDefaultDirectory);
            }
            else
            {
                _generatedContractsDirectory = Path.GetFullPath(appArgs.OutputDirectory);
            }

            if (string.IsNullOrWhiteSpace(appArgs.AssemblyOutputDirectory))
            {
                string sourceFilesParentDir = Directory.GetParent(_solSourceDirectory).FullName;
                _generatedAssemblyDirectory = Path.Combine(sourceFilesParentDir, GeneratedAssemblyDefaultDirectory);
            }
            else
            {
                _generatedAssemblyDirectory = Path.GetFullPath(appArgs.AssemblyOutputDirectory);
            }

            if (!string.IsNullOrEmpty(appArgs.LegacySolcPath))
            {
                _legacySolcPath = Path.GetFullPath(appArgs.LegacySolcPath);
            }

            _namespace               = appArgs.Namespace;
            _solcVersion             = appArgs.SolcVersion;
            _solcOptimzer            = appArgs.SolcOptimizer;
            _solcLib                 = SetupSolcLib();
            _solidityCompilerVersion = _solcLib.Version.ToString(3);
        }
示例#16
0
        static void TestNativeLibLoaders()
        {
            void TryLib <TLib>() where TLib : INativeSolcLib, new()
            {
                Console.WriteLine($"Trying {typeof(TLib)}");
                try
                {
                    var solc = SolcLib.Create <TLib>();
                    var ver  = solc.VersionDescription;
                    Console.WriteLine($"Loaded solc lib version: {ver}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            TryLib <SolcLibDefaultProvider>();
            TryLib <NativeLibraryLoader.SolcLibDynamicProvider>();
            TryLib <AdvDL.SolcLibAdvDLProvider>();
        }
示例#17
0
        public void ParallelCompiles()
        {
            var taskList = new List <Task>();

            for (var i = 0; i < 1; i++)
            {
                taskList.Add(Task.Run(() =>
                {
                    var solcLib = new SolcLib("OpenZeppelin");
                    for (var j = 0; j < 10; j++)
                    {
                        var srcs = new[] {
                            "contracts/crowdsale/validation/WhitelistedCrowdsale.sol",
                            "contracts/token/ERC20/StandardBurnableToken.sol"
                        };
                        solcLib.Compile(srcs);
                    }
                }));
            }

            Task.WaitAll(taskList.ToArray());
        }
示例#18
0
 public CompileOutput()
 {
     _lib = new SolcLib();
 }
示例#19
0
 public void CompileEthPMContractPath()
 {
     var solcLib     = new SolcLib(CONTRACT_SRC_DIR);
     var sourceFiles = Directory.GetFiles(CONTRACT_SRC_DIR, "*.sol", SearchOption.AllDirectories).Select(p => Path.GetRelativePath(CONTRACT_SRC_DIR, p)).ToArray();
     var result      = solcLib.Compile(sourceFiles);
 }
示例#20
0
        public void CompileCallbackTest(IInteropLibProvider nativeSolcLib)
        {
            var solcLib = new SolcLib(nativeSolcLib.InteropLib, CONTRACT_SRC_DIR);

            CompileSeveralContracts(solcLib);
        }