Ejemplo n.º 1
0
        public async Task TestDeployContract()
        {
            byte[] script;
            var    manifest = new ContractManifest()
            {
                Permissions = new[] { ContractPermission.DefaultPermission },
                Abi         = new ContractAbi()
                {
                    Events  = new ContractEventDescriptor[0],
                    Methods = new ContractMethodDescriptor[0]
                },
                Groups             = new ContractGroup[0],
                Trusts             = WildcardContainer <ContractPermissionDescriptor> .Create(),
                SupportedStandards = new string[]
                {
                    "NEP-10"
                },
                Extra = null,
            };

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitDynamicCall(NativeContract.ContractManagement.Hash, "deploy", new byte[1], manifest.ToJson().ToString());
                script = sb.ToArray();
            }

            UT_TransactionManager.MockInvokeScript(rpcClientMock, script, new ContractParameter());

            ContractClient contractClient = new ContractClient(rpcClientMock.Object);
            var            result         = await contractClient.CreateDeployContractTxAsync(new byte[1], manifest, keyPair1);

            Assert.IsNotNull(result);
        }
Ejemplo n.º 2
0
    public async Task GivenNoContract_WhenCreated_ShouldVerify()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        var query = new QueryParameter()
        {
            Filter    = "test/unit-tests-smart",
            Recursive = false,
        };

        IReadOnlyList <string> search = (await client.Search(query).ReadNext()).Records;

        if (search.Any(x => x == (string)documentId))
        {
            await client.Delete(documentId);
        }

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        await client.Create(blkHeader);

        BlockChainModel model = await client.Get(documentId);

        model.Should().NotBeNull();
        model.Blocks.Should().NotBeNull();
        model.Blocks.Count.Should().Be(2);

        model.Blocks[0].Should().NotBeNull();
        model.Blocks[0].IsValid().Should().BeTrue();

        model.Blocks[1].Should().NotBeNull();
        model.Blocks[1].IsValid().Should().BeTrue();
        model.Blocks[1].DataBlock.Should().NotBeNull();
        model.Blocks[1].DataBlock.BlockType.Should().Be(typeof(BlkHeader).Name);

        bool isValid = await client.Validate(model);

        isValid.Should().BeTrue();


        BatchSet <string> searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        searchList.Records.Any(x => x.EndsWith(documentId.Path)).Should().BeTrue();

        (await client.Delete(documentId)).Should().BeTrue();

        searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        searchList.Records.Any(x => x.EndsWith(documentId.Path)).Should().BeFalse();
    }
Ejemplo n.º 3
0
        public void TestDeployContract()
        {
            byte[] script;
            var    manifest = new ContractManifest()
            {
                Permissions = new[] { ContractPermission.DefaultPermission },
                Abi         = new ContractAbi()
                {
                    Hash    = new byte[1].ToScriptHash(),
                    Events  = new ContractEventDescriptor[0],
                    Methods = new ContractMethodDescriptor[0]
                },
                Groups      = new ContractGroup[0],
                SafeMethods = WildcardContainer <string> .Create(),
                Trusts      = WildcardContainer <UInt160> .Create(),
                Extra       = null,
            };

            manifest.Features = ContractFeatures.HasStorage | ContractFeatures.Payable;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitSysCall(ApplicationEngine.System_Contract_Create, new byte[1], manifest.ToString());
                script = sb.ToArray();
            }

            UT_TransactionManager.MockInvokeScript(rpcClientMock, script, new ContractParameter());

            ContractClient contractClient = new ContractClient(rpcClientMock.Object);
            var            result         = contractClient.CreateDeployContractTx(new byte[1], manifest, keyPair1);

            Assert.IsNotNull(result);
        }
Ejemplo n.º 4
0
    private async Task Delete(DocumentId documentId, bool shouldExist)
    {
        ContractClient client = TestApplication.GetContractClient();

        var query = new QueryParameter()
        {
            Filter    = documentId.Id.Split('/').Reverse().Skip(1).Reverse().Join("/"),
            Recursive = false,
        };

        BatchSet <string> searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        bool exists = searchList.Records.Any(x => x.EndsWith(documentId.Path));

        if (!shouldExist && !exists)
        {
            return;
        }
        exists.Should().BeTrue();

        (await client.Delete(documentId)).Should().BeTrue();

        searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        searchList.Records.Any(x => x.EndsWith(documentId.Path)).Should().BeFalse();
    }
Ejemplo n.º 5
0
        public void Bootstrap()
        {
            IContractCallback contractCallback = new CallBk();
            InstanceContext   cntxt            = new InstanceContext(contractCallback);
            ContractClient    client           = new ContractClient(cntxt);

            MessageBox.Show(client.GetConnectionConfirmation(true), "Status Check", MessageBoxButton.OKCancel);
        }
Ejemplo n.º 6
0
        private static async Task QueryMethod(IClient client, string method, string[] arguments)
        {
            // ContractClient has access to asset endpoints
            var contractClient = new ContractClient(client);

            var result = await contractClient.QueryContractAsync(s_AssemblyId, ContractName, InstanceName, method, arguments);

            Console.WriteLine($"value={result.Value}");
        }
Ejemplo n.º 7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         IContractCallback contractCallback = new CallBk();
         InstanceContext   cntxt            = new InstanceContext(contractCallback);
         client = new ContractClient(cntxt, "WSDualHttpBinding_IContract");
     }
 }
Ejemplo n.º 8
0
        public void TestInvoke()
        {
            byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", UInt160.Zero);
            UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.ByteArray, Value = "00e057eb481b".HexToBytes() });

            ContractClient contractClient = new ContractClient(rpcClientMock.Object);
            var result = contractClient.TestInvoke(NativeContract.GAS.Hash, "balanceOf", UInt160.Zero);

            Assert.AreEqual(30000000000000L, (long)result.Stack[0].ToStackItem().GetBigInteger());
        }
Ejemplo n.º 9
0
 void DisconnectUser()
 {
     if (isConnected)
     {
         client.Disconnect(id);
         tbUserName.IsEnabled = true;
         client = null;
         btConDiscon.Content = "Connect";
         isConnected         = false;
     }
 }
Ejemplo n.º 10
0
 void ConnectUser()
 {
     if (!isConnected)
     {
         client = new ContractClient(new InstanceContext(this));
         btConDiscon.Content  = "Disconnect";
         isConnected          = true;
         tbUserName.IsEnabled = false;
         id = client.Connect(tbUserName.Text);
     }
 }
Ejemplo n.º 11
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         IContractCallback contractCallback = new CallBk();
         InstanceContext   cntxt            = new InstanceContext(contractCallback);
         client = new ContractClient(cntxt, "WSDualHttpBinding_IContract");
         lbl_confirmation.Text = client.GetConnectionConfirmation();
     }
     catch (Exception exception) {
         lbl_confirmation.Text = exception.Message;
         app.Visible           = false;
     }
 }
Ejemplo n.º 12
0
    public async Task GivenBlockChain_WhenFile_WillRoundTrip()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        await Delete(documentId, false);

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        BlockChain blockChain = new BlockChainBuilder()
                                .SetPrincipleId(blkHeader.PrincipalId)
                                .Build()
                                .Add(blkHeader, blkHeader.PrincipalId);

        BlockChainModel signedBlockChainModel = await client.Sign(blockChain.ToBlockChainModel());

        signedBlockChainModel.Should().NotBeNull();

        await client.Set(documentId, signedBlockChainModel);

        BlockChainModel readBlockChainModel = await client.Get(documentId);

        readBlockChainModel.Should().NotBeNull();

        readBlockChainModel.Blocks.Count.Should().Be(signedBlockChainModel.Blocks.Count);
        readBlockChainModel.Blocks
        .Zip(signedBlockChainModel.Blocks)
        .All(x => x.First == x.Second)
        .Should().BeTrue();

        bool isValid = await client.Validate(documentId);

        isValid.Should().BeTrue();

        isValid = await client.Validate(readBlockChainModel);

        isValid.Should().BeTrue();

        await Delete(documentId, true);
    }
Ejemplo n.º 13
0
        public void TestDeployContract()
        {
            byte[] script;
            var manifest = ContractManifest.CreateDefault(new byte[1].ToScriptHash());
            manifest.Features = ContractFeatures.HasStorage | ContractFeatures.Payable;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitSysCall(InteropService.Neo_Contract_Create, new byte[1], manifest.ToString());
                script = sb.ToArray();
            }

            UT_TransactionManager.MockInvokeScript(rpcClientMock, script, new ContractParameter());

            ContractClient contractClient = new ContractClient(rpcClientMock.Object);
            var result = contractClient.DeployContract(new byte[1], manifest, keyPair1);

            Assert.IsNotNull(result);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            ContractClient client = new ContractClient(new InstanceContext(new CallbackHandler()));

            //Console.WriteLine("Connected");
            //Console.WriteLine(client.ServiceMethodAdd(22, 33));
            client.Connect("Grisha");
            client.Connect("Kolya");
            client.Connect("Olya");
            client.SendMess("Hello", 1);
            //client.Disconnect(2);
            client.SendMess("Hello", 2);
            client.SendMess("Hello", 3);
            //client.Disconnect(1);
            client.SendMess("Hello", 1);
            //client.Disconnect(3);

            Console.ReadLine();
        }
Ejemplo n.º 15
0
    public async Task GivenBlockChain_WhenSigned_FailedWithWrongSignature()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        BlockChain blockChain = new BlockChainBuilder()
                                .SetPrincipleId(blkHeader.PrincipalId)
                                .Build()
                                .Add(blkHeader, blkHeader.PrincipalId);

        BlockChainModel signedBlockChainModel = await client.Sign(blockChain.ToBlockChainModel());

        signedBlockChainModel.Should().NotBeNull();

        bool isValid = await client.Validate(signedBlockChainModel);


        // Modify signature
        signedBlockChainModel.Blocks[1] = signedBlockChainModel.Blocks[1] with {
            DataBlock = signedBlockChainModel.Blocks[1].DataBlock with {
                JwtSignature = "junk"
            }
        };

        isValid = await client.Validate(signedBlockChainModel);

        isValid.Should().BeFalse();
    }
Ejemplo n.º 16
0
 public void Initialize(ContractClient proxy)
 {
     this.proxy = proxy;
 }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var instanceContext       = new InstanceContext(new ClientCallbackHandler());
            var contractClient        = new ContractClient(instanceContext);
            var binding               = contractClient.Endpoint.Binding as WSDualHttpBinding;
            var clientCallbackAddress = binding.ClientBaseAddress.AbsoluteUri + Guid.NewGuid().ToString();

            Console.WriteLine($"ClientCallbaclAddress: {clientCallbackAddress}");
            binding.ClientBaseAddress = new Uri(clientCallbackAddress);

            var name = string.Empty;
            var done = false;

            try
            {
                contractClient.Open();
                Console.WriteLine(contractClient.State.ToString());
                contractClient.Join("User");
                name = "User";
                Console.WriteLine(contractClient.State.ToString());
                Console.WriteLine("Connected as User");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception while attempting to open connection and join as {name}: ", e.Message);
                Console.WriteLine(e.StackTrace);
                done = true;
            }

            while (!done)
            {
                var joinMsg = string.Empty;
                if (!string.IsNullOrEmpty(name))
                {
                    joinMsg = $"[Joined as {name}]";
                }
                Console.WriteLine();
                Console.WriteLine($"Menu {joinMsg} Connection State: {contractClient.State.ToString()}");
                Console.WriteLine("     Enter 'x' to exit client");
                Console.WriteLine("     Enter 'j:<name>' to join");
                Console.WriteLine("     Enter 'l' to leave");
                Console.WriteLine("     Enter 'p:<message>' to ping the server with message");
                Console.WriteLine();
                Console.Write("Enter a command: ");
                var cmd = Console.ReadLine();
                cmd = cmd.ToLower().Trim();
                var splitCmd = cmd.Split(':');
                if (splitCmd[0] == "x")
                {
                    done = true;
                }
                else if (splitCmd[0] == "l")
                {
                    try
                    {
                        Console.WriteLine(contractClient.State.ToString());
                        contractClient.Leave();
                        name = null;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception while attempting to leave: ", e.Message);
                        Console.WriteLine(e.StackTrace);
                    }
                }
                else if (splitCmd[0] == "j")
                {
                    var newname = (splitCmd.Length < 2 || string.IsNullOrEmpty(splitCmd[1])) ? null : splitCmd[1];
                    if (!string.IsNullOrEmpty(newname))
                    {
                        try
                        {
                            Console.WriteLine(contractClient.State.ToString());
                            contractClient.Join(newname);
                            name = newname;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Exception while attempting to join as {newname}: ", e.Message);
                            Console.WriteLine(e.StackTrace);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Name should not be left empty on a join request");
                    }
                }
                else if (splitCmd[0] == "p")
                {
                    if (!string.IsNullOrEmpty(name))
                    {
                        var msg = (splitCmd.Length < 2 || string.IsNullOrEmpty(splitCmd[1])) ? null : splitCmd[1];
                        if (!string.IsNullOrEmpty(msg))
                        {
                            try
                            {
                                Console.WriteLine(contractClient.State.ToString());
                                contractClient.Ping(msg);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Exception attempting to ping with msg: {msg}: ", e.Message);
                                Console.WriteLine(e.StackTrace);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Message cannot be left empty on a ping request");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Must join the server before sending a ping request");
                    }
                }
                else
                {
                    Console.WriteLine("Unrecognized command");
                }
            }
            try
            {
                Console.WriteLine(contractClient.State.ToString());
                contractClient.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception attempt to close out the client: ", e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }