Пример #1
0
        /// <summary>
        /// Create witenss
        /// </summary>
        /// <param name="parameters"></param>
        /// /// Parameter Index
        /// [0] : Witness url
        /// <returns></returns>
        public static bool CreateWitness(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <url>\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length != 1)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                byte[] owner_address = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                byte[] url           = Encoding.UTF8.GetBytes(parameters[0]);

                RpcApiResult result = RpcApi.CreateWitnessContract(owner_address,
                                                                   url,
                                                                   out WitnessCreateContract contract);

                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.WitnessCreateContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #2
0
        /// <summary>
        /// Transfer asset
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// </param>
        /// <returns></returns>
        public static bool UnfreezeAsset(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <to address> <asset name> <amount>\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters != null)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                byte[] owner_address = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);

                RpcApiResult result = RpcApi.CreateUnfreezeAssetContract(owner_address,
                                                                         out UnfreezeAssetContract contract);

                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.UnfreezeAssetContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #3
0
        public static Permission JsonToPermission(JObject json)
        {
            Permission permisstion = new Permission();

            if (json.ContainsKey("type"))
            {
                permisstion.Type = (Permission.Types.PermissionType)json["type"].ToObject <int>();
            }

            if (json.ContainsKey("permission_name"))
            {
                permisstion.PermissionName = json["permission_name"].ToString();
            }

            if (json.ContainsKey("threshold"))
            {
                permisstion.Threshold = json["threshold"].ToObject <long>();
            }

            if (json.ContainsKey("parent_id"))
            {
                permisstion.ParentId = json["parent_id"].ToObject <int>();
            }

            if (json.ContainsKey("operations"))
            {
                permisstion.Operations = ByteString.CopyFrom(json["operations"].ToString().HexToBytes());
            }

            if (json.ContainsKey("keys"))
            {
                List <Key> keys = new List <Key>();

                foreach (JToken token in json["keys"] as JArray)
                {
                    Key key = new Key();
                    key.Address = ByteString.CopyFrom(Wallet.Base58ToAddress(token["address"].ToString()));
                    key.Weight  = token["weight"].ToObject <long>();
                    keys.Add(key);
                }

                permisstion.Keys.AddRange(keys);
            }

            return(permisstion);
        }
Пример #4
0
        public static BlockCapsule GenerateGenesisBlock()
        {
            List <Transaction> transactions = Args.Instance.GenesisBlock.Assets.Select(asset =>
            {
                return(TransactionCapsule.GenerateGenesisTransaction(Wallet.Base58ToAddress(asset.Address), asset.Balance));
            }).ToList();

            BlockCapsule result = new BlockCapsule((int)Args.Instance.GenesisBlock.Timestamp,
                                                   ByteString.CopyFrom(Args.Instance.GenesisBlock.ParentHash),
                                                   Args.Instance.GenesisBlock.Number,
                                                   transactions);

            result.SetMerkleTree();
            result.SetWitness("A new system must allow existing systems to be linked together without "
                              + "requiring any central control or coordination");
            result.IsGenerateMyself = true;

            return(result);
        }
Пример #5
0
        /// <summary>
        /// Get transaction information by id
        /// </summary>
        /// <param name="parameters"></param>
        /// /// Parameter Index
        /// [0] : Transaction id
        /// <returns></returns>
        public static bool GetTransactionsToThis(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <transaction id>\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length != 3)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            try
            {
                byte[] address = Wallet.Base58ToAddress(parameters[0]);
                int    offset  = int.Parse(parameters[1]);
                int    limit   = int.Parse(parameters[2]);

                RpcApiResult result = RpcApi.GetTransactionsToThis(address, offset, limit, out TransactionListExtention transactions);
                if (result.Result)
                {
                    if (transactions != null)
                    {
                        Console.WriteLine(PrintUtil.PrintTransactionExtentionList(new List <TransactionExtention>(transactions.Transaction)));
                    }
                    else
                    {
                        Console.WriteLine("No transaction from " + Wallet.AddressToBase58(address));
                    }
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #6
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(Wallet.Base58ToAddress(reader.Value.ToString()));
 }
Пример #7
0
        /// <summary>
        /// Freeze balance
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// [0] : Amount
        /// [1] : Duration time (day)
        /// [2] : Energy / Bandwidth        (default 0 : enerygy)
        /// [3] : Address                   (optional)
        /// </param>
        /// <returns></returns>
        public static bool FreezeBalance(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <amount> <duration> || [<energy/bandwidth>] || [<address>]\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length < 2 || parameters.Length > 4)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                byte[] owner_address = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                byte[] address       = null;
                long   amount        = long.Parse(parameters[0]);
                long   duration      = long.Parse(parameters[1]);
                int    resource_code = 0;

                if (parameters.Length == 3)
                {
                    try
                    {
                        resource_code = int.Parse(parameters[2]);
                    }
                    catch
                    {
                        address = Wallet.Base58ToAddress(parameters[3]);
                    }
                }
                else if (parameters.Length == 4)
                {
                    resource_code = int.Parse(parameters[2]);
                    address       = Wallet.Base58ToAddress(parameters[3]);
                }

                RpcApiResult result = RpcApi.CreateFreezeBalanceContract(owner_address,
                                                                         address,
                                                                         amount,
                                                                         duration,
                                                                         resource_code,
                                                                         out FreezeBalanceContract contract);


                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.FreezeBalanceContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #8
0
        /// <summary>
        /// Send balance
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// [0] : To address
        /// [1] : Balance amount
        /// </param>
        /// <returns></returns>
        public static bool SendCoin(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <to address> <amount>\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length != 2)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                byte[] owner_address = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                byte[] to_address    = Wallet.Base58ToAddress(parameters[0]);
                long   amount        = long.Parse(parameters[1]);

                RpcApiResult result = RpcApi.CreateTransaferContract(owner_address,
                                                                     to_address,
                                                                     amount,
                                                                     out TransferContract contract);

                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.TransferContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                if (result.Result)
                {
                    Console.WriteLine(
                        string.Format("Send {0} drop to {1} + successful. ", long.Parse(parameters[1]), parameters[0]));
                }
                else
                {
                    Console.WriteLine(
                        string.Format("Send {0} drop to {1} + failed. ", long.Parse(parameters[1]), parameters[0]));
                }

                OutputResultMessage(RpcCommand.Transaction.SendCoin, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #9
0
        /// <summary>
        /// UnFreeze balance
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// [0] : Energy / Bandwidth        (default 0 : enerygy)
        /// [1] : Address                   (optional)
        /// </param>
        /// <returns></returns>
        public static bool UnFreezeBalance(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] <address>\n", command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length < 1 || parameters.Length > 2)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            try
            {
                byte[] owner_address = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                byte[] address       = null;
                int    resource_code = 0;

                if (parameters.Length == 1)
                {
                    try
                    {
                        resource_code = int.Parse(parameters[0]);
                    }
                    catch (System.Exception)
                    {
                        address = Wallet.Base58ToAddress(parameters[0]);
                    }
                }
                else if (parameters.Length == 2)
                {
                    resource_code = int.Parse(parameters[0]);
                    address       = Wallet.Base58ToAddress(parameters[1]);
                }


                RpcApiResult result = RpcApi.CreateUnfreezeBalanceContract(owner_address,
                                                                           address,
                                                                           resource_code,
                                                                           out UnfreezeBalanceContract contract);


                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.UnfreezeBalanceContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Пример #10
0
        public bool SetParam(string[] args, string config_path)
        {
            CommanderParser <Args> parser = new CommanderParser <Args>();

            try
            {
                instance = parser.Add(args).Parse();
            }
            catch (System.Exception e)
            {
                Logger.Error(e.Message);
                return(false);
            }

            if (instance.version)
            {
                Console.WriteLine(Version);
                return(false);
            }

            string config_filename = instance.config_file.IsNotNullOrEmpty() ? instance.config_file : config_path;

            if (!Config.Instance.Initialize(config_filename))
            {
                Logger.Error(
                    string.Format("Failed to initialize config. please check config : {0} file",
                                  config_path));

                return(false);
            }

            #region Wallet prefix
            if (Config.Instance.Net.Type.Equals("mainnet"))
            {
                // TODO : Wallet address prefix mainnet
            }
            else
            {
                // TODO : Wallet address prefix testnet
            }
            #endregion

            #region  Local witness
            if (instance.privatekey.Length > 0)
            {
                instance.LocalWitness = new LocalWitness(instance.privatekey.HexToBytes());
                if (!string.IsNullOrEmpty(instance.witness_address))
                {
                    byte[] address = Wallet.Base58ToAddress(instance.witness_address);
                    if (address.IsNotNullOrEmpty())
                    {
                        instance.LocalWitness.SetWitnessAccountAddress(address);
                        Logger.Debug("local witness account address from command.");
                    }
                    else
                    {
                        instance.witness_address = "";
                        Logger.Warning("Local witness account address is incorrect.");
                    }
                }
                instance.LocalWitness.InitWitnessAccountAddress();
            }
            else if (Config.Instance.LocalWitness != null &&
                     Config.Instance.LocalWitness.LocalWitness != null &&
                     Utils.CollectionUtil.IsNotNullOrEmpty(Config.Instance.LocalWitness.LocalWitness))
            {
                instance.LocalWitness = new LocalWitness();

                List <byte[]> witness_list = Config.Instance.LocalWitness.LocalWitness;
                if (witness_list.Count > 1)
                {
                    Logger.Warning("Local witness count must be one. get the first witness");
                    witness_list = witness_list.GetRange(0, 1);
                }
                instance.LocalWitness.SetPrivateKeys(witness_list);

                if (Config.Instance.LocalWitness.LocalWitnessAccountAddress.IsNotNullOrEmpty())
                {
                    byte[] address = Wallet.Base58ToAddress(Config.Instance.LocalWitness.LocalWitnessAccountAddress);
                    if (address.IsNotNullOrEmpty())
                    {
                        instance.LocalWitness.SetWitnessAccountAddress(address);
                        Logger.Debug("Local witness account address from \'config.conf\' file.");
                    }
                    else
                    {
                        Logger.Warning("Local witness account address is incorrect.");
                    }
                }
                instance.LocalWitness.InitWitnessAccountAddress();
            }
            else if (Config.Instance.LocalWitness != null &&
                     Config.Instance.LocalWitness.LocalWitnessKeyStore != null &&
                     Utils.CollectionUtil.IsNotNullOrEmpty(Config.Instance.LocalWitness.LocalWitnessKeyStore))
            {
                List <byte[]> privatekeys = new List <byte[]>();

                instance.LocalWitness = new LocalWitness();
                if (instance.witness)
                {
                    // TODO : Keystore 로드 CLI와 함께 정리해서 중복제거
                    if (Config.Instance.LocalWitness.LocalWitnessKeyStore.Count > 0)
                    {
                        string file_path = Config.Instance.LocalWitness.LocalWitnessKeyStore[0];

                        JObject json;
                        using (var file = File.OpenText(file_path))
                        {
                            string data = file.ReadToEnd();
                            json = JObject.Parse(data);
                        }

                        string password = CommandLineUtil.ReadPasswordString("Password: "******"Invalid password."
                                      );
                        }

                        KeyStore keystore = new KeyStore();
                        keystore = JsonConvert.DeserializeObject <KeyStore>(json.ToString());

                        if (!KeyStoreService.DecryptKeyStore(password, keystore, out byte[] privatekey))
Пример #11
0
 public void Base58ToAddress()
 {
     Wallet.Base58ToAddress(this.base85_address).SequenceEqual(prefix_address).Should().BeTrue();
 }
Пример #12
0
        /// <summary>
        /// Create asset issue
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// [0] : Name
        /// [1] : Description
        /// [2] : Url
        /// [3] : transaction count
        /// [4] : count
        /// [5] : Precision
        /// [6] : Total supply
        /// [7] : Free net limit
        /// [8] : public free net limit
        /// [9] : Start time
        /// [10] : End time
        /// [11-] : Pair frozen supply
        /// </param>
        /// <returns></returns>
        public static bool CreateAssetIssue(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] " +
                              "<name> <description> <url>" +
                              "<transaction count> <count>" +
                              "<precision>" +
                              "<total supply>" +
                              "<free net limit> <public free net limit>" +
                              "<start time> <end time>" +
                              "<amount 1> <days 1> <amount 2> <days 2> ...\n"
                              , command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length < 11 || parameters.Length % 2 == 0)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                int      i                 = 0;
                byte[]   owner_address     = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                string   name              = parameters[i++];
                string   description       = parameters[i++];
                string   url               = parameters[i++];
                long     total_supply      = long.Parse(parameters[i++]);
                int      tx_num            = int.Parse(parameters[i++]);
                int      num               = int.Parse(parameters[i++]);
                int      precision         = int.Parse(parameters[i++]);
                long     free_limit        = long.Parse(parameters[i++]);
                long     public_free_limit = long.Parse(parameters[i++]);
                DateTime start_time        = DateTime.ParseExact(parameters[i++], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                DateTime end_time          = DateTime.ParseExact(parameters[i++], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

                Dictionary <long, long> frozen_supply = new Dictionary <long, long>();
                for (int j = i; j < parameters.Length; j += 2)
                {
                    frozen_supply.Add(
                        long.Parse(parameters[j + 0]),
                        long.Parse(parameters[j + 1])
                        );
                }

                RpcApiResult result = RpcApi.CreateAssetIssueContract(owner_address,
                                                                      name,
                                                                      description,
                                                                      url,
                                                                      tx_num,
                                                                      num,
                                                                      precision,
                                                                      0,
                                                                      total_supply,
                                                                      free_limit,
                                                                      public_free_limit,
                                                                      start_time.ToTimestamp(),
                                                                      end_time.ToTimestamp(),
                                                                      frozen_supply,
                                                                      out AssetIssueContract contract);

                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.AssetIssueContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }