Ejemplo n.º 1
0
        public void TestToJson()
        {
            JObject json = contract.ToJson();

            json["hash"].AsString().Should().Be("0x820944cfdc70976602d71b0091445eedbc661bc5");
            json["nef"]["script"].AsString().Should().Be("AQ==");
            json["manifest"].AsString().Should().Be(manifest.ToJson().AsString());
        }
Ejemplo n.º 2
0
        public JObject ToJson()
        {
            JObject json = new JObject();

            json["hash"]     = ScriptHash.ToString();
            json["script"]   = Script.ToHexString();
            json["manifest"] = Manifest.ToJson();
            return(json);
        }
Ejemplo n.º 3
0
        public JObject ToJson()
        {
            JObject json = new JObject();

            json["hash"]     = ScriptHash.ToString();
            json["script"]   = Convert.ToBase64String(Script);
            json["manifest"] = Manifest.ToJson();
            return(json);
        }
Ejemplo n.º 4
0
        private byte[] LoadUpdateScript(UInt160 scriptHash, string nefFilePath, string manifestFilePath, out NefFile nef, out ContractManifest manifest)
        {
            if (string.IsNullOrEmpty(manifestFilePath))
            {
                manifestFilePath = Path.ChangeExtension(nefFilePath, ".manifest.json");
            }

            // Read manifest

            var info = new FileInfo(manifestFilePath);

            if (!info.Exists || info.Length >= Transaction.MaxTransactionSize)
            {
                throw new ArgumentException(nameof(manifestFilePath));
            }

            manifest = ContractManifest.Parse(File.ReadAllBytes(manifestFilePath));

            // Read nef

            info = new FileInfo(nefFilePath);
            if (!info.Exists || info.Length >= Transaction.MaxTransactionSize)
            {
                throw new ArgumentException(nameof(nefFilePath));
            }

            using (var stream = new BinaryReader(File.OpenRead(nefFilePath), Utility.StrictUTF8, false))
            {
                nef = stream.ReadSerializable <NefFile>();
            }

            // Basic script checks

            Script script = new Script(nef.Script);

            for (var i = 0; i < script.Length;)
            {
                // Check bad opcodes

                Instruction inst = script.GetInstruction(i);
                if (inst is null || !Enum.IsDefined(typeof(OpCode), inst.OpCode))
                {
                    throw new FormatException($"OpCode not found at {i}-{((byte)inst.OpCode).ToString("x2")}");
                }
                i += inst.Size;
            }

            // Build script

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitDynamicCall(scriptHash, "update", nef.ToArray(), manifest.ToJson().ToString());
                return(sb.ToArray());
            }
        }
Ejemplo n.º 5
0
        public JObject ToJson()
        {
            JObject json = new JObject();

            json["id"]            = Id;
            json["updatecounter"] = UpdateCounter;
            json["hash"]          = Hash.ToString();
            json["script"]        = Convert.ToBase64String(Script);
            json["manifest"]      = Manifest.ToJson();
            return(json);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Converts the contract to a JSON object.
 /// </summary>
 /// <returns>The contract represented by a JSON object.</returns>
 public JObject ToJson()
 {
     return(new JObject
     {
         ["id"] = Id,
         ["updatecounter"] = UpdateCounter,
         ["hash"] = Hash.ToString(),
         ["nef"] = Nef.ToJson(),
         ["manifest"] = Manifest.ToJson()
     });
 }
Ejemplo n.º 7
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.º 8
0
        /// <summary>
        /// Deploy Contract, return signed transaction
        /// </summary>
        /// <param name="contractScript">contract script</param>
        /// <param name="manifest">contract manifest</param>
        /// <param name="key">sender KeyPair</param>
        /// <returns></returns>
        public async Task <Transaction> CreateDeployContractTxAsync(byte[] nefFile, ContractManifest manifest, KeyPair key)
        {
            byte[] script;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitDynamicCall(NativeContract.ContractManagement.Hash, "deploy", nefFile, manifest.ToJson().ToString());
                script = sb.ToArray();
            }
            UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash();

            Signer[] signers = new[] { new Signer {
                                           Scopes = WitnessScope.CalledByEntry, Account = sender
                                       } };

            TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient);
            TransactionManager        manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false);

            return(await manager
                   .AddSignature(key)
                   .SignAsync().ConfigureAwait(false));
        }
Ejemplo n.º 9
0
        public async Task <object> DeployContract(string nefPath, string manifestPath = null, bool sendTx = false)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }
            if (nefPath.IsNull())
            {
                return(Error(ErrorCode.ParameterIsNull, "nefPath is empty."));
            }
            if (manifestPath.IsNull())
            {
                manifestPath = Path.ChangeExtension(nefPath, ".manifest.json");
            }
            // Read nef
            NefFile nefFile = ReadNefFile(nefPath);


            using var snapshot = Blockchain.Singleton.GetSnapshot();
            var oldContract = snapshot.Contracts.TryGet(nefFile.ScriptHash);

            if (oldContract != null)
            {
                return(Error(ErrorCode.ContractAlreadyExist));
            }
            // Read manifest
            ContractManifest manifest = ReadManifestFile(manifestPath);

            // Basic script checks
            await CheckBadOpcode(nefFile.Script);

            // Build script
            using ScriptBuilder sb = new ScriptBuilder();
            sb.EmitSysCall(InteropService.Contract.Create, nefFile.Script, manifest.ToJson().ToString());
            var script = sb.ToArray();

            Transaction tx;

            try
            {
                tx = CurrentWallet.MakeTransaction(script);
            }
            catch (InvalidOperationException)
            {
                return(Error(ErrorCode.EngineFault));
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Insufficient GAS"))
                {
                    return(Error(ErrorCode.GasNotEnough));
                }
                throw;
            }

            var result = new DeployResultModel
            {
                ContractHash = nefFile.ScriptHash,
                GasConsumed  = new BigDecimal(tx.SystemFee, NativeContract.GAS.Decimals)
            };

            if (sendTx)
            {
                var(signSuccess, context) = CurrentWallet.TrySignTx(tx);
                if (!signSuccess)
                {
                    return(Error(ErrorCode.SignFail, context.SafeSerialize()));
                }
                await tx.Broadcast();

                result.TxId = tx.Hash;
            }
            return(result);
        }
Ejemplo n.º 10
0
        public async Task <object> DeployContract(string nefPath, string manifestPath = null, bool sendTx = false, UInt160 sender = null)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }
            if (nefPath.IsNull())
            {
                return(Error(ErrorCode.ParameterIsNull, "nefPath is empty."));
            }
            if (manifestPath.IsNull())
            {
                manifestPath = Path.ChangeExtension(nefPath, ".manifest.json");
            }
            // Read nef
            NefFile nefFile = ReadNefFile(nefPath);
            // Read manifest
            ContractManifest manifest = ReadManifestFile(manifestPath);

            // Basic script checks
            await CheckBadOpcode(nefFile.Script);

            // Build script
            using ScriptBuilder sb = new ScriptBuilder();
            sb.EmitDynamicCall(NativeContract.ContractManagement.Hash, "deploy", nefFile.ToArray(),
                               manifest.ToJson().ToString());
            //sb.EmitAppCall(NativeContract.Management.Hash, "deploy", nefFile.ToArray(), manifest.ToJson().ToString());
            var script = sb.ToArray();

            Transaction tx;

            try
            {
                tx = CurrentWallet.MakeTransaction(Helpers.GetDefaultSnapshot(), script, sender);
            }
            catch (InvalidOperationException ex)
            {
                return(Error(ErrorCode.EngineFault, ex.GetExMessage()));
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Insufficient GAS"))
                {
                    return(Error(ErrorCode.GasNotEnough));
                }
                throw;
            }

            UInt160 hash = SmartContract.Helper.GetContractHash(tx.Sender, nefFile.CheckSum, manifest.Name);

            var oldContract = hash.GetContract();

            if (oldContract != null)
            {
                return(Error(ErrorCode.ContractAlreadyExist));
            }
            var result = new DeployResultModel
            {
                ContractHash = hash,
                GasConsumed  = new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)
            };

            if (sendTx)
            {
                var(signSuccess, context) = CurrentWallet.TrySignTx(tx);
                if (!signSuccess)
                {
                    return(Error(ErrorCode.SignFail, context.SafeSerialize()));
                }
                await tx.Broadcast();

                result.TxId = tx.Hash;
            }
            return(result);
        }
Ejemplo n.º 11
0
        public async Task <object> UpdateContract(UInt160 contractHash, string nefPath, string manifestPath = null, bool sendTx = false, UInt160[] cosigners = null)
        {
            if (CurrentWallet == null)
            {
                return(Error(ErrorCode.WalletNotOpen));
            }
            if (nefPath.IsNull())
            {
                return(Error(ErrorCode.ParameterIsNull, "nefPath is empty."));
            }
            if (manifestPath.IsNull())
            {
                manifestPath = Path.ChangeExtension(nefPath, ".manifest.json");
            }
            // Read nef
            NefFile nefFile = ReadNefFile(nefPath);
            // Read manifest
            ContractManifest manifest = ReadManifestFile(manifestPath);

            // Basic script checks
            await CheckBadOpcode(nefFile.Script);

            // Build script
            using ScriptBuilder sb = new ScriptBuilder();
            sb.EmitDynamicCall(contractHash, "update", nefFile.ToArray(), manifest.ToJson().ToString(), null);
            var script = sb.ToArray();

            var singers = new List <Signer> {
            };

            if (cosigners != null)
            {
                singers.AddRange(cosigners.Select(s => new Signer()
                {
                    Account = s, Scopes = WitnessScope.Global
                }));
            }
            Transaction tx;

            try
            {
                tx = CurrentWallet.MakeTransaction(Helpers.GetDefaultSnapshot(), script, null, singers.ToArray());
            }
            catch (InvalidOperationException ex)
            {
                return(Error(ErrorCode.EngineFault, ex.GetExMessage()));
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Insufficient GAS"))
                {
                    return(Error(ErrorCode.GasNotEnough));
                }
                throw;
            }

            var result = new DeployResultModel
            {
                ContractHash = contractHash,
                GasConsumed  = new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)
            };

            if (sendTx)
            {
                var(signSuccess, context) = CurrentWallet.TrySignTx(tx);
                if (!signSuccess)
                {
                    return(Error(ErrorCode.SignFail, context.SafeSerialize()));
                }
                await tx.Broadcast();

                result.TxId = tx.Hash;
            }
            return(result);
        }