public void SingleUploadSuccessMaxFileSize() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var testUser = KeyPair.Generate(); BigInteger accountBalance = (Archive.MaxSize / 1024) / KilobytesPerStake; //provide enough account balance for max file size available space accountBalance *= UnitConversion.GetUnitValue(Nexus.StakingTokenDecimals); Transaction tx = null; simulator.BeginBlock(); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.StakingTokenSymbol, accountBalance); simulator.EndBlock(); //----------- //Perform a valid Stake call var stakeAmount = accountBalance; var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Stake", testUser.Address, stakeAmount). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); BigInteger stakedAmount = simulator.Nexus.RootChain.InvokeContract(Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); Assert.IsTrue(stakedAmount == stakeAmount); var finalSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); Assert.IsTrue(stakeAmount == startingSoulBalance - finalSoulBalance); //----------- //Upload a file: should succeed var filename = "notAVirus.exe"; var headerSize = CalculateRequiredSize(filename, 0); var contentSize = (long)(Archive.MaxSize) - (long)headerSize; var content = new byte[contentSize]; var contentMerkle = new MerkleTree(content); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); System.IO.File.WriteAllText(@"D:\Repos\bug_vm.txt", string.Join('\n', new VM.Disassembler(tx.Script).Instructions)); simulator.EndBlock(); var usedSpace = simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == contentSize + headerSize); }
private void StartSimulator(CommandDispatcher dispatcher) { new Thread(() => { Logger.Message("Initializing simulator..."); _simulator = new NexusSimulator(this._nexus, _nodeKeys, 1234); _simulator.MinimumFee = Settings.Node.MinimumFee; bool genBlocks = Settings.Simulator.Blocks; if (genBlocks) { int blockNumber = 0; while (Running) { Thread.Sleep(5000); blockNumber++; Logger.Debug("Generating sim block #" + blockNumber); try { _simulator.CurrentTime = DateTime.UtcNow; _simulator.GenerateRandomBlock(); } catch (Exception e) { Logger.Error("Fatal error: " + e.ToString()); Environment.Exit(-1); } } } MakeReady(dispatcher); }).Start(); }
private void InitMainNode(int _port = 7077) { var log = new ConsoleLogger(); string wif = nexusWif; int port = _port; var node_keys = PhantasmaKeys.FromWIF(wif); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var simulator = new NexusSimulator(nexus, node_keys, 1234); // mempool setup mempool = new Mempool(nexus, Mempool.MinimumBlockTime, 1, System.Text.Encoding.UTF8.GetBytes("TEST")); mempool.SetKeys(node_keys); mempool.Start(); // node setup node = new Node("test node", nexus, mempool, node_keys, port, PeerCaps.Mempool, Enumerable.Empty <String>(), log); log.Message("Phantasma Node address: " + node_keys.Address.Text); node.Start(); }
private ApiTests.TestData CreateAPI(bool useMempool = true) { var owner = PhantasmaKeys.FromWIF(testWIF); var sim = new NexusSimulator(owner, 1234); var mempool = useMempool ? new Mempool(sim.Nexus, 2, 1, System.Text.Encoding.UTF8.GetBytes("TEST")) : null; mempool.SetKeys(owner); var node = useMempool ? new Node("relay node", sim.Nexus, mempool, owner, 7073, PeerCaps.None, new List <string>() { "192.168.0.1:7073" }, null) : null; var api = useMempool ? new NexusAPI(sim.Nexus) : null; if (api != null) { api.Mempool = mempool; api.Node = node; } var data = new ApiTests.TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.Start(); return(data); }
private TestData CreateAPI(bool useMempool = false) { var owner = PhantasmaKeys.FromWIF(testWIF); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var sim = new NexusSimulator(nexus, owner, 1234); var mempool = useMempool? new Mempool(sim.Nexus, 2, 1, System.Text.Encoding.UTF8.GetBytes("TEST"), 0, new DummyLogger()) : null; mempool?.SetKeys(owner); var api = new NexusAPI(sim.Nexus); api.Mempool = mempool; var data = new TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.StartInThread(); return(data); }
private ApiTests.TestData CreateAPI(bool useMempool = true) { var owner = PhantasmaKeys.FromWIF(testWIF); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var sim = new NexusSimulator(nexus, owner, 1234); var mempool = useMempool ? new Mempool(sim.Nexus, 2, 1, System.Text.Encoding.UTF8.GetBytes("TEST")) : null; mempool.SetKeys(owner); var node = useMempool ? new Node("relay node", sim.Nexus, mempool, owner, "localhost", 7073, PeerCaps.Relay | PeerCaps.Mempool, new List <string>() { "tcp:localhost:7073" }, null) : null; var api = useMempool ? new NexusAPI(sim.Nexus) : null; if (api != null) { api.Mempool = mempool; api.Node = node; } var data = new ApiTests.TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.StartInThread(); return(data); }
private void InitExchange() { simulatorOwner = PhantasmaKeys.Generate(); nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); simulator = new NexusSimulator(nexus, simulatorOwner, 1234); CreateTokens(); }
private void TopUpChannel(NexusSimulator simulator, PhantasmaKeys from, BigInteger amount) { simulator.BeginBlock(); simulator.GenerateCustomTransaction(from, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(from.Address, Address.Null, 1, 9999) .CallContract("relay", "TopUpChannel", from.Address, amount). SpendGas(from.Address).EndScript()); simulator.EndBlock(); }
public void TestGetBotWrestler() { var owner = PhantasmaKeys.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var api = new NexusAPI(nexus); var callScript = ScriptUtils.BeginScript().CallContract("nacho", "GetWrestler", new object[] { -1 }).EndScript(); var apiResult = (ScriptResult)api.InvokeRawScript("main", Base16.Encode(callScript)); var bytes = Base16.Decode(apiResult.results[0]); var objResult = Serialization.Unserialize <VMObject>(bytes); var nachoWrestler = objResult.ToStruct <NachoWrestler>(); }
private TestData CreateAPI(bool useMempool = false) { var owner = KeyPair.FromWIF(testWIF); var sim = new NexusSimulator(owner, 1234); var mempool = useMempool? new Mempool(owner, sim.Nexus, 2, 1) : null; var api = new NexusAPI(sim.Nexus, mempool); var data = new TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.Start(); return(data); }
private TestData CreateAPI(bool useMempool = false) { var owner = PhantasmaKeys.FromWIF(testWIF); var sim = new NexusSimulator(owner, 1234); var mempool = useMempool? new Mempool(owner, sim.Nexus, 2, 1, System.Text.Encoding.UTF8.GetBytes("TEST")) : null; var api = new NexusAPI(sim.Nexus); api.Mempool = mempool; var data = new TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.Start(); return(data); }
public void OracleTestWithTooMuchData() { var owner = PhantasmaKeys.Generate(); var wallet = PhantasmaKeys.Generate(); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var simulator = new NexusSimulator(nexus, owner, 1234); for (int i = 0; i < DomainSettings.MaxOracleEntriesPerBlock + 1; i++) { var url = DomainExtensions.GetOracleBlockURL("neo", "neo", new BigInteger(i)); var iBlock = nexus.GetOracleReader().Read <InteropBlock>(DateTime.Now, url); } Assert.ThrowsException <ChainException>(() => { simulator.BeginBlock(); simulator.GenerateTransfer(owner, wallet.Address, nexus.RootChain, "SOUL", 100); simulator.EndBlock().First(); }); }
private void InitMainNode(int _port = 7077) { string wif = nexusWif; int port = _port; var node_keys = PhantasmaKeys.FromWIF(wif); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var simulator = new NexusSimulator(nexus, node_keys, 1234); // mempool setup mempool = new Mempool(nexus, Mempool.MinimumBlockTime, 1, System.Text.Encoding.UTF8.GetBytes("TEST")); mempool.SetKeys(node_keys); mempool.StartInThread(); // node setup node = new Node("test node", nexus, mempool, node_keys, "localhost", port, PeerCaps.Mempool, Enumerable.Empty <String>(), new DebugLogger()); node.StartInThread(); }
private ApiTests.TestData CreateAPI(bool useMempool = true) { var owner = KeyPair.FromWIF(testWIF); var sim = new NexusSimulator(owner, 1234); var mempool = useMempool ? new Mempool(owner, sim.Nexus, 2, 1) : null; var node = useMempool ? new Node(sim.Nexus, mempool, owner, 7073, PeerCaps.None, new List <string>() { "192.168.0.1:7073" }, null) : null; var api = useMempool ? new NexusAPI(sim.Nexus, mempool, node) : null; var data = new ApiTests.TestData() { owner = owner, simulator = sim, nexus = sim.Nexus, api = api }; mempool?.Start(); return(data); }
public void OracleTestWithData() { var owner = PhantasmaKeys.Generate(); var wallet = PhantasmaKeys.Generate(); var nexus = new Nexus("simnet", null, null); nexus.SetOracleReader(new OracleSimulator(nexus)); var simulator = new NexusSimulator(nexus, owner, 1234); //for (var i = 0; i < 65536; i++) for (var i = 0; i < 100; i++) { var url = DomainExtensions.GetOracleBlockURL("neo", "neo", new BigInteger(i)); var iBlock = nexus.GetOracleReader().Read <InteropBlock>(DateTime.Now, url); } simulator.BeginBlock(); simulator.GenerateTransfer(owner, wallet.Address, nexus.RootChain, "SOUL", 100); var block = simulator.EndBlock().First(); Console.WriteLine("block oracle data: " + block.OracleData.Count()); Assert.IsTrue(block.OracleData.Count() == 100); }
private void InitMainNode() { var log = new ConsoleLogger(); string wif = nexusWif; int port = 7077; var node_keys = KeyPair.FromWIF(wif); var simulator = new NexusSimulator(node_keys, 1234); nexus = simulator.Nexus; // mempool setup mempool = new Mempool(node_keys, nexus, Mempool.MinimumBlockTime, 1); mempool.Start(); // node setup node = new Node(nexus, mempool, node_keys, port, PeerCaps.Mempool, Enumerable.Empty <String>(), log); log.Message("Phantasma Node address: " + node_keys.Address.Text); node.Start(); }
public void UnstakeWithStoredFilesFailure() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var testUser = KeyPair.Generate(); var accountBalance = MinimumValidStake * 100; Transaction tx = null; simulator.BeginBlock(); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.StakingTokenSymbol, accountBalance); simulator.EndBlock(); //----------- //Perform a valid Stake call for minimum staking amount var stakedAmount = MinimumValidStake; var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Stake", testUser.Address, stakedAmount). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); //----------- //Upload a file var filename = "notAVirus.exe"; var headerSize = CalculateRequiredSize(filename, 0); var contentSize = (long)(stakedAmount / MinimumValidStake * KilobytesPerStake * 1024) - (long)headerSize; var content = new byte[contentSize]; var contentMerkle = new MerkleTree(content); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); var usedSpace = simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == contentSize + headerSize); var oldSpace = usedSpace; //----------- //Time skip 1 day simulator.TimeSkipDays(1); //----------- //Try to unstake everything: should fail due to files still existing for this user var initialStakedAmount = simulator.Nexus.RootChain.InvokeContract(Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); var stakeReduction = initialStakedAmount - MinimumValidStake; startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); Assert.ThrowsException <ChainException>(() => { simulator.BeginBlock(); simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Unstake", testUser.Address, stakeReduction). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); }); var finalStakedAmount = simulator.Nexus.RootChain.InvokeContract(Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); Assert.IsTrue(initialStakedAmount == finalStakedAmount); usedSpace = simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == oldSpace); }
public void ReduceAvailableSpace() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var testUser = KeyPair.Generate(); var accountBalance = MinimumValidStake * 100; Transaction tx = null; simulator.BeginBlock(); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, DomainSettings.FuelTokenSymbol, 100000000); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, DomainSettings.StakingTokenSymbol, accountBalance); simulator.EndBlock(); //----------- //Perform a valid Stake call for minimum staking amount var stakedAmount = MinimumValidStake * 5; var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, DomainSettings.StakingTokenSymbol, testUser.Address); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Stake", testUser.Address, stakedAmount). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); //----------- //Upload a file var filename = "notAVirus.exe"; var headerSize = CalculateRequiredSize(filename, 0); var contentSize = (long)(stakedAmount / MinimumValidStake * KilobytesPerStake * 1024 / 5) - (long)headerSize; var content = new byte[contentSize]; var contentMerkle = new MerkleTree(content); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); var usedSpace = simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, "storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == contentSize + headerSize); //----------- //Time skip 1 day simulator.TimeSkipDays(1); //----------- //Try partial unstake: should succeed var initialStakedAmount = simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); var stakeReduction = stakedAmount / 5; simulator.BeginBlock(); simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Unstake", testUser.Address, stakeReduction). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); var finalStakedAmount = simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); Assert.IsTrue(finalStakedAmount == initialStakedAmount - stakeReduction); }
[Ignore] //TODO public void TestVote() { nexus.SetOracleReader(new OracleSimulator(nexus)); simulator = new NexusSimulator(nexus, owner, 1234); CreateValidators(); }
public CLI(string[] args) { var culture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = culture; CultureInfo.DefaultThreadCurrentCulture = culture; var seeds = new List <string>(); var settings = new Arguments(args); var useGUI = settings.GetBool("gui.enabled", true); if (useGUI) { gui = new ConsoleGUI(); logger = gui; } else { gui = null; logger = new ConsoleLogger(); } string mode = settings.GetString("node.mode", "default"); restartTime = settings.GetInt("node.reboot", 0); showWebLogs = settings.GetBool("web.log", false); bool apiLog = settings.GetBool("api.log", true); string apiProxyURL = settings.GetString("api.proxy", ""); if (string.IsNullOrEmpty(apiProxyURL)) { apiProxyURL = null; } bool hasSync = settings.GetBool("sync.enabled", true); bool hasMempool = settings.GetBool("mempool.enabled", true); bool hasEvents = settings.GetBool("events.enabled", true); bool hasRelay = settings.GetBool("relay.enabled", true); bool hasArchive = settings.GetBool("archive.enabled", true); bool hasRPC = settings.GetBool("rpc.enabled", false); bool hasREST = settings.GetBool("rest.enabled", false); var nexusName = settings.GetString("nexus.name", "simnet"); string profilePath = settings.GetString("mempool.profile", ""); if (string.IsNullOrEmpty(profilePath)) { profilePath = null; } bool isValidator = false; switch (mode) { case "sender": { string host = settings.GetString("sender.host"); int threadCount = settings.GetInt("sender.threads", 8); int addressesPerSender = settings.GetInt("sender.addressCount", 100); string wif = settings.GetString("node.wif"); RunSender(wif, nexusName, host, threadCount, addressesPerSender); Console.WriteLine("Sender finished operations."); return; } case "validator": isValidator = true; break; case "default": break; default: { logger.Error("Unknown mode: " + mode); return; } } int port = settings.GetInt("node.port", 7073); var defaultStoragePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/Storage"; var defaultOraclePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/Oracle"; var storagePath = FixPath(settings.GetString("storage.path", defaultStoragePath)); var oraclePath = FixPath(settings.GetString("storage.oracle", defaultOraclePath)); var storageBackend = settings.GetString("storage.backend", "file"); logger.Message("Storage backend: " + storageBackend); var storageFix = settings.GetBool("storage.fix", false); // TODO remove this later if (storageFix) { if (Directory.Exists(storagePath)) { logger.Warning("Storage fix enabled... Cleaning up all storage..."); var di = new DirectoryInfo(storagePath); foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } } } logger.Message("Storage path: " + storagePath); logger.Message("Oracle path: " + oraclePath); switch (storageBackend) { case "file": nexus = new Nexus(logger, (name) => new BasicDiskStore(storagePath + name + ".csv"), (n) => new SpookOracle(this, n, oraclePath) ); break; case "db": nexus = new Nexus(logger, (name) => new DBPartition(storagePath + name), (n) => new SpookOracle(this, n, oraclePath) ); break; default: throw new Exception("Backend has to be set to either \"db\" or \"file\""); } running = true; // mempool setup int blockTime = settings.GetInt("node.blocktime", Mempool.MinimumBlockTime); int minimumFee; try { minimumFee = settings.GetInt("mempool.fee", 100000); if (minimumFee < 1) { logger.Error("Invalid mempool fee value. Expected a positive value."); } } catch (Exception e) { logger.Error("Invalid mempool fee value. Expected something in fixed point format."); return; } int minimumPow; try { minimumPow = settings.GetInt("mempool.pow", 0); int maxPow = 5; if (minimumPow < 0 || minimumPow > maxPow) { logger.Error($"Invalid mempool pow value. Expected a value between 0 and {maxPow}."); } } catch (Exception e) { logger.Error("Invalid mempool fee value. Expected something in fixed point format."); return; } if (apiProxyURL != null) { hasMempool = false; isValidator = false; hasSync = false; hasEvents = false; hasRelay = false; hasArchive = false; if (!hasRPC && !hasREST) { logger.Error("API proxy must have REST or RPC enabled."); return; } } if (hasMempool) { this.mempool = new Mempool(nexus, blockTime, minimumFee, System.Text.Encoding.UTF8.GetBytes(Identifier), 0, logger, profilePath); var mempoolLogging = settings.GetBool("mempool.log", true); if (mempoolLogging) { mempool.OnTransactionFailed += Mempool_OnTransactionFailed; mempool.OnTransactionAdded += (hash) => logger.Message($"Received transaction {hash}"); mempool.OnTransactionCommitted += (hash) => logger.Message($"Commited transaction {hash}"); mempool.OnTransactionDiscarded += (hash) => logger.Message($"Discarded transaction {hash}"); } mempool.Start(ThreadPriority.AboveNormal); } else { this.mempool = null; } if (!isValidator && !hasSync && apiProxyURL == null) { logger.Warning("Non-validator nodes require sync feature to be enabled, auto enabled now"); hasSync = true; } PeerCaps caps = PeerCaps.None; if (hasSync) { caps |= PeerCaps.Sync; } if (hasMempool) { caps |= PeerCaps.Mempool; } if (hasEvents) { caps |= PeerCaps.Events; } if (hasRelay) { caps |= PeerCaps.Relay; } if (hasArchive) { caps |= PeerCaps.Archive; } if (hasRPC) { caps |= PeerCaps.RPC; } if (hasREST) { caps |= PeerCaps.REST; } var possibleCaps = Enum.GetValues(typeof(PeerCaps)).Cast <PeerCaps>().ToArray(); foreach (var cap in possibleCaps) { if (cap != PeerCaps.None && caps.HasFlag(cap)) { logger.Message("Feature enabled: " + cap); } } PhantasmaKeys node_keys = null; bool bootstrap = false; if (hasSync) { string wif = settings.GetString("node.wif"); node_keys = PhantasmaKeys.FromWIF(wif); WalletModule.Keys = PhantasmaKeys.FromWIF(wif); try { if (this.mempool != null) { this.mempool.SetKeys(node_keys); } this.node = new Node("Spook v" + SpookVersion, nexus, mempool, node_keys, port, caps, seeds, logger); } catch (Exception e) { logger.Error(e.Message); return; } if (!nexus.HasGenesis) { if (isValidator) { if (settings.GetBool("nexus.bootstrap")) { if (!ValidationUtils.IsValidIdentifier(nexusName)) { logger.Error("Invalid nexus name: " + nexusName); this.Terminate(); return; } logger.Debug($"Boostraping {nexusName} nexus using {node_keys.Address}..."); var genesisTimestamp = new Timestamp(settings.GetUInt("genesis.timestamp", Timestamp.Now.Value)); bootstrap = true; if (!nexus.CreateGenesisBlock(nexusName, node_keys, genesisTimestamp)) { throw new ChainException("Genesis block failure"); } logger.Debug("Genesis block created: " + nexus.GetGenesisHash(nexus.RootStorage)); } else { logger.Error("No Nexus found."); this.Terminate(); } } } else { var genesisAddress = nexus.GetGenesisAddress(nexus.RootStorage); if (isValidator && node_keys.Address != genesisAddress) { logger.Error("Specified node key does not match genesis address " + genesisAddress.Text); return; } else { logger.Success("Loaded Nexus with genesis " + nexus.GetGenesisHash(nexus.RootStorage)); //seeds.Add("127.0.0.1:7073"); } } } else { this.node = null; } if (mempool != null) { if (isValidator) { this.mempool.SetKeys(node_keys); } else { this.mempool.SubmissionCallback = (tx, chain) => { logger.Message($"Relaying tx {tx.Hash} to other node"); //this.node. }; } } var useAPICache = settings.GetBool("api.cache", true); if (apiProxyURL != null) { useAPICache = true; } logger.Message($"API cache is {(useAPICache ? "enabled" : "disabled")}."); nexusApi = new NexusAPI(nexus, useAPICache, apiLog ? logger : null); nexusApi.Mempool = mempool; if (!string.IsNullOrEmpty(apiProxyURL)) { nexusApi.ProxyURL = apiProxyURL; logger.Message($"API will be acting as proxy for {apiProxyURL}"); } else { nexusApi.Node = node; } var readOnlyMode = settings.GetBool("readonly", false); if (apiProxyURL != null) { readOnlyMode = true; } if (readOnlyMode) { logger.Warning($"Node will be running in read-only mode."); nexusApi.acceptTransactions = false; } // RPC setup if (hasRPC) { rpcPort = settings.GetInt("rpc.port", 7077); logger.Message($"RPC server listening on port {rpcPort}..."); var rpcServer = new RPCServer(nexusApi, "/rpc", rpcPort, (level, text) => WebLogMapper("rpc", level, text)); rpcServer.Start(ThreadPriority.AboveNormal); } else { rpcPort = 0; } // REST setup if (hasREST) { restPort = settings.GetInt("rest.port", 7078); logger.Message($"REST server listening on port {restPort}..."); var restServer = new RESTServer(nexusApi, "/api", restPort, (level, text) => WebLogMapper("rest", level, text)); restServer.Start(ThreadPriority.AboveNormal); } else { restPort = 0; } if (node != null) { var neoScanURL = settings.GetString("neoscan.url", "https://api.neoscan.io"); var rpcList = settings.GetString("neo.rpc", "http://seed6.ngd.network:10332,http://seed.neoeconomy.io:10332"); var neoRpcURLs = rpcList.Split(','); this.neoAPI = new Neo.Core.RemoteRPCNode(neoScanURL, neoRpcURLs); this.neoAPI.SetLogger((s) => logger.Message(s)); this.neoScanAPI = new NeoScanAPI(neoScanURL, logger, nexus, node_keys); cryptoCompareAPIKey = settings.GetString("cryptocompare.apikey", ""); if (!string.IsNullOrEmpty(cryptoCompareAPIKey)) { logger.Message($"CryptoCompare API enabled..."); } node.Start(); } if (gui != null) { int pluginPeriod = settings.GetInt("plugin.refresh", 1); // in seconds if (settings.GetBool("plugin.tps", false)) { RegisterPlugin(new TPSPlugin(logger, pluginPeriod)); } if (settings.GetBool("plugin.ram", false)) { RegisterPlugin(new RAMPlugin(logger, pluginPeriod)); } if (settings.GetBool("plugin.mempool", false)) { RegisterPlugin(new MempoolPlugin(mempool, logger, pluginPeriod)); } } Console.CancelKeyPress += delegate { Terminate(); }; useSimulator = settings.GetBool("simulator.enabled", false); var dispatcher = new CommandDispatcher(); SetupCommands(dispatcher); if (settings.GetBool("swaps.enabled")) { var tokenSwapper = new TokenSwapper(node_keys, nexusApi, neoScanAPI, neoAPI, minimumFee, logger, settings); nexusApi.TokenSwapper = tokenSwapper; new Thread(() => { logger.Message("Running token swapping service..."); while (running) { Thread.Sleep(5000); if (nodeReady) { tokenSwapper.Update(); } } }).Start(); } if (useSimulator && bootstrap) { new Thread(() => { logger.Message("Initializing simulator..."); simulator = new NexusSimulator(this.nexus, node_keys, 1234); simulator.MinimumFee = minimumFee; /* * logger.Message("Bootstrapping validators"); * simulator.BeginBlock(); * for (int i = 1; i < validatorWIFs.Length; i++) * { * simulator.GenerateTransfer(node_keys, Address.FromWIF(validatorWIFs[i]), this.nexus.RootChain, DomainSettings.StakingTokenSymbol, UnitConversion.ToBigInteger(50000, DomainSettings.StakingTokenDecimals)); * } * simulator.EndBlock();*/ string[] dapps = settings.GetString("dapps", "").Split(','); DappServer.InitDapps(nexus, simulator, node_keys, dapps, minimumFee, logger); bool genBlocks = settings.GetBool("simulator.blocks", false); if (genBlocks) { int blockNumber = 0; while (running) { Thread.Sleep(5000); blockNumber++; logger.Message("Generating sim block #" + blockNumber); try { simulator.CurrentTime = DateTime.UtcNow; simulator.GenerateRandomBlock(); } catch (Exception e) { logger.Error("Fatal error: " + e.ToString()); Environment.Exit(-1); } } } MakeReady(dispatcher); }).Start(); } else { MakeReady(dispatcher); } this.Run(); }
public void TestNachoPurchase() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var tokenSupply = ToBigInteger(69931640.63m, NACHO_TOKEN_DECIMALS); simulator.BeginBlock(); simulator.GenerateToken(owner, NACHO_SYMBOL, NACHO_SYMBOL, DomainSettings.PlatformName, Hash.FromString(NACHO_SYMBOL), tokenSupply, NACHO_TOKEN_DECIMALS, Fungible | Transferable | Finite | Divisible); simulator.MintTokens(owner, owner.Address, NACHO_SYMBOL, tokenSupply); simulator.EndBlock(); var buyer = KeyPair.Generate(); var receiver = KeyPair.Generate(); var nexus = simulator.Nexus; simulator.BeginBlock(); simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, FuelTokenSymbol, 100000000); simulator.MintTokens(owner, owner.Address, FiatTokenSymbol, new BigInteger("1000000000000000000000000000000000000000000000000", 10) * GetUnitValue(FiatTokenDecimals)); //simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, DomainSettings.FiatTokenSymbol, 1000000 * UnitConversion.GetUnitValue(DomainSettings.FiatTokenDecimals)); simulator.EndBlock(); var ownerFiat = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, DomainSettings.FiatTokenSymbol, owner.Address); decimal requiredMoney = 0; for (int stage = 0; stage < stageCount; stage++) { for (int milestone = 1; milestone <= milestoneCount; milestone++) { decimal milestoneTokens = stageTokenAmount[stage] * milestone / 10m; milestoneTokens = Math.Round(milestoneTokens, 2, AwayFromZero); decimal milestoneTokensPerUsd = stageTokensPerUsd[stage] * tokenDecreaseFactor[stage]; milestoneTokensPerUsd = Math.Round(milestoneTokensPerUsd, 3, AwayFromZero); requiredMoney += milestoneTokens / milestoneTokensPerUsd; Assert.IsTrue(requiredMoney >= 500, "unexpected order size: not enough for 40% bonus"); requiredMoney = requiredMoney / 1.4m; var bigintMoney = ToBigInteger(requiredMoney, FiatTokenDecimals); simulator.BeginBlock(); simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, FiatTokenSymbol, bigintMoney); simulator.EndBlock(); var initialNachos = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, NACHO_SYMBOL, receiver.Address); var initialFiat = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, DomainSettings.FiatTokenSymbol, receiver.Address); simulator.BeginBlock(); simulator.GenerateCustomTransaction(buyer, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(buyer.Address, Address.Null, 1, 9999) .CallContract("nacho", "BuyInApp", buyer.Address, FiatTokenSymbol, bigintMoney). SpendGas(buyer.Address).EndScript()); simulator.EndBlock(); var finalNachos = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, NACHO_SYMBOL, receiver.Address); var finalFiat = simulator.Nexus.RootChain.GetTokenBalance(simulator.Nexus.RootStorage, DomainSettings.FiatTokenSymbol, receiver.Address); var milestoneTokensBigInt = ToBigInteger(milestoneTokens, NACHO_TOKEN_DECIMALS); Assert.IsTrue(finalNachos == initialNachos + milestoneTokensBigInt); Assert.IsTrue(finalFiat == initialFiat - bigintMoney); } } }
private void InitExchange() { simulatorOwner = KeyPair.Generate(); simulator = new NexusSimulator(simulatorOwner, 1234); CreateTokens(); }
public void SingleUploadSuccess() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var testUser = KeyPair.Generate(); var accountBalance = MinimumValidStake * 5; Transaction tx = null; simulator.BeginBlock(); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.StakingTokenSymbol, accountBalance); simulator.EndBlock(); //----------- //Perform a valid Stake call for minimum staking amount var stakeAmount = accountBalance / 2; var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Stake", testUser.Address, stakeAmount). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); BigInteger stakedAmount = simulator.Nexus.RootChain.InvokeContract(Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); Assert.IsTrue(stakedAmount == stakeAmount); var finalSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); Assert.IsTrue(stakeAmount == startingSoulBalance - finalSoulBalance); //----------- //Upload a file: should succeed var filename = "notAVirus.exe"; var headerSize = CalculateRequiredSize(filename, 0); var contentSize = (long)((stakedAmount / MinimumValidStake * KilobytesPerStake) * 1024) - (long)headerSize; var content = new byte[contentSize]; var rnd = new Random(); for (int i = 0; i < content.Length; i++) { content[i] = (byte)rnd.Next(); } var contentMerkle = new MerkleTree(content); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); //System.IO.File.WriteAllText(@"c:\code\bug_vm.txt", string.Join('\n', new VM.Disassembler(tx.Script).Instructions)); simulator.EndBlock(); var usedSpace = simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == contentSize + headerSize); Assert.IsTrue(simulator.Nexus.ArchiveExists(contentMerkle.Root)); var archive = simulator.Nexus.FindArchive(contentMerkle.Root); for (int i = 0; i < archive.BlockCount; i++) { int ofs = (int)(i * Archive.BlockSize); var blockContent = content.Skip(ofs).Take((int)Archive.BlockSize).ToArray(); simulator.Nexus.WriteArchiveBlock(archive, blockContent, i); } }
public void TestNachoPurchaseBonus() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var tokenSupply = ToBigInteger(69931640.63m, NACHO_TOKEN_DECIMALS); simulator.BeginBlock(); simulator.GenerateToken(owner, NACHO_SYMBOL, NACHO_SYMBOL, Nexus.PlatformName, Hash.FromString(NACHO_SYMBOL), tokenSupply, NACHO_TOKEN_DECIMALS, Fungible | Transferable | Finite | Divisible); simulator.MintTokens(owner, owner.Address, NACHO_SYMBOL, tokenSupply); simulator.EndBlock(); var buyer = KeyPair.Generate(); var receiver = KeyPair.Generate(); var nexus = simulator.Nexus; simulator.BeginBlock(); simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, FuelTokenSymbol, 100000000); simulator.MintTokens(owner, owner.Address, FiatTokenSymbol, new BigInteger("1000000000000000000000000000000000000000000000000", 10) * GetUnitValue(FiatTokenDecimals)); //simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, Nexus.FiatTokenSymbol, 1000000 * UnitConversion.GetUnitValue(Nexus.FiatTokenDecimals)); simulator.EndBlock(); var ownerFiat = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FiatTokenSymbol, owner.Address); decimal milestoneRequiredMoney = 0; decimal[] purchaseAmounts = { 1, 2, 5, 10, 20, 50, 100, 250, 500 }; decimal[] purchaseBonus = { 0, 5, 10, 15, 20, 25, 30, 35, 40 }; for (int stage = 0; stage < stageCount; stage++) { for (int milestone = 1; milestone <= milestoneCount; milestone++) { decimal milestoneTokens = stageTokenAmount[stage] * milestone / 10m; milestoneTokens = Math.Round(milestoneTokens, 2, AwayFromZero); decimal milestoneTokensPerUsd = stageTokensPerUsd[stage] * tokenDecreaseFactor[stage]; milestoneTokensPerUsd = Math.Round(milestoneTokensPerUsd, 3, AwayFromZero); for (int purchase = 0; purchase < purchaseAmounts.Length; purchase++) { var purchaseCoef = purchaseBonus[purchase] / 100; var expectedPurchasedTokens = purchaseAmounts[purchase] * milestoneTokensPerUsd * (1 + purchaseCoef); var expectedPurchasedTokensBigint = ToBigInteger(expectedPurchasedTokens, NACHO_TOKEN_DECIMALS); var purchaseAmountsBigint = ToBigInteger(purchaseAmounts[purchase], FiatTokenDecimals); simulator.BeginBlock(); simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, FiatTokenSymbol, purchaseAmountsBigint); simulator.EndBlock(); var initialNachos = simulator.Nexus.RootChain.GetTokenBalance(NACHO_SYMBOL, receiver.Address); var initialFiat = simulator.Nexus.RootChain.GetTokenBalance(FiatTokenSymbol, receiver.Address); simulator.BeginBlock(); simulator.GenerateCustomTransaction(buyer, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(buyer.Address, Address.Null, 1, 9999) .CallContract("nacho", "BuyInApp", buyer.Address, FiatTokenSymbol, purchaseAmountsBigint). SpendGas(buyer.Address).EndScript()); simulator.EndBlock(); var finalNachos = simulator.Nexus.RootChain.GetTokenBalance(NACHO_SYMBOL, receiver.Address); var finalFiat = simulator.Nexus.RootChain.GetTokenBalance(Nexus.FiatTokenSymbol, receiver.Address); Assert.IsTrue(finalNachos == initialNachos + expectedPurchasedTokensBigint); Assert.IsTrue(finalFiat == initialFiat - purchaseAmountsBigint); milestoneTokens -= expectedPurchasedTokens; } //do a single order to clean up the rest of the current milestone var requiredMoney = milestoneTokens / milestoneTokensPerUsd; Assert.IsTrue(requiredMoney >= 500, "unexpected order size: not enough for 40% bonus"); requiredMoney = requiredMoney / 1.4m; var bigintMoney = ToBigInteger(requiredMoney, FiatTokenDecimals); simulator.BeginBlock(); simulator.GenerateTransfer(owner, buyer.Address, nexus.RootChain, FiatTokenSymbol, bigintMoney); simulator.EndBlock(); simulator.BeginBlock(); simulator.GenerateCustomTransaction(buyer, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(buyer.Address, Address.Null, 1, 9999) .CallContract("nacho", "BuyInApp", buyer.Address, FiatTokenSymbol, bigintMoney). SpendGas(buyer.Address).EndScript()); simulator.EndBlock(); } } }
public void UploadDuplicateFilename() { var owner = KeyPair.Generate(); var simulator = new NexusSimulator(owner, 1234); var nexus = simulator.Nexus; var testUser = KeyPair.Generate(); var accountBalance = MinimumValidStake * 100; Transaction tx = null; simulator.BeginBlock(); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000); simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.StakingTokenSymbol, accountBalance); simulator.EndBlock(); //----------- //Perform a valid Stake call var stakeAmount = MinimumValidStake * 2; var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract(Nexus.StakeContractName, "Stake", testUser.Address, stakeAmount). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); BigInteger stakedAmount = simulator.Nexus.RootChain.InvokeContract(Nexus.StakeContractName, "GetStake", testUser.Address).AsNumber(); Assert.IsTrue(stakedAmount == stakeAmount); var finalSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address); Assert.IsTrue(stakeAmount == startingSoulBalance - finalSoulBalance); //----------- //Upload a file: should succeed var filename = "notAVirus.exe"; var headerSize = CalculateRequiredSize(filename, 0); var contentSize = (long)(stakeAmount / MinimumValidStake * KilobytesPerStake * 1024 / 2) - (long)headerSize; var content = new byte[contentSize]; var contentMerkle = new MerkleTree(content); simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); var usedSpace = simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address).AsNumber(); Assert.IsTrue(usedSpace == contentSize + headerSize); var oldSpace = contentSize + headerSize; //---------- //Upload a file with the same name: should fail Assert.ThrowsException <ChainException>(() => { simulator.BeginBlock(); tx = simulator.GenerateCustomTransaction(testUser, ProofOfWork.None, () => ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999) .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, content, ArchiveFlags.None, new byte[0]). SpendGas(testUser.Address).EndScript()); simulator.EndBlock(); }); Assert.IsTrue(usedSpace == oldSpace); }