Esempio n. 1
0
        public object Start(string level)
        {
            LocalNode node = new LocalNode(Assembly.GetExecutingAssembly());
            node.Join();

            try
            {
                FileInfo levelInfo = new FileInfo(level);
                if (levelInfo.Directory.Name != "Resources")
                    return "Level is not in a resources directory.";

                DirectoryInfo directoryInfo = levelInfo.Directory.Parent;
                World.BaseDirectory = directoryInfo.FullName;
                World.RuntimeDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;

                using (RuntimeGame game = new RuntimeGame(levelInfo.Name.Substring(0, levelInfo.Name.Length - levelInfo.Extension.Length)))
                {
                    game.Run();
                }
            }
            finally
            {
                node.Leave();
            }

            return null;
        }
Esempio n. 2
0
 public void BarReturnsCorrectString()
 {
     var node = new LocalNode();
     node.Bind(IPAddress.Loopback, 11003);
     
     var foo = (Foo)new Distributed<Foo>(node, "foo");
     var bar = foo.ConstructBar();
     Assert.Equal("Hello, World!", bar.GetHelloWorldString());
 }
Esempio n. 3
0
 public void ThrowsExceptionWhenNetworkIsNotJoined()
 {
     var node = new LocalNode();
     
     Assert.Throws<InvalidOperationException>(() =>
     {
         new Distributed<InterceptNewInstructionTest>(node, "hello");
     });
 }
Esempio n. 4
0
        public void TwoNodesCanNotRunInTheSameProcessOnTheSamePort()
        {
            var node = new LocalNode();
            node.Bind(IPAddress.Loopback, 9004);

            var second = new LocalNode();
            Assert.Throws<SocketException>(() => second.Bind(IPAddress.Loopback, 9004));

            node.Close();
        }
Esempio n. 5
0
        public void NodeBindsAndClosesCleanly()
        {
            var node = new LocalNode();
            node.Bind(IPAddress.Loopback, 9001);
            node.Close();

            var second = new LocalNode();
            second.Bind(IPAddress.Loopback, 9001);
            second.Close();
        }
Esempio n. 6
0
 public void DoesNotThrowExceptionWhenDirectlyConstructingInsideDistributedContext()
 {
     var node = new LocalNode();
     node.Bind(IPAddress.Loopback, 11001);
     
     Assert.DoesNotThrow(() =>
     {
         new Distributed<InterceptNewInstructionTest>(node, "hello");
     });
 }
Esempio n. 7
0
        public void TwoNodesCanRunInTheSameProcessOnDifferentPorts()
        {
            var node = new LocalNode();
            node.Bind(IPAddress.Loopback, 9002);

            var second = new LocalNode();
            second.Bind(IPAddress.Loopback, 9003);

            node.Close();
            second.Close();
        }
Esempio n. 8
0
 public void DoesNotThrowExceptionWhenIndirectlyConstructingInsideDistributedContext()
 {
     var node = new LocalNode();
     node.Bind(IPAddress.Loopback, 11002);
     
     Assert.DoesNotThrow(() =>
     {
         var foo = (Foo)new Distributed<Foo>(node, "foo");
         var bar = foo.ConstructBar();
     });
 }
Esempio n. 9
0
        public void InvokeOnSameNode()
        {
            // Set up nodes.
            var first = new LocalNode();
            first.Bind(IPAddress.Loopback, 9002);

            // Create the bar object in the first node.
            var barFirst = (Bar)new Distributed<Bar>(first, "bar");

            // Assert that the second bar returns the right value.
            Assert.Equal("Hello, World!", barFirst.GetHelloWorldString());

            // Close nodes.
            first.Close();
        }
Esempio n. 10
0
        public void TestFetchHandler()
        {
            var node = new LocalNode();
            node.Bind(IPAddress.Loopback, 10001);

            try
            {
                var constructor = node.GetService<IMessageConstructor>();
                var serializer = node.GetService<IObjectWithTypeSerializer>();

                var storage = node.GetService<IObjectStorage>();
                storage.Put(new LiveEntry
                {
                    Key = ID.NewHash("hello"),
                    Owner = node.Self,
                    Value = 40
                });

                var fetchMessage = constructor.ConstructFetchMessage(ID.NewHash("hello"));
                fetchMessage.Sender = node.Self;

                var handler = node.GetService<FetchMessageHandler>();
                handler.Handle(fetchMessage);

                var sideChannel = node.GetService<IMessageSideChannel>();
                Assert.True(
                    sideChannel.Has(x => x.Type == MessageType.FetchResult),
                    "side channel does not report message");

                var result = sideChannel.WaitUntil(x => x.Type == MessageType.FetchResult, 100);

                Assert.Equal(1, result.FetchResult.Length);

                var value = serializer.Deserialize(result.FetchResult.First().Value);

                Assert.IsType<int>(value);
                Assert.Equal(40, (int)value);
            }
            finally
            {
                node.Close();
            }
        }
Esempio n. 11
0
        public void InvocationIsCorrectForServer()
        {
            // Set up nodes.
            var first = new LocalNode(Architecture.ServerClient, Caching.PushOnChange) { IsServer = true };
            var second = new LocalNode(Architecture.ServerClient, Caching.PushOnChange);
            first.Bind(IPAddress.Loopback, 9004);
            second.Bind(IPAddress.Loopback, 9005);

            // Connect the second node to the first.
            second.GetService<IClientConnector>().Connect(IPAddress.Loopback, 9004);

            // Create the bar object in the first node.
            var barFirst = (Semantic)new Distributed<Semantic>(first, "semantic");

            // Retrieve it on the second node.
            var barSecond = (Semantic)new Distributed<Semantic>(second, "semantic");

            // Set the property.
            barFirst.Value = "Hello, World!";

            // If we try and call any of the methods from the server, they should
            // all work.
            Assert.Equal("Hello, World!", barFirst.GetException());
            Assert.Equal("Hello, World!", barFirst.GetIgnore());
            Assert.Equal("Hello, World!", barFirst.GetValue());

            // If we try and call barSecond.GetException, we should get an exception
            // because we are not a server.
            Assert.Throws<MemberAccessException>(() => barSecond.GetException());

            // If we try and call barSecond.GetIgnore, we should get a null value
            // because we are not a server.
            Assert.Equal(null, barSecond.GetIgnore());

            // If we try and call barSecond.GetValue, we should get "Hello, World!"
            Assert.Equal("Hello, World!", barSecond.GetValue());

            // Close nodes.
            first.Close();
            second.Close();
        }
Esempio n. 12
0
        public void InvokeAcrossNodes()
        {
            // Set up nodes.
            var first = new LocalNode();
            var second = new LocalNode();
            first.Bind(IPAddress.Loopback, 9004);
            second.Bind(IPAddress.Loopback, 9005);

            // Create the bar object in the first node.
            new Distributed<Bar>(first, "bar");

            // Retrieve it on the second node.
            var barSecond = (Bar)new Distributed<Bar>(second, "bar");

            // Assert that the second bar returns the right value.
            Assert.Equal("Hello, World!", barSecond.GetHelloWorldString());

            // Close nodes.
            first.Close();
            second.Close();
        }
Esempio n. 13
0
        private async void StartMine(CancellationToken token)
        {
            while (wallet == null && !token.IsCancellationRequested)
            {
                await Task.Delay(100);
            }
            while (!token.IsCancellationRequested)
            {
                ECPoint[] miners   = Blockchain.Default.GetMiners();
                bool      is_miner = false;
                foreach (Account account in wallet.GetAccounts())
                {
                    if (miners.Contains(account.PublicKey))
                    {
                        is_miner = true;
                        break;
                    }
                }
                if (!is_miner)
                {
                    try
                    {
                        await Task.Delay(Blockchain.TimePerBlock, token);
                    }
                    catch (TaskCanceledException) { }
                    continue;
                }
                Block header = Blockchain.Default.GetHeader(Blockchain.Default.CurrentBlockHash);
                if (header == null)
                {
                    continue;
                }
                TimeSpan timespan = header.Timestamp.ToDateTime() + Blockchain.TimePerBlock - DateTime.Now;
                if (timespan > TimeSpan.Zero)
                {
                    try
                    {
                        await Task.Delay(timespan, token);
                    }
                    catch (TaskCanceledException) { }
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                }
                byte[] nonce_data = new byte[sizeof(ulong)];
                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(nonce_data);
                }
                ulong nonce = BitConverter.ToUInt64(nonce_data, 0);
                List <Transaction> transactions = Blockchain.Default.GetMemoryPool().ToList();
                transactions.Insert(0, CreateGenerationTransaction(transactions, header.Height + 1, nonce));
                Block block = new Block
                {
                    PrevBlock    = header.Hash,
                    Timestamp    = DateTime.Now.ToTimestamp(),
                    Height       = header.Height + 1,
                    Nonce        = nonce,
                    NextMiner    = Blockchain.GetMinerAddress(Blockchain.Default.GetMiners(transactions).ToArray()),
                    Transactions = transactions.ToArray()
                };
                block.RebuildMerkleRoot();
                wallet.Sign(block, miners);
                await LocalNode.RelayAsync(block);

                while (Blockchain.Default.CurrentBlockHash != block.Hash && !token.IsCancellationRequested)
                {
                    await Task.Delay(100, token);
                }
            }
            stopped = true;
        }
Esempio n. 14
0
        private JObject InternalCall(string method, JArray _params)
        {
            switch (method)
            {
            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    return(block.ToJson());
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                return(Blockchain.Default.GetBlockHash(height).ToString());
            }

            case "getconnectioncount":
                return(localNode.RemoteNodeCount);

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                Transaction tx      = Blockchain.Default.GetTransaction(hash);
                if (tx == null)
                {
                    throw new RpcException(-101, "Unknown transaction");
                }
                if (verbose)
                {
                    return(tx.ToJson());
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(localNode.Relay(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(localNode.Relay(block));
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Esempio n. 15
0
 public ConsensusWithPolicy(LocalNode localNode, Wallet wallet, string log_dictionary)
     : base(localNode, wallet)
 {
     this.log_dictionary = log_dictionary;
 }
Esempio n. 16
0
        protected internal override void OnStart(string[] args)
        {
            bool useRPC = false, nopeers = false, useLog = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "/rpc":
                case "--rpc":
                case "-r":
                    useRPC = true;
                    break;

                case "--nopeers":
                    nopeers = true;
                    break;

                case "-l":
                case "--log":
                    useLog = true;
                    break;
                }
            }
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Path.GetFullPath(Settings.Default.Paths.Chain)));
            if (!nopeers && File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }
            LocalNode = new LocalNode();
            if (useLog)
            {
                LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
            }
            Task.Run(() =>
            {
                const string path_acc = "chain.acc";
                if (File.Exists(path_acc))
                {
                    using (FileStream fs = new FileStream(path_acc, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                }
                const string path_acc_zip = path_acc + ".zip";
                if (File.Exists(path_acc_zip))
                {
                    using (FileStream fs = new FileStream(path_acc_zip, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(path_acc).Open())
                            {
                                ImportBlocks(zs);
                            }
                }
                var paths = Directory.EnumerateFiles(".", "chain.*.acc", SearchOption.TopDirectoryOnly).Concat(Directory.EnumerateFiles(".", "chain.*.acc.zip", SearchOption.TopDirectoryOnly)).Select(p => new
                {
                    FileName     = Path.GetFileName(p),
                    Start        = uint.Parse(Regex.Match(p, @"\d+").Value),
                    IsCompressed = p.EndsWith(".zip")
                }).OrderBy(p => p.Start);
                foreach (var path in paths)
                {
                    if (path.Start > Blockchain.Default.Height + 1)
                    {
                        break;
                    }
                    if (path.IsCompressed)
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                            using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                                using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open())
                                {
                                    ImportBlocks(zs, true);
                                }
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            ImportBlocks(fs, true);
                        }
                    }
                }
                LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
                if (Settings.Default.UnlockWallet.IsActive)
                {
                    try
                    {
                        Program.Wallet = OpenWallet(Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password);
                    }
                    catch (CryptographicException)
                    {
                        Console.WriteLine($"failed to open file \"{Settings.Default.UnlockWallet.Path}\"");
                    }
                    if (Settings.Default.UnlockWallet.StartConsensus && Program.Wallet != null)
                    {
                        OnStartConsensusCommand(null);
                    }
                }
                if (useRPC)
                {
                    rpc = new RpcServerWithWallet(LocalNode);
                    rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword);
                }
            });
        }
Esempio n. 17
0
 public RpcServerWithWallet(LocalNode localNode)
     : base(localNode)
 {
 }
Esempio n. 18
0
 static Program()
 {
     Blockchain.RegisterBlockchain(new LevelDBBlockchain(Settings.Default.DataDirectoryPath));
     LocalNode = new LocalNode(Settings.Default.NodePort);
 }
Esempio n. 19
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getapplicationlog":
            {
                UInt256 hash = UInt256.Parse(_params[0].AsString());
                string  path = Path.Combine(Settings.Default.Paths.ApplicationLogs, $"{hash}.json");
                return(File.Exists(path)
                            ? JObject.Parse(File.ReadAllText(path))
                            : throw new RpcException(-100, "Unknown transaction"));
            }

            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    JObject json = new JObject();
                    switch (UIntBase.Parse(_params[0].AsString()))
                    {
                    case UInt160 asset_id_160:         //NEP-5 balance
                        json["balance"] = Program.Wallet.GetAvailable(asset_id_160).ToString();
                        break;

                    case UInt256 asset_id_256:         //Global Assets balance
                        IEnumerable <Coin> coins = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256));
                        json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                        json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        break;
                    }
                    return(json);
                }

            case "balance":     // 使用address查询余额 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    JObject json = new JObject();
                    if (_params.Count() == 1)
                    {
                        // 查询NEO和GAS资产
                        string address = _params[0].AsString();
                        try
                        {
                            Wallet.ToScriptHash(address);
                        }
                        catch
                        {
                            json["code"]    = -1;
                            json["message"] = "NEO地址错误";
                            return(json);
                        }
                        IEnumerable <Coin> coins = Program.Wallet.GetCoins(address);
                        // NEO
                        var neoCoins = coins.Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(UInt256.Parse(Settings.Default.Asset.NEOAsset)));
                        json["balance"]   = neoCoins.Sum(p => p.Output.Value).ToString();
                        json["confirmed"] = neoCoins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        // GAS
                        var gasCoins = coins.Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(UInt256.Parse(Settings.Default.Asset.GASAsset)));
                        json["gasbalance"]   = gasCoins.Sum(p => p.Output.Value).ToString();
                        json["gasconfirmed"] = gasCoins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        return(json);
                    }
                    else     // 查询指定资产余额
                    {
                        string address = _params[1].AsString();

                        switch (UIntBase.Parse(_params[0].AsString()))
                        {
                        case UInt160 asset_id_160:         //NEP-5 balance
                            json["balance"] = Program.Wallet.GetAvailable(asset_id_160, address).ToString();
                            break;

                        case UInt256 asset_id_256:         //Global Assets balance
                            IEnumerable <Coin> coins = Program.Wallet.GetCoins(address).Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256));
                            json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                            json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                            break;
                        }
                        return(json);
                    }
                }

            case "listaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    return(Program.Wallet.GetAccounts().Select(p =>
                    {
                        JObject account = new JObject();
                        account["address"] = p.Address;
                        account["haskey"] = p.HasKey;
                        account["label"] = p.Label;
                        account["watchonly"] = p.WatchOnly;
                        return account;
                    }).ToArray());
                }

            case "sendfrom":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = Wallet.ToScriptHash(_params[1].AsString());
                    UInt160         to         = Wallet.ToScriptHash(_params[2].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 6 ? Wallet.ToScriptHash(_params[5].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendfromto":     // 从指定账号向指定账号转账 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    // 参数顺序  资产类型  输出账号  输入账号  输出金额  输出账号私钥  手续费    找零地址
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = Wallet.ToScriptHash(_params[1].AsString());
                    UInt160         to         = Wallet.ToScriptHash(_params[2].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    string          privatekey = _params[4].AsString();
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 6 ? Fixed8.Parse(_params[5].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 7 && !string.IsNullOrEmpty(_params[6].AsString()) ? Wallet.ToScriptHash(_params[6].AsString()) : from;// 找零地址
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    //File.AppendAllText("wallet.log", context.ScriptHashes.Count().ToString());
                    //Program.Wallet.Sign(context);
                    Program.Wallet.Sign(context, privatekey);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = Wallet.ToScriptHash(to[i]["address"].AsString())
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? Wallet.ToScriptHash(_params[2].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = Program.Wallet.CreateAccount();
                    if (Program.Wallet is NEP6Wallet wallet)
                    {
                        wallet.Save();
                    }
                    return(account.Address);
                }

            case "newaddress":    // 创建一个账号 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = Program.Wallet.CreateAccount();
                    if (Program.Wallet is NEP6Wallet wallet)
                    {
                        wallet.Save();
                    }
                    return(account.OutputJson());
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160       scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    WalletAccount account    = Program.Wallet.GetAccount(scriptHash);
                    return(account.GetKey().Export());
                }

            case "invoke":
            case "invokefunction":
            case "invokescript":
                JObject result = base.Process(method, _params);
                if (Program.Wallet != null)
                {
                    InvocationTransaction tx = new InvocationTransaction
                    {
                        Version = 1,
                        Script  = result["script"].AsString().HexToBytes(),
                        Gas     = Fixed8.Parse(result["gas_consumed"].AsString())
                    };
                    tx.Gas -= Fixed8.FromDecimal(10);
                    if (tx.Gas < Fixed8.Zero)
                    {
                        tx.Gas = Fixed8.Zero;
                    }
                    tx.Gas = tx.Gas.Ceiling();
                    tx     = Program.Wallet.MakeTransaction(tx);
                    if (tx != null)
                    {
                        ContractParametersContext context = new ContractParametersContext(tx);
                        Program.Wallet.Sign(context);
                        if (context.Completed)
                        {
                            tx.Scripts = context.GetScripts();
                        }
                        else
                        {
                            tx = null;
                        }
                    }
                    result["tx"] = tx?.ToArray().ToHexString();
                }
                return(result);

            default:
                return(base.Process(method, _params));
            }
        }
Esempio n. 20
0
 public MonitorServerWithWallet(LocalNode localNode, string name, string type)
     : base(localNode)
 {
     this.nodeName = name;
     this.nodeType = type;
 }
Esempio n. 21
0
 internal TransactionExecutionEngine(LocalNode node)
 {
     _node = node;
 }
Esempio n. 22
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    UInt256            assetId = UInt256.Parse(_params[0].AsString());
                    IEnumerable <Coin> coins   = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(assetId));
                    JObject            json    = new JObject();
                    json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                    json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                    return(json);
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt256 assetId        = UInt256.Parse(_params[0].AsString());
                    UInt160 scriptHash     = Wallet.ToScriptHash(_params[1].AsString());
                    Fixed8  value          = Fixed8.Parse(_params[2].AsString());
                    Fixed8  fee            = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    UInt160 change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    if (value <= Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    ContractTransaction tx = Program.Wallet.MakeTransaction(new ContractTransaction
                    {
                        Outputs = new[]
                        {
                            new TransactionOutput
                            {
                                AssetId    = assetId,
                                Value      = value,
                                ScriptHash = scriptHash
                            }
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    SignatureContext context = new SignatureContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.SaveTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    KeyPair  key      = Program.Wallet.CreateKey();
                    Contract contract = Program.Wallet.GetContracts(key.PublicKeyHash).First(p => p.IsStandard);
                    return(contract.Address);
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160 scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    KeyPair key        = Program.Wallet.GetKeyByScriptHash(scriptHash);
                    return(key.Export());
                }

            default:
                return(base.Process(method, _params));
            }
        }
Esempio n. 23
0
        public virtual async Task Start(string[] args)
        {
            if (NeoSystem != null)
            {
                return;
            }
            try
            {
                NeoSystem = new NeoSystem(CliSettings.Default.Protocol, CliSettings.Default.Storage.Engine, CliSettings.Default.Storage.Path);
                NeoSystem.AddService(this);

                LocalNode = await NeoSystem.LocalNode.Ask <LocalNode>(new LocalNode.GetInstance());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            using (IEnumerator <Block> blocksBeingImported = GetBlocksFromFile().GetEnumerator())
            {
                while (true)
                {
                    List <Block> blocksToImport = new List <Block>();
                    for (int i = 0; i < 10; i++)
                    {
                        if (!blocksBeingImported.MoveNext())
                        {
                            break;
                        }
                        blocksToImport.Add(blocksBeingImported.Current);
                    }
                    if (blocksToImport.Count == 0)
                    {
                        break;
                    }
                    await NeoSystem.Blockchain.Ask <Blockchain.ImportCompleted>(new Blockchain.Import {
                        Blocks = blocksToImport
                    });

                    if (NeoSystem is null)
                    {
                        return;
                    }
                }
            }
            NeoSystem.StartNode(new ChannelsConfig
            {
                Tcp                      = new IPEndPoint(IPAddress.Any, CliSettings.Default.P2P.Port),
                WebSocket                = new IPEndPoint(IPAddress.Any, CliSettings.Default.P2P.WsPort),
                MinDesiredConnections    = CliSettings.Default.P2P.MinDesiredConnections,
                MaxConnections           = CliSettings.Default.P2P.MaxConnections,
                MaxConnectionsPerAddress = CliSettings.Default.P2P.MaxConnectionsPerAddress
            });
            if (CliSettings.Default.UnlockWallet.IsActive)
            {
                try
                {
                    OpenWallet(CliSettings.Default.UnlockWallet.Path, CliSettings.Default.UnlockWallet.Password);
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine($"Warning: wallet file \"{CliSettings.Default.UnlockWallet.Path}\" not found.");
                }
                catch (CryptographicException)
                {
                    Console.WriteLine($"failed to open file \"{CliSettings.Default.UnlockWallet.Path}\"");
                }
            }
        }
Esempio n. 24
0
        private void OnTimeout(object state)
        {
            lock (context)
            {
                if (timer_height != context.BlockIndex || timer_view != context.ViewNumber)
                {
                    return;
                }
                Log($"timeout: height={timer_height} view={timer_view} state={context.State}");
                if (context.State.HasFlag(ConsensusState.Primary) && !context.State.HasFlag(ConsensusState.RequestSent))
                {
                    Log($"send prepare request: height={timer_height} view={timer_view}");
                    context.State |= ConsensusState.RequestSent;
                    if (!context.State.HasFlag(ConsensusState.SignatureSent))
                    {
                        context.Timestamp = Math.Max(DateTime.Now.ToTimestamp(), Blockchain.Default.GetHeader(context.PrevHash).Timestamp + 1);
                        context.Nonce     = GetNonce();
                        List <Transaction> transactions = LocalNode.GetMemoryPool().Where(p => CheckPolicy(p)).ToList();

                        Dictionary <UInt160, Transaction> scriptHashDictionary = new Dictionary <UInt160, Transaction>();
                        Console.WriteLine("Mempool count " + transactions.Count.ToString());
                        for (int i = 0; i < transactions.Count; i++)
                        {
                            if (transactions[i].Type == TransactionType.MinerTransaction ||
                                transactions[i].Type == TransactionType.AnonymousContractTransaction ||
                                transactions[i].Type == TransactionType.RingConfidentialTransaction)
                            {
                                continue;
                            }
                            if (transactions[i].Inputs == null || transactions[i].Inputs.Length == 0)
                            {
                                continue;
                            }

                            if (transactions[i].References == null)
                            {
                                transactions.RemoveAt(i);
                                i--;
                                continue;
                            }


                            if (transactions[i].Inputs.Length > 0 &&
                                transactions[i].References.ContainsKey(transactions[i].Inputs[0]) &&
                                LocalNode.KnownHashes.Count > 0)
                            {
                                UInt160 scripthash = transactions[i].References[transactions[i].Inputs[0]].ScriptHash;

                                if (scriptHashDictionary.ContainsKey(scripthash))
                                {
                                    Transaction prevTx = scriptHashDictionary[scripthash];
                                    if (LocalNode.KnownHashes.IndexOf(prevTx.Hash) > LocalNode.KnownHashes.IndexOf(transactions[i].Hash))
                                    {
                                        scriptHashDictionary[scripthash] = transactions[i];
                                        transactions.Remove(prevTx);
                                    }
                                    else
                                    {
                                        transactions.RemoveAt(i);
                                    }

                                    i--;
                                }
                                else
                                {
                                    scriptHashDictionary.Add(scripthash, transactions[i]);
                                }
                            }
                        }


                        Transaction[]      tmpool = LocalNode.GetMemoryPool().ToArray();
                        List <Transaction> consensus_transactions = new List <Transaction>();

                        for (int i = 0; i < transactions.Count; i++)
                        {
                            Transaction tx = transactions[i];
                            if (!tx.Verify(tmpool))
                            {
                                Console.Write("Transaction verify failed : ");

                                transactions.RemoveAt(i);
                                LocalNode.RemoveTxFromMempool(tx.Hash);
                                i--;

                                Console.WriteLine(tx.ToJsonString());
                                continue;
                            }

                            UInt160 fromScriptHash = LocalNode.GetFromAddressFromTx(tx); Console.WriteLine("Step_1_2");

                            if (Blockchain.IsConsensusAddress(fromScriptHash))
                            {
                                consensus_transactions.Add(tx);
                                continue;
                            }
                            else if (tx.GetFee() == Fixed8.Zero && fromScriptHash != UInt160.Zero)
                            {
                                if (LocalNode.freetx_pool.ContainsKey(fromScriptHash) &&
                                    LocalNode.freetx_pool[fromScriptHash].Count >= Blockchain.Default.FreeTransactionLimitPerPeriod &&
                                    Blockchain.Default.Height - LocalNode.freetx_pool[fromScriptHash].ElementAt(LocalNode.freetx_pool[fromScriptHash].Count - 1) < Blockchain.Default.FreeTransactionBlockPeriodNum)
                                {
                                    UInt256 removalHash = transactions[i].Hash;

                                    Console.WriteLine("TX removed " + removalHash);

                                    LocalNode.RemoveTxFromMempool(removalHash);

                                    transactions.RemoveAt(i);
                                    i--;
                                }
                                else
                                {
                                    localNode.AddFreeTxAddressToPool(fromScriptHash);

                                    foreach (RemoteNode node in LocalNode.Default.GetRemoteNodes()) // enqueue message
                                    {
                                        node.EnqueueMessage("blockfree", fromScriptHash);
                                    }
                                }
                            }
                        }

                        if (transactions.Count >= MaxTransactionsPerBlock)
                        {
                            transactions = consensus_transactions.Concat(transactions.OrderByDescending(p => p.NetworkFee / p.Size).Take(MaxTransactionsPerBlock - 1 - consensus_transactions.Count).ToList()).ToList();
                        }

                        transactions.Insert(0, CreateMinerTransaction(transactions, context.BlockIndex, context.Nonce));
                        context.TransactionHashes           = transactions.Select(p => p.Hash).ToArray();
                        context.Transactions                = transactions.ToDictionary(p => p.Hash);
                        context.CurrentConsensus            = wallet.GetChangeAddress();
                        context.NextConsensus               = Blockchain.GetConsensusAddress(Blockchain.Default.GetValidators(transactions).ToArray());
                        context.Signatures[context.MyIndex] = context.MakeHeader().Sign((KeyPair)wallet.GetKey(context.Validators[context.MyIndex]));
                    }
                    SignAndRelay(context.MakePrepareRequest());
                    timer.Change(TimeSpan.FromSeconds(Blockchain.SecondsPerBlock << (timer_view + 1)), Timeout.InfiniteTimeSpan);
                }
                else if ((context.State.HasFlag(ConsensusState.Primary) && context.State.HasFlag(ConsensusState.RequestSent)) || context.State.HasFlag(ConsensusState.Backup))
                {
                    RequestChangeView();
                }
            }
        }
Esempio n. 25
0
        private void OnPrepareRequestReceived(ConsensusPayload payload, PrepareRequest message)
        {
            Log($"{nameof(OnPrepareRequestReceived)}: height={payload.BlockIndex} view={message.ViewNumber} index={payload.ValidatorIndex} tx={message.TransactionHashes.Length}");
            if (!context.State.HasFlag(ConsensusState.Backup) || context.State.HasFlag(ConsensusState.RequestReceived))
            {
                return;
            }
            if (payload.ValidatorIndex != context.PrimaryIndex)
            {
                return;
            }
            if (payload.Timestamp <= Blockchain.Default.GetHeader(context.PrevHash).Timestamp || payload.Timestamp > DateTime.Now.AddMinutes(10).ToTimestamp())
            {
                Log($"Timestamp incorrect: {payload.Timestamp}");
                return;
            }
            context.State            |= ConsensusState.RequestReceived;
            context.Timestamp         = payload.Timestamp;
            context.Nonce             = message.Nonce;
            context.CurrentConsensus  = message.CurrentConsensus;
            context.NextConsensus     = message.NextConsensus;
            context.TransactionHashes = message.TransactionHashes;
            if (context.TransactionHashes.Length > MaxTransactionsPerBlock)
            {
                return;
            }
            context.Transactions = new Dictionary <UInt256, Transaction>();
            if (!Crypto.Default.VerifySignature(context.MakeHeader().GetHashData(), message.Signature, context.Validators[payload.ValidatorIndex].EncodePoint(false)))
            {
                return;
            }
            context.Signatures = new byte[context.Validators.Length][];
            context.Signatures[payload.ValidatorIndex] = message.Signature;
            Dictionary <UInt256, Transaction> mempool = LocalNode.GetMemoryPool().ToDictionary(p => p.Hash);

            foreach (UInt256 hash in context.TransactionHashes.Skip(1))
            {
                if (mempool.TryGetValue(hash, out Transaction tx))
                {
                    Console.WriteLine("No Verify Add Transaction" + tx.is_consensus_mempool);
                    if (!AddTransaction(tx, true))
                    {
                        return;
                    }
                }
            }
            if (!AddTransaction(message.MinerTransaction, true))
            {
                return;
            }
            if (context.Transactions.Count < context.TransactionHashes.Length)
            {
                LocalNode.AllowHashes(context.TransactionHashes.Except(context.Transactions.Keys));
                UInt256[]  hashes = context.TransactionHashes.ToArray();         // get hashes
                InvPayload msg    = InvPayload.Create(InventoryType.TX, hashes); // create message
                foreach (RemoteNode node in localNode.GetRemoteNodes())          // enqueue message
                {
                    node.EnqueueMessage("getdata", msg);
                }
            }
        }
Esempio n. 26
0
 private JObject GetConnectionCount(LocalNode localNode)
 {
     return(localNode.ConnectedCount);
 }
Esempio n. 27
0
        public async void Start(string[] args)
        {
            if (NeoSystem != null)
            {
                return;
            }
            bool verifyImport = true;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "/noverify":
                case "--noverify":
                    verifyImport = false;
                    break;
                }
            }

            _ = new Logger();

            NeoSystem = new NeoSystem(ProtocolSettings.Load("config.json"), Settings.Default.Storage.Engine, Settings.Default.Storage.Path);

            NeoSystem.AddService(this);

            LocalNode = NeoSystem.LocalNode.Ask <LocalNode>(new LocalNode.GetInstance()).Result;

            foreach (var plugin in Plugin.Plugins)
            {
                // Register plugins commands

                RegisterCommand(plugin, plugin.Name);
            }

            using (IEnumerator <Block> blocksBeingImported = GetBlocksFromFile().GetEnumerator())
            {
                while (true)
                {
                    List <Block> blocksToImport = new List <Block>();
                    for (int i = 0; i < 10; i++)
                    {
                        if (!blocksBeingImported.MoveNext())
                        {
                            break;
                        }
                        blocksToImport.Add(blocksBeingImported.Current);
                    }
                    if (blocksToImport.Count == 0)
                    {
                        break;
                    }
                    await NeoSystem.Blockchain.Ask <Blockchain.ImportCompleted>(new Blockchain.Import
                    {
                        Blocks = blocksToImport,
                        Verify = verifyImport
                    });

                    if (NeoSystem is null)
                    {
                        return;
                    }
                }
            }
            NeoSystem.StartNode(new ChannelsConfig
            {
                Tcp                      = new IPEndPoint(IPAddress.Any, Settings.Default.P2P.Port),
                WebSocket                = new IPEndPoint(IPAddress.Any, Settings.Default.P2P.WsPort),
                MinDesiredConnections    = Settings.Default.P2P.MinDesiredConnections,
                MaxConnections           = Settings.Default.P2P.MaxConnections,
                MaxConnectionsPerAddress = Settings.Default.P2P.MaxConnectionsPerAddress
            });

            if (Settings.Default.UnlockWallet.IsActive)
            {
                try
                {
                    OpenWallet(Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password);
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine($"Warning: wallet file \"{Settings.Default.UnlockWallet.Path}\" not found.");
                }
                catch (System.Security.Cryptography.CryptographicException)
                {
                    Console.WriteLine($"Failed to open file \"{Settings.Default.UnlockWallet.Path}\"");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"error: {ex.GetBaseException().Message}");
                }
            }
        }
 public RpcServer(LocalNode localNode, bool isRPC)
 {
     this.LocalNode = localNode;
     IsRPC          = isRPC;
 }
Esempio n. 29
0
        internal static void Main(string[] args)
        {
            var connectToRunningGame = false;
            var options = new OptionSet
            {
                { "connect", "Internal use only (used by the game client).", v => connectToRunningGame = true }
            };

            try
            {
                options.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.Write("ProtogameAssetManager.exe: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try `ProtogameAssetManager.exe --help` for more information.");
                return;
            }

            // Deploy the correct MojoShader DLL.
            MojoShaderDeploy.Deploy();

            var kernel = new StandardKernel();

            kernel.Load <Protogame2DIoCModule>();
            kernel.Load <ProtogameAssetIoCModule>();
            kernel.Load <ProtogameEventsIoCModule>();
            kernel.Load <ProtogamePlatformingIoCModule>();
            kernel.Load <AssetManagerIoCModule>();

            // Only allow the source load strategies.
            kernel.Unbind <ILoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <RawTextureLoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <RawModelLoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <RawEffectLoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <LocalSourceLoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <EmbeddedSourceLoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <EmbeddedCompiledLoadStrategy>();

            var runningFile          = new FileInfo(Assembly.GetExecutingAssembly().Location);
            var workingDirectoryInfo = new DirectoryInfo(Environment.CurrentDirectory);
            var scannedUnique        = new List <string>();

            foreach (var file in runningFile.Directory.GetFiles("*.dll"))
            {
                if (scannedUnique.Contains(file.FullName))
                {
                    continue;
                }
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in runningFile.Directory.GetFiles("*.exe"))
            {
                if (scannedUnique.Contains(file.FullName))
                {
                    continue;
                }
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in workingDirectoryInfo.GetFiles("*.dll"))
            {
                if (scannedUnique.Contains(file.FullName))
                {
                    continue;
                }
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in workingDirectoryInfo.GetFiles("*.exe"))
            {
                if (scannedUnique.Contains(file.FullName))
                {
                    continue;
                }
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }

#if FALSE
            if (connectToRunningGame)
            {
                var node = new LocalNode(Architecture.ServerClient, Caching.PushOnChange);
                node.Bind(IPAddress.Loopback, 9837);
                node.GetService <IClientConnector>().Connect(IPAddress.Loopback, 9838);
                var assetManagerProvider = new NetworkedAssetManagerProvider(node, kernel);
                kernel.Bind <IAssetManagerProvider>().ToMethod(x => assetManagerProvider);
            }
            else
#endif
            kernel.Bind <IAssetManagerProvider>().To <LocalAssetManagerProvider>().InSingletonScope();

            using (var game = new AssetManagerGame(kernel))
            {
                game.Run();
            }
        }
Esempio n. 30
0
 public Coins(Wallet wallet, LocalNode node)
 {
     current_wallet = wallet;
     local_node     = node;
 }
Esempio n. 31
0
 protected void OnStart(bool useRPC = false, bool nopeers = false, bool useLog = false)
 {
     Blockchain.RegisterBlockchain(new LevelDBBlockchain(Path.GetFullPath(Settings.Default.Paths.Chain)));
     if (!nopeers && File.Exists(PeerStatePath))
     {
         using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
         {
             LocalNode.LoadState(fs);
         }
     }
     LocalNode = new LocalNode();
     if (useLog)
     {
         LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
     }
     Task.Run(() =>
     {
         const string path_acc = "chain.acc";
         if (File.Exists(path_acc))
         {
             using (FileStream fs = new FileStream(path_acc, FileMode.Open, FileAccess.Read, FileShare.None))
             {
                 ImportBlocks(fs);
             }
         }
         const string path_acc_zip = path_acc + ".zip";
         if (File.Exists(path_acc_zip))
         {
             using (FileStream fs = new FileStream(path_acc_zip, FileMode.Open, FileAccess.Read, FileShare.None))
                 using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                     using (Stream zs = zip.GetEntry(path_acc).Open())
                     {
                         ImportBlocks(zs);
                     }
         }
         var paths = Directory.EnumerateFiles(".", "chain.*.acc", SearchOption.TopDirectoryOnly).Concat(Directory.EnumerateFiles(".", "chain.*.acc.zip", SearchOption.TopDirectoryOnly)).Select(p => new
         {
             FileName     = Path.GetFileName(p),
             Start        = uint.Parse(Regex.Match(p, @"\d+").Value),
             IsCompressed = p.EndsWith(".zip")
         }).OrderBy(p => p.Start);
         foreach (var path in paths)
         {
             if (path.Start > Blockchain.Default.Height + 1)
             {
                 break;
             }
             if (path.IsCompressed)
             {
                 using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                     using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                         using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open())
                         {
                             ImportBlocks(zs, true);
                         }
             }
             else
             {
                 using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                 {
                     ImportBlocks(fs, true);
                 }
             }
         }
         LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
         if (useRPC)
         {
             rpc = new RpcServerWithWallet(LocalNode);
             rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword);
         }
     });
 }
        protected internal override void OnStart(string[] args)
        {
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Settings.Default.DataDirectoryPath));
            if (File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }

            // Load Verify Key
            string vk_path = ".//crypto//vk.key";
            string pk_path = ".//crypto//pk.key";

            int ret = SnarkDllApi.Snark_DllInit(1, vk_path.ToArray(), pk_path.ToArray());

            if (ret > 0)
            {
                Console.WriteLine($"Verify key loading success");
            }
            else
            {
                Console.WriteLine($"Verify key loading unseccess");
            }

            LocalNode = new LocalNode();
            Task.Run(() =>
            {
                const string acc_path     = "chain.acc";
                const string acc_zip_path = acc_path + ".zip";
                if (File.Exists(acc_path))
                {
                    using (FileStream fs = new FileStream(acc_path, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                    File.Delete(acc_path);
                }
                else if (File.Exists(acc_zip_path))
                {
                    using (FileStream fs = new FileStream(acc_zip_path, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(acc_path).Open())
                            {
                                ImportBlocks(zs);
                            }
                    File.Delete(acc_zip_path);
                }
                LocalNode.Start(Settings.Default.NodePort, Settings.Default.WsPort);
                bool recordNotifications = false;
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "/rpc":
                    case "--rpc":
                    case "-r":
                        if (rpc == null)
                        {
                            rpc = new RpcServerWithWallet(LocalNode);
                            rpc.Start(Settings.Default.UriPrefix.OfType <string>().ToArray(), Settings.Default.SslCert, Settings.Default.SslCertPassword);
                        }
                        break;

                    case "--record-notifications":
                        recordNotifications = true;
                        break;
                    }
                }
                if (recordNotifications)
                {
                    Blockchain.Notify += Blockchain_Notify;
                }
            });
        }
Esempio n. 33
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getapplicationlog":
            {
                UInt256 hash = UInt256.Parse(_params[0].AsString());
                string  path = Path.Combine(Settings.Default.Paths.ApplicationLogs, $"{hash}.json");
                return(File.Exists(path)
                            ? JObject.Parse(File.ReadAllText(path))
                            : throw new RpcException(-100, "Unknown transaction"));
            }

            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    UInt256            assetId = UInt256.Parse(_params[0].AsString());
                    IEnumerable <Coin> coins   = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(assetId));
                    JObject            json    = new JObject();
                    json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                    json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                    return(json);
                }

            case "listaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    return(Program.Wallet.GetAccounts().Select(p =>
                    {
                        JObject account = new JObject();
                        account["address"] = p.Address;
                        account["haskey"] = p.HasKey;
                        account["label"] = p.Label;
                        account["watchonly"] = p.WatchOnly;
                        return account;
                    }).ToArray());
                }

            case "sendfrom":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = Wallet.ToScriptHash(_params[1].AsString());
                    UInt160         to         = Wallet.ToScriptHash(_params[2].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 6 ? Wallet.ToScriptHash(_params[5].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = Wallet.ToScriptHash(to[i]["address"].AsString())
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? Wallet.ToScriptHash(_params[2].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = Program.Wallet.CreateAccount();
                    if (Program.Wallet is NEP6Wallet wallet)
                    {
                        wallet.Save();
                    }
                    return(account.Address);
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160       scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    WalletAccount account    = Program.Wallet.GetAccount(scriptHash);
                    return(account.GetKey().Export());
                }

            case "invoke":
            case "invokefunction":
            case "invokescript":
                JObject result = base.Process(method, _params);
                if (Program.Wallet != null)
                {
                    InvocationTransaction tx = new InvocationTransaction
                    {
                        Version = 1,
                        Script  = result["script"].AsString().HexToBytes(),
                        Benz    = Fixed8.Parse(result["benz_consumed"].AsString())
                    };
                    tx.Benz -= Fixed8.FromDecimal(10);
                    if (tx.Benz < Fixed8.Zero)
                    {
                        tx.Benz = Fixed8.Zero;
                    }
                    tx.Benz = tx.Benz.Ceiling();
                    tx      = Program.Wallet.MakeTransaction(tx);
                    if (tx != null)
                    {
                        ContractParametersContext context = new ContractParametersContext(tx);
                        Program.Wallet.Sign(context);
                        if (context.Completed)
                        {
                            tx.Scripts = context.GetScripts();
                        }
                        else
                        {
                            tx = null;
                        }
                    }
                    result["tx"] = tx?.ToArray().ToHexString();
                }
                return(result);

            default:
                return(base.Process(method, _params));
            }
        }
Esempio n. 34
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    UInt256            assetId = UInt256.Parse(_params[0].AsString());
                    IEnumerable <Coin> coins   = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(assetId));
                    JObject            json    = new JObject();
                    json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                    json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                    return(json);
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = Wallet.ToScriptHash(to[i]["address"].AsString())
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? Wallet.ToScriptHash(_params[2].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    return(Program.Wallet.CreateAccount().Address);
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160       scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    WalletAccount account    = Program.Wallet.GetAccount(scriptHash);
                    return(account.GetKey().Export());
                }

            case "invoke":
            case "invokefunction":
            case "invokescript":
                JObject result = base.Process(method, _params);
                if (Program.Wallet != null)
                {
                    InvocationTransaction tx = new InvocationTransaction
                    {
                        Version = 1,
                        Script  = result["script"].AsString().HexToBytes(),
                        Gas     = Fixed8.Parse(result["gas_consumed"].AsString())
                    };
                    tx.Gas -= Fixed8.FromDecimal(10);
                    if (tx.Gas < Fixed8.Zero)
                    {
                        tx.Gas = Fixed8.Zero;
                    }
                    tx.Gas = tx.Gas.Ceiling();
                    tx     = Program.Wallet.MakeTransaction(tx);
                    if (tx != null)
                    {
                        ContractParametersContext context = new ContractParametersContext(tx);
                        Program.Wallet.Sign(context);
                        if (context.Completed)
                        {
                            tx.Scripts = context.GetScripts();
                        }
                        else
                        {
                            tx = null;
                        }
                    }
                    result["tx"] = tx?.ToArray().ToHexString();
                }
                return(result);

            default:
                return(base.Process(method, _params));
            }
        }
Esempio n. 35
0
        public void NodeIsReusable()
        {
            this.AssertNoActiveConnections();

            var other = new LocalNode();
            var node = new LocalNode();

            try
            {
                other.Bind(IPAddress.Loopback, 12002);

                node.Bind(IPAddress.Loopback, 12000);
                node.GetService<IClientConnector>().Connect(IPAddress.Loopback, 12002);
                Assert.Equal(2, node.GetService<IClientLookup>().GetAll().Count());
                node.Close();
                node.Bind(IPAddress.Loopback, 12001);
                Assert.Equal(1, node.GetService<IClientLookup>().GetAll().Count());
            }
            finally
            {
                other.Close();
                node.Close();
            }

            this.AssertNoActiveConnections();
        }
Esempio n. 36
0
 public ConsensusService(LocalNode localNode, Wallet wallet)
 {
     this.localNode = localNode;
     this.wallet    = wallet;
     this.timer     = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
 }
Esempio n. 37
0
        protected internal override void OnStart(string[] args)
        {
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Settings.Default.Paths.Chain));
            if (!args.Contains("--nopeers") && File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }
            LocalNode = new LocalNode();
            Task.Run(() =>
            {
                const string acc_path     = "chain.acc";
                const string acc_zip_path = acc_path + ".zip";
                if (File.Exists(acc_path))
                {
                    using (FileStream fs = new FileStream(acc_path, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                    File.Delete(acc_path);
                }
                else if (File.Exists(acc_zip_path))
                {
                    using (FileStream fs = new FileStream(acc_zip_path, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(acc_path).Open())
                            {
                                ImportBlocks(zs);
                            }
                    File.Delete(acc_zip_path);
                }
                LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
                bool log = false;
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "/rpc":
                    case "--rpc":
                    case "-r":
                        if (rpc == null)
                        {
                            rpc = new RpcServerWithWallet(LocalNode);
                            rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword);
                        }
                        break;

                    case "-l":
                    case "--log":
                        log = true;
                        break;
                    }
                }
                if (log)
                {
                    LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
                }
            });
        }
Esempio n. 38
0
 public RpcServer(LocalNode localNode)
 {
     this.LocalNode = localNode;
 }
Esempio n. 39
0
        public JObject Process(string method, JArray _params)
        {
            try
            {
                switch (method)
                {
                case "getbestblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBestBlockHash(blockchain));
                }

                case "getblock":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlock(blockchain, key, verbose));
                }

                case "getblockcount":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBlockCount(blockchain));
                }

                case "getblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockHash(blockchain, height));
                }

                case "getblockheader":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlockHeader(blockchain, key, verbose));
                }

                case "getblocksysfee":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockSysFee(blockchain, height));
                }

                case "getconnectioncount":
                {
                    LocalNode localNode = GetTargetNode(_params[0]);
                    return(localNode != null ? localNode.ConnectedCount : 0);
                }

                case "getcontractstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    return(GetContractState(blockchain, script_hash));
                }

                case "getpeers":
                {
                    return(GetPeers(_params[0]));
                }

                case "getrawmempool":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPool(blockchain, shouldGetUnverified));
                }

                case "getrawmempoolcount":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPoolCount(blockchain, shouldGetUnverified));
                }

                case "getrawtransaction":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetRawTransaction(blockchain, hash, verbose));
                }

                case "getstorage":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    byte[]     key         = _params[2].AsString().HexToBytes();
                    return(GetStorage(blockchain, script_hash, key));
                }

                case "gettransactionheight":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    return(GetTransactionHeight(blockchain, hash));
                }

                case "getvalidators":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetValidators(blockchain));
                }

                case "getversion":
                {
                    return(GetVersion());
                }

                case "invokefunction":
                {
                    UInt160             script_hash = UInt160.Parse(_params[1].AsString());
                    string              operation   = _params[2].AsString();
                    ContractParameter[] args        = _params.Count >= 4 ? ((JArray)_params[3]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                    return(InvokeFunction(_params[0], script_hash, operation, args));
                }

                case "invokescript":
                {
                    byte[] script = _params[1].AsString().HexToBytes();
                    return(InvokeScript(_params[0], script));
                }

                case "listplugins":
                {
                    return(ListPlugins());
                }

                case "sendrawtransaction":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Transaction tx = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                        return(SendRawTransaction(targetSystem, tx));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "submitblock":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                        return(SubmitBlock(targetSystem, block));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "validateaddress":
                {
                    string address = _params[0].AsString();
                    return(ValidateAddress(address));
                }

                case "getappchainhashlist":
                {
                    return(GetAppChainHashList());
                }

                case "getappchainstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[0].AsString());
                    return(GetAppChainState(blockchain, script_hash));
                }

                case "getappchainlist":
                {
                    return(GetAppChainList());
                }

                case "getappchainlistenerports":
                {
                    return(GetAppChainListenerPorts());
                }

                case "estimategas":
                {
                    Blockchain  blockchain = GetTargetChain(_params[0]);
                    Transaction tx         = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                    return(GetEstimateGas(blockchain, tx));
                }

                default:
                    throw new RpcException(-32601, "Method not found");
                }
            }
            catch (Exception ex)
            {
                JObject json = new JObject();
                json["message"] = ex.Message;
                json["method"]  = method;
                json["source"]  = ex.Source;
                return(json);
            }
        }
Esempio n. 40
0
        internal static void Main(string[] args)
        {
            var connectToRunningGame = false;
            var options = new OptionSet
            {
                { "connect", "Internal use only (used by the game client).", v => connectToRunningGame = true }
            };
            try
            {
                options.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.Write("ProtogameAssetManager.exe: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try `ProtogameAssetManager.exe --help` for more information.");
                return;
            }

            // Deploy the correct MojoShader DLL.
            MojoShaderDeploy.Deploy();

            var kernel = new StandardKernel();
            kernel.Load<Protogame2DIoCModule>();
            kernel.Load<ProtogameAssetIoCModule>();
            kernel.Load<ProtogameEventsIoCModule>();
            kernel.Load<ProtogamePlatformingIoCModule>();
            kernel.Load<AssetManagerIoCModule>();

            // Only allow the source load strategies.
            kernel.Unbind<ILoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<RawTextureLoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<RawModelLoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<RawEffectLoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<LocalSourceLoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<EmbeddedSourceLoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<EmbeddedCompiledLoadStrategy>();

            var runningFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
            var workingDirectoryInfo = new DirectoryInfo(Environment.CurrentDirectory);
            var scannedUnique = new List<string>();
            foreach (var file in runningFile.Directory.GetFiles("*.dll"))
            {
                if (scannedUnique.Contains(file.FullName))
                    continue;
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in runningFile.Directory.GetFiles("*.exe"))
            {
                if (scannedUnique.Contains(file.FullName))
                    continue;
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in workingDirectoryInfo.GetFiles("*.dll"))
            {
                if (scannedUnique.Contains(file.FullName))
                    continue;
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }
            foreach (var file in workingDirectoryInfo.GetFiles("*.exe"))
            {
                if (scannedUnique.Contains(file.FullName))
                    continue;
                Console.WriteLine("Scanning " + file.Name);
                try
                {
                    RegisterEditorsFromAssembly(Assembly.LoadFrom(file.FullName), kernel);
                    scannedUnique.Add(file.FullName);
                }
                catch (BadImageFormatException) { }
                catch (FileLoadException) { }
            }

            #if FALSE
            if (connectToRunningGame)
            {
                var node = new LocalNode(Architecture.ServerClient, Caching.PushOnChange);
                node.Bind(IPAddress.Loopback, 9837);
                node.GetService<IClientConnector>().Connect(IPAddress.Loopback, 9838);
                var assetManagerProvider = new NetworkedAssetManagerProvider(node, kernel);
                kernel.Bind<IAssetManagerProvider>().ToMethod(x => assetManagerProvider);
            }
            else
            #endif
                kernel.Bind<IAssetManagerProvider>().To<LocalAssetManagerProvider>().InSingletonScope();

            using (var game = new AssetManagerGame(kernel))
            {
                game.Run();
            }
        }
Esempio n. 41
0
 public void CanBindNode()
 {
     var node = new LocalNode();
     node.Bind(IPAddress.Loopback, 9000);
     node.Close();
 }
Esempio n. 42
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    UInt256            assetId = UInt256.Parse(_params[0].AsString());
                    IEnumerable <Coin> coins   = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(assetId));
                    JObject            json    = new JObject();
                    json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                    json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                    return(json);
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.SaveTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = Wallet.ToScriptHash(to[i]["address"].AsString())
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? Wallet.ToScriptHash(_params[2].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.SaveTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    KeyPair key = (KeyPair)Program.Wallet.CreateKey();
                    VerificationContract contract = Program.Wallet.GetContracts(key.PublicKeyHash).First(p => p.IsStandard);
                    return(contract.Address);
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160 scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    KeyPair key        = (KeyPair)Program.Wallet.GetKeyByScriptHash(scriptHash);
                    return(key.Export());
                }

            default:
                return(base.Process(method, _params));
            }
        }
 public RpcServerWithWallet(LocalNode localNode, bool isRPC)
     : base(localNode, isRPC)
 {
 }
Esempio n. 44
0
        private JObject InternalCall(string method, JArray _params)
        {
            switch (method)
            {
            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    UInt256            assetId = UInt256.Parse(_params[0].AsString());
                    IEnumerable <Coin> coins   = Program.Wallet.FindCoins().Where(p => p.AssetId.Equals(assetId));
                    JObject            json    = new JObject();
                    json["balance"]   = coins.Where(p => p.State == CoinState.Unspent || p.State == CoinState.Unconfirmed).Sum(p => p.Value).ToString();
                    json["confirmed"] = coins.Where(p => p.State == CoinState.Unspent).Sum(p => p.Value).ToString();
                    return(json);
                }

            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Default.Height - block.Height + 1;
                    UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                return(Blockchain.Default.GetBlockHash(height).ToString());
            }

            case "getconnectioncount":
                return(localNode.RemoteNodeCount);

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                int         height  = -1;
                Transaction tx      = LocalNode.GetTransaction(hash);
                if (tx == null)
                {
                    tx = Blockchain.Default.GetTransaction(hash, out height);
                }
                if (tx == null)
                {
                    throw new RpcException(-101, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json = tx.ToJson();
                    if (height >= 0)
                    {
                        Header header = Blockchain.Default.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Default.Height - header.Height + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(localNode.Relay(tx));
            }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt256 assetId    = UInt256.Parse(_params[0].AsString());
                    UInt160 scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    Fixed8  value      = Fixed8.Parse(_params[2].AsString());
                    Fixed8  fee        = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (value <= Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    ContractTransaction tx = Program.Wallet.MakeTransaction(new ContractTransaction
                    {
                        Outputs = new[]
                        {
                            new TransactionOutput
                            {
                                AssetId    = assetId,
                                Value      = value,
                                ScriptHash = scriptHash
                            }
                        }
                    }, fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    SignatureContext context = new SignatureContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.SaveTransaction(tx);
                        localNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(localNode.Relay(block));
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Esempio n. 45
0
        protected internal override void OnStart(string[] args)
        {
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Settings.Default.Paths.Chain,
                                                                Settings.Default.Paths.Fulllogs,
                                                                Settings.Default.Paths.fulllog_splitcount,
                                                                Settings.Default.Paths.fulllog_splitindex));
            if (!args.Contains("--nopeers") && File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }
            LocalNode = new LocalNode();
            Task.Run(() =>
            {
                const string acc_path     = "chain.acc";
                const string acc_zip_path = acc_path + ".zip";
                if (File.Exists(acc_path))
                {
                    using (FileStream fs = new FileStream(acc_path, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                    File.Delete(acc_path);
                }
                else if (File.Exists(acc_zip_path))
                {
                    using (FileStream fs = new FileStream(acc_zip_path, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(acc_path).Open())
                            {
                                ImportBlocks(zs);
                            }
                    File.Delete(acc_zip_path);
                }
                LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);

                //open rpc & notifications for default

                //bool recordNotifications = false;
                //for (int i = 0; i < args.Length; i++)
                //{
                //    switch (args[i])
                //    {
                //        case "/rpc":
                //        case "--rpc":
                //        case "-r":
                //if (rpc == null)
                //{
                rpc = new RpcServerWithWallet(LocalNode);
                rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword,
                          Settings.Default.Paths.ApplicationLogs,
                          Settings.Default.Paths.Fulllogs
                          );
                //}
                //            break;
                //        case "--record-notifications":
                //            recordNotifications = true;
                //            break;
                //    }
                //}
                //if (recordNotifications)
                LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
            });
        }