Пример #1
0
        public void AddSignature(byte[] privatekey, AccountStore account_store)
        {
            Transaction.Types.Contract contract = this.transaction.RawData.Contract[0];

            byte[] owner         = GetOwner(contract);
            int    permission_id = contract.PermissionId;

            AccountCapsule account = account_store.Get(owner);

            if (account == null)
            {
                throw new PermissionException("Account is not exist.");
            }

            Permission permission = account.GetPermissionById(permission_id);

            if (permission == null)
            {
                throw new PermissionException("Permission is not exist");
            }

            if (permission_id != 0)
            {
                if (permission.Type != Permission.Types.PermissionType.Active)
                {
                    throw new PermissionException("Permission type is error");
                }
                if (Wallet.CheckPermissionOperations(permission, contract))
                {
                    throw new PermissionException("Invalid permission");
                }
            }

            List <ByteString> approves = new List <ByteString>();
            ECKey             ec_key   = ECKey.FromPrivateKey(privatekey);

            byte[] address = Wallet.PublickKeyToAddress(ec_key.PublicKey);

            if (this.transaction.Signature.Count > 0)
            {
                CheckWeight(permission, new List <ByteString>(this.transaction.Signature), this.GetRawHash().Hash, approves);
                if (approves.Contains(ByteString.CopyFrom(address)))
                {
                    throw new PermissionException(Wallet.AddressToBase58(address) + "had signed!");
                }
            }

            long weight = GetWeight(permission, address);

            if (weight == 0)
            {
                throw new PermissionException(
                          privatekey.ToHexString() + " address is " +
                          Wallet.AddressToBase58(address) + "but it is not contained of permission.");
            }

            ECDSASignature signature = ec_key.Sign(this.GetRawHash().Hash);

            this.transaction.Signature.Add(ByteString.CopyFrom(signature.ToByteArray()));
        }
Пример #2
0
 public LogInfoTriggerParser(long block_num, long block_timestamp, byte[] tx_id, byte[] origin_address)
 {
     this.block_num       = block_num;
     this.block_timestamp = block_timestamp;
     this.transaction_id  = tx_id.IsNotNullOrEmpty() ? tx_id.ToHexString() : "";
     this.origin_address  = origin_address.IsNotNullOrEmpty() ? Wallet.AddressToBase58(origin_address) : "";
 }
Пример #3
0
        public void CheckIsConstant()
        {
            if (VMConfig.AllowTvmConstantinople)
            {
                return;
            }

            TriggerSmartContract trigger_contract = ContractCapsule.GetTriggerContractFromTransaction(this.Transaction.Instance);

            if (this.transaction_type == TransactionType.TX_CONTRACT_CALL_TYPE)
            {
                Deposit         deposit  = Deposit.CreateRoot(this.db_manager);
                ContractCapsule contract = deposit.GetContract(trigger_contract.ContractAddress.ToByteArray());
                if (contract == null)
                {
                    Logger.Info(string.Format("contract: {0} is not in contract store",
                                              Wallet.AddressToBase58(trigger_contract.ContractAddress.ToByteArray())));

                    throw new ContractValidateException("contract: "
                                                        + Wallet.AddressToBase58(trigger_contract.ContractAddress.ToByteArray())
                                                        + " is not in contract store");
                }
                ABI abi = contract.Instance.Abi;
                if (Wallet.IsConstant(abi, trigger_contract))
                {
                    throw new VMIllegalException("cannot call constant method");
                }
            }
        }
Пример #4
0
        public void Update(BlockCapsule block)
        {
            List <ByteString> witnesses = this.db_manager.WitnessController.GetActiveWitnesses();
            ByteString        witness   = block.WitnessAddress;
            int slot = witnesses.IndexOf(witness);

            if (slot < 0)
            {
                return;
            }

            int version = block.Instance.BlockHeader.RawData.Version;

            if (version < Parameter.ForkBlockVersionParameters.ENERGY_LIMIT)
            {
                return;
            }

            Downgrade(version, slot);

            byte[] stats = this.db_manager.DynamicProperties.StatsByVersion(version);
            if (Check(stats))
            {
                Upgrade(version, stats.Length);
                return;
            }

            if (stats == null || stats.Length != witnesses.Count)
            {
                stats = new byte[witnesses.Count];
            }

            stats[slot] = VERSION_UPGRADE;
            this.db_manager.DynamicProperties.StatsByVersion(version, stats);
            Logger.Info(
                string.Format(
                    "*******update hard fork:{0}, witness size:{1}, solt:{2}, witness:{3}, version:{4}",

                    string.Join(", ",
                                Enumerable.Zip <ByteString, byte, KeyValuePair <ByteString, byte> >(
                                    witnesses,
                                    stats,
                                    (ByteString key, byte value) =>
            {
                return(new KeyValuePair <ByteString, byte>(key, value));
            })
                                .Select(pair =>
            {
                string address = Wallet.AddressToBase58(pair.Key.ToByteArray());
                address        = address.Substring(address.Length - 4);
                return(new KeyValuePair <string, byte>(address, pair.Value));
            })
                                .ToList()
                                .ToString()),
                    witnesses.Count,
                    slot,
                    Wallet.AddressToBase58(witness.ToByteArray()),
                    version));
        }
Пример #5
0
        public void AddressToBase58()
        {
            byte[] address = Wallet.PublickKeyToAddress(this.publickey);
            address.Length.Should().Be(21);

            string address_str = Wallet.AddressToBase58(address);

            address_str.Equals(this.base85_address).Should().BeTrue();
        }
Пример #6
0
        public static long CheckWeight(Permission permission, List <ByteString> signature, byte[] hash, List <ByteString> approve_list)
        {
            long result = 0;

            if (signature.Count > permission.Keys.Count)
            {
                throw new PermissionException(
                          "Signature count is" + signature.Count +
                          "more than key counts of permission" + permission.Keys.Count);
            }

            Dictionary <ByteString, long> signature_weight = new Dictionary <ByteString, long>();

            foreach (ByteString sign in signature)
            {
                if (sign.Length < 65)
                {
                    throw new SignatureFormatException("Signature size is" + sign.Length);
                }

                ECKey ec_key = ECKey.RecoverFromSignature(ECDSASignature.ExtractECDSASignature(sign.ToByteArray()),
                                                          hash,
                                                          false);

                byte[] publickey = ec_key.PublicKey;
                byte[] address   = Wallet.PublickKeyToAddress(ec_key.PublicKey);

                long weight = GetWeight(permission, address);
                if (weight == 0)
                {
                    throw new PermissionException(
                              sign.ToByteArray().ToHexString()
                              + "is signed by"
                              + Wallet.AddressToBase58(address)
                              + "but it is not contained of permission.");
                }

                if (signature_weight.ContainsKey(sign))
                {
                    throw new PermissionException(Wallet.AddressToBase58(address) + " has signed twice");
                }

                signature_weight.Add(sign, weight);
                if (approve_list != null)
                {
                    approve_list.Add(ByteString.CopyFrom(publickey));
                }
                result += weight;
            }

            return(result);
        }
Пример #7
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);
        }
Пример #8
0
        public bool HasMostApprovals(List <ByteString> active_witness)
        {
            List <ByteString> contains = new List <ByteString>(this.proposal.Approvals.Where(witness => active_witness.Contains(witness)));
            long count = contains.Count;

            if (count != this.proposal.Approvals.Count())
            {
                List <ByteString> not_contains = new List <ByteString>(this.proposal.Approvals.Where(witness => !active_witness.Contains(witness)));

                List <string> addresses = not_contains.Select(witness => Wallet.AddressToBase58(witness.ToByteArray())).ToList();
                Logger.Info("Invalid approval list : " + addresses.ToString());
            }

            if (active_witness.Count != Parameter.ChainParameters.MAX_ACTIVE_WITNESS_NUM)
            {
                Logger.Info("Active witness count = " + active_witness.Count());
            }

            return(count >= active_witness.Count * 7 / 10);
        }
Пример #9
0
        public bool ValidateWitnessSchedule(ByteString witness_address, long timestamp)
        {
            if (this.db_manager.DynamicProperties.GetLatestBlockHeaderNumber() == 0)
            {
                return(true);
            }

            long abs_slot      = GetAbsSlotAtTime(timestamp);
            long head_abs_slot = GetAbsSlotAtTime(this.db_manager.DynamicProperties.GetLatestBlockHeaderTimestamp());

            if (abs_slot <= head_abs_slot)
            {
                Logger.Warning("abs_slot is equals with head_abs_slot[" + abs_slot + "]");
                return(false);
            }

            long       slot = GetSlotAtTime(timestamp);
            ByteString scheduled_witness = GetScheduleWitness(slot);

            if (!scheduled_witness.Equals(witness_address))
            {
                Logger.Warning(
                    string.Format(
                        "Witness is out of order, scheduled Witness[{0}],BlockWitnessAddress[{1}], BlockTimeStamp[{2}], Slot[{3}]",
                        Wallet.AddressToBase58(scheduled_witness.ToByteArray()),
                        Wallet.AddressToBase58(witness_address.ToByteArray()),
                        timestamp.ToDateTime().ToLocalTime(),
                        slot));

                return(false);
            }

            Logger.Debug(
                string.Format(
                    "Validate witness schedule successfully, scheduled witness:{0}",
                    Wallet.AddressToBase58(witness_address.ToByteArray())));

            return(true);
        }
Пример #10
0
        public static RpcApiResult ImportWallet(string password, string privatekey)
        {
            if (password.IsNullOrEmpty() || privatekey.IsNullOrEmpty())
            {
                Console.WriteLine("Invalide password and privatekey");
                return(new RpcApiResult(false, RpcMessage.INVALID_PASSWORD, "Invalide password and privatekey"));
            }

            try
            {
                byte[] pk = privatekey.HexToBytes();
                if (pk.Length != 32)
                {
                    return(new RpcApiResult(false, RpcMessage.INVALID_PRIVATEKEY, "Invalid privatekey. Privatekey must be 32 bytes."));
                }

                ECKey  key     = ECKey.FromPrivateKey(pk);
                string address = Wallet.AddressToBase58(Wallet.PublickKeyToAddress(key.PublicKey));

                if (!KeyStoreService.GenerateKeyStore(RpcApi.FILE_PATH,
                                                      password,
                                                      pk,
                                                      address,
                                                      out _))
                {
                    Console.WriteLine();
                    return(new RpcApiResult(false, RpcMessage.INTERNAL_ERROR, "Faild to generate keystore file."));
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }

            return(RpcApiResult.Success);
        }
Пример #11
0
        public ByteString GetScheduleWitness(long slot)
        {
            long current_slot = GetHeadSlot() + slot;

            if (current_slot < 0)
            {
                throw new System.Exception("CurrentSlot should be positive");
            }

            int active_witness_count = GetActiveWitnesses().Count;
            int single_repeat        = Parameter.ChainParameters.SINGLE_REPEAT;

            if (active_witness_count <= 0)
            {
                throw new System.Exception("Active Witnesses is null.");
            }

            int witness_Index = (int)current_slot % (active_witness_count * single_repeat);

            witness_Index /= single_repeat;

            Logger.Debug(
                string.Format("Current Slot : {0}, Witness Index : {1}, CrrentActiveWitness Size : {2}",
                              current_slot,
                              witness_Index,
                              active_witness_count));

            ByteString scheduled_witness = GetActiveWitnesses()?[witness_Index];

            Logger.Info(
                string.Format("Scheduled Witness : {0}, Current Slot : {1}",
                              Wallet.AddressToBase58(scheduled_witness.ToByteArray()),
                              current_slot));

            return(scheduled_witness);
        }
Пример #12
0
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     writer.WriteValue(Wallet.AddressToBase58((byte[])value));
 }
Пример #13
0
        private void Create()
        {
            if (!this.deposit.DBManager.DynamicProperties.SupportVM())
            {
                throw new ContractValidateException("vm work is off, need to be opened by the committee");
            }

            CreateSmartContract contract = ContractCapsule.GetSmartContractFromTransaction(this.transaction);

            if (contract == null)
            {
                throw new ContractValidateException("Cannot get CreateSmartContract from transaction");
            }

            SmartContract new_contract = contract.NewContract;

            if (!contract.OwnerAddress.Equals(new_contract.OriginAddress))
            {
                Logger.Info("OwnerAddress not equals OriginAddress");
                throw new VMIllegalException("OwnerAddress is not equals OriginAddress");
            }

            byte[] contract_name = Encoding.UTF8.GetBytes(new_contract.Name);

            if (contract_name.Length > VMParameter.CONTRACT_NAME_LENGTH)
            {
                throw new ContractValidateException("contractName's length cannot be greater than 32");
            }

            long percent = contract.NewContract.ConsumeUserResourcePercent;

            if (percent < 0 || percent > DefineParameter.ONE_HUNDRED)
            {
                throw new ContractValidateException("percent must be >= 0 and <= 100");
            }

            byte[] contract_address = Wallet.GenerateContractAddress(this.transaction);
            if (this.deposit.GetAccount(contract_address) != null)
            {
                throw new ContractValidateException(
                          "Trying to create a contract with existing contract address: " + Wallet.AddressToBase58(contract_address));
            }

            new_contract.ContractAddress = ByteString.CopyFrom(contract_address);

            long call_value  = new_contract.CallValue;
            long token_value = 0;
            long token_id    = 0;

            if (VMConfig.AllowTvmTransferTrc10)
            {
                token_value = contract.CallTokenValue;
                token_id    = contract.TokenId;
            }

            byte[] caller_address = contract.OwnerAddress.ToByteArray();
            try
            {
                long fee_limit = this.transaction.RawData.FeeLimit;
                if (fee_limit < 0 || fee_limit > VMConfig.MAX_FEE_LIMIT)
                {
                    Logger.Info(string.Format("invalid feeLimit {0}", fee_limit));
                    throw new ContractValidateException(
                              "feeLimit must be >= 0 and <= " + VMConfig.MAX_FEE_LIMIT);
                }

                AccountCapsule creator      = this.deposit.GetAccount(new_contract.OriginAddress.ToByteArray());
                long           energy_limit = 0;
                if (VMConfig.EnergyLimitHardFork)
                {
                    if (call_value < 0)
                    {
                        throw new ContractValidateException("callValue must >= 0");
                    }
                    if (token_value < 0)
                    {
                        throw new ContractValidateException("tokenValue must >= 0");
                    }
                    if (new_contract.OriginEnergyLimit <= 0)
                    {
                        throw new ContractValidateException("The originEnergyLimit must be > 0");
                    }
                    energy_limit = GetAccountEnergyLimitWithFixRatio(creator, fee_limit, call_value);
                }
                else
                {
                    energy_limit = GetAccountEnergyLimitWithFloatRatio(creator, fee_limit, call_value);
                }

                CheckTokenValueAndId(token_value, token_id);

                byte[] ops = new_contract.Bytecode.ToByteArray();
                this.root_internal_transaction = new InternalTransaction(this.transaction, this.transaction_type);

                long max_cpu_time_tx = this.deposit.DBManager.DynamicProperties.GetMaxCpuTimeOfOneTx() * DefineParameter.ONE_THOUSAND;
                long tx_cpu_limit    = (long)(max_cpu_time_tx * GetCpuLimitInUsRatio());
                long vm_start        = Helper.NanoTime() / DefineParameter.ONE_THOUSAND;
                long vm_should_end   = vm_start + tx_cpu_limit;

                IProgramInvoke invoke = this.invoke_factory.CreateProgramInvoke(TransactionType.TX_CONTRACT_CREATION_TYPE,
                                                                                this.executor_type,
                                                                                this.transaction,
                                                                                token_value,
                                                                                token_id,
                                                                                this.block.Instance,
                                                                                this.deposit,
                                                                                vm_start,
                                                                                vm_should_end,
                                                                                energy_limit);

                this.vm      = new Vm();
                this.program = new Program(ops, invoke, this.root_internal_transaction, this.block);
                byte[] tx_id = new TransactionCapsule(this.transaction).Id.Hash;
                this.program.RootTransactionId = tx_id;

                // TODO: EventPluginLoader is not Implementation
                //if (this.enable_listener
                //    && (EventPluginLoader.getInstance().isContractEventTriggerEnable()
                //    || EventPluginLoader.getInstance().isContractLogTriggerEnable())
                //    && IsCheckTransaction)
                //{
                //    logInfoTriggerParser = new LogInfoTriggerParser(this.block.getNum(), this.block.getTimeStamp(), txId, callerAddress);
                //}
            }
            catch (Exception e)
            {
                Logger.Info(e.Message);
                throw new ContractValidateException(e.Message);
            }
            this.program.Result.ContractAddress = contract_address;
            this.deposit.CreateAccount(contract_address, new_contract.Name, AccountType.Contract);
            this.deposit.CreateContract(contract_address, new ContractCapsule(new_contract));
            byte[] code = new_contract.Bytecode.ToByteArray();

            if (!VMConfig.AllowTvmConstantinople)
            {
                deposit.SaveCode(contract_address, ProgramPrecompile.GetCode(code));
            }

            if (call_value > 0)
            {
                MUtil.Transfer(this.deposit, caller_address, contract_address, call_value);
            }
            if (VMConfig.AllowTvmTransferTrc10)
            {
                if (token_value > 0)
                {
                    MUtil.TransferToken(this.deposit, caller_address, contract_address, token_id.ToString(), token_value);
                }
            }
        }
Пример #14
0
        private BlockProductionCondition TryProduceBlock()
        {
            Logger.Info("Try Produce Block");

            long now = Helper.CurrentTimeMillis() + 50;

            if (need_sync_check)
            {
                long next_slot_time = this.controller.GetSlotTime(1);
                if (next_slot_time > now)
                {
                    need_sync_check = false;
                    Thread.Sleep((int)(next_slot_time - now));
                    now = Helper.CurrentTimeMillis();
                }
                else
                {
                    Logger.Debug(
                        string.Format("Not sync, Now : {0}, HeadBlockTime:{1}, HeadBlockNumber : {2}, HeadBlockId:{3}",
                                      now.ToDateTime().ToLocalTime(),
                                      this.db_manager.DynamicProperties.GetLatestBlockHeaderTimestamp().ToDateTime().ToLocalTime(),
                                      this.db_manager.DynamicProperties.GetLatestBlockHeaderNumber(),
                                      this.db_manager.DynamicProperties.GetLatestBlockHeaderHash()));

                    return(BlockProductionCondition.NOT_SYNCED);
                }
            }

            if (this.backup_manager.Status != BackupManager.BackupStatus.MASTER)
            {
                return(BlockProductionCondition.BACKUP_STATUS_IS_NOT_MASTER);
            }

            if (DupWitnessCheck())
            {
                return(BlockProductionCondition.DUP_WITNESS);
            }

            int participation = this.controller.CalculateParticipationRate();

            if (participation < MIN_PARTICIPATION_RATE)
            {
                Logger.Warning(
                    string.Format("Participation[{0}] > MIN_PARTICIPATION_RATE[{1}]",
                                  participation,
                                  MIN_PARTICIPATION_RATE));

                this.controller.DumpParticipationLog();

                return(BlockProductionCondition.LOW_PARTICIPATION);
            }

            if (!this.controller.ActiveWitnessesContain(this.local_witness_states.Keys.ToHashSet()))
            {
                string log_address = "";
                foreach (var addr in this.controller.GetActiveWitnesses().Select(witness => Wallet.AddressToBase58(witness.ToByteArray())))
                {
                    log_address += "\n" + "[" + addr + "]";
                }

                Logger.Info(
                    string.Format("Unelected. Elected Witnesses: {0}", log_address));

                return(BlockProductionCondition.UNELECTED);
            }

            try
            {
                BlockCapsule block = null;

                lock (this.db_manager)
                {
                    long slot = this.controller.GetSlotAtTime(now);
                    Logger.Debug("Slot : " + slot);

                    if (slot == 0)
                    {
                        Logger.Info(
                            string.Format("Not time yet, Now : {0}, HeadBlockTime : {1}, HeadBlockNumber : {2}, HeadBlockId:{3}",
                                          now.ToDateTime().ToLocalTime(),
                                          this.db_manager.DynamicProperties.GetLatestBlockHeaderTimestamp().ToDateTime().ToLocalTime(),
                                          this.db_manager.DynamicProperties.GetLatestBlockHeaderNumber(),
                                          this.db_manager.DynamicProperties.GetLatestBlockHeaderHash()));

                        return(BlockProductionCondition.NOT_TIME_YET);
                    }

                    if (now < this.db_manager.DynamicProperties.GetLatestBlockHeaderTimestamp())
                    {
                        Logger.Warning(
                            string.Format("timestamp : {0} less than or equal to the previous block timestamp : {1}",
                                          now.ToDateTime().ToLocalTime(),
                                          this.db_manager.DynamicProperties.GetLatestBlockHeaderTimestamp().ToDateTime().ToLocalTime()));

                        return(BlockProductionCondition.EXCEPTION_PRODUCING_BLOCK);
                    }

                    ByteString scheduled_witness = this.controller.GetScheduleWitness(slot);
                    if (!this.local_witness_states.ContainsKey(scheduled_witness))
                    {
                        Logger.Info(
                            string.Format("It's not my turn, ScheduledWitness[{0}], Slot[{1}], AbsSlot[{2}],",
                                          Wallet.AddressToBase58(scheduled_witness.ToByteArray()),
                                          slot,
                                          controller.GetAbsSlotAtTime(now)));

                        return(BlockProductionCondition.NOT_MY_TURN);
                    }

                    long scheduled_time = controller.GetSlotTime(slot);
                    if (scheduled_time - now > PRODUCE_TIME_OUT)
                    {
                        return(BlockProductionCondition.LAG);
                    }

                    if (!this.privatekeys.ContainsKey(scheduled_witness))
                    {
                        return(BlockProductionCondition.NO_PRIVATE_KEY);
                    }

                    this.controller.IsGeneratingBlock = true;
                    block = GenerateBlock(scheduled_time, scheduled_witness, this.db_manager.LastHeadBlockIsMaintenance());

                    if (block == null)
                    {
                        Logger.Warning("Exception when generate block");
                        return(BlockProductionCondition.EXCEPTION_PRODUCING_BLOCK);
                    }

                    int block_produce_timeout = Args.Instance.Node.BlockProducedTimeout;

                    long timeout = Math.Min(Parameter.ChainParameters.BLOCK_PRODUCED_INTERVAL * block_produce_timeout / 100 + 500,
                                            Parameter.ChainParameters.BLOCK_PRODUCED_INTERVAL);

                    if (DateTime.Now.Millisecond - now > timeout)
                    {
                        Logger.Warning(
                            string.Format("Task timeout ( > {0}ms),startTime:{1}, endTime:{2}",
                                          timeout,
                                          now.ToDateTime().ToLocalTime(),
                                          DateTime.Now));

                        this.db_manager.EraseBlock();
                        return(BlockProductionCondition.TIME_OUT);
                    }
                }

                Logger.Info(
                    string.Format(
                        "Produce block successfully, BlockNumber:{0}, AbsSlot[{1}], BlockId:{2}, TransactionSize:{3}, BlockTime:{4}, ParentBlockId:{5}",
                        block.Num,
                        controller.GetAbsSlotAtTime(now),
                        block.Id,
                        block.Transactions.Count,
                        block.Timestamp.ToDateTime().ToLocalTime(),
                        block.ParentId));

                Logger.Refactoring(
                    string.Format("Produce block successfully, block number {0}", block.Num));

                BroadcastBlock(block);

                return(BlockProductionCondition.PRODUCED);
            }
            catch (System.Exception e)
            {
                Logger.Error(e.Message);
                return(BlockProductionCondition.EXCEPTION_PRODUCING_BLOCK);
            }
            finally
            {
                this.controller.IsGeneratingBlock = false;
            }
        }
Пример #15
0
        public List <ContractTrigger> ParseLogInfos(List <LogInfo> log_infos, IDeposit deposit)
        {
            List <ContractTrigger> triggers = new List <ContractTrigger>();

            if (log_infos == null || log_infos.Count <= 0)
            {
                return(triggers);
            }

            Dictionary <string, string> signs = new Dictionary <string, string>();
            Dictionary <string, string> abis  = new Dictionary <string, string>();

            foreach (LogInfo info in log_infos)
            {
                byte[] contract_address     = Wallet.ToAddAddressPrefix(info.Address);
                string contract_address_str = contract_address.IsNotNullOrEmpty() ?
                                              Wallet.AddressToBase58(contract_address) : "";


                if (signs.TryGetValue(contract_address_str, out _) == false)
                {
                    continue;
                }

                ContractCapsule contract = deposit.GetContract(contract_address);
                if (contract == null)
                {
                    signs.Add(contract_address_str, origin_address);
                    abis.Add(contract_address_str, "");
                    continue;
                }

                ABI    abi             = contract.Instance.Abi;
                string creator_address = Wallet.AddressToBase58(Wallet.ToAddAddressPrefix(contract.Instance.OriginAddress.ToByteArray()));
                signs.Add(contract_address_str, creator_address);

                if (abi != null && abi.Entrys.Count > 0)
                {
                    abis.Add(contract_address_str, JsonFormat.PrintToString(abi, false));
                }
                else
                {
                    abis.Add(contract_address_str, "");
                }
            }

            int index = 1;

            foreach (LogInfo info in log_infos)
            {
                byte[] contract_address     = Wallet.ToAddAddressPrefix(info.Address);
                string contract_address_str = contract_address.IsNotNullOrEmpty() ? Wallet.AddressToBase58(contract_address) : "";

                string          abi_value       = abis[contract_address_str];
                ContractTrigger trigger         = new ContractTrigger();
                string          creator_address = signs[contract_address_str];

                trigger.UniqueId        = this.transaction_id + "_" + index;
                trigger.TransactionId   = this.transaction_id;
                trigger.ContractAddress = contract_address_str;
                trigger.OriginAddress   = this.origin_address;
                trigger.CallerAddress   = "";
                trigger.CreatorAddress  = creator_address.IsNotNullOrEmpty() ? creator_address : "";
                trigger.BlockNumber     = this.block_num;
                trigger.Timestamp       = this.block_timestamp;
                trigger.LogInfo         = info;
                trigger.AbiString       = abi_value;

                triggers.Add(trigger);
                index++;
            }

            return(triggers);
        }
Пример #16
0
        public void InitializeWitness()
        {
            var  it    = this.db_manager.Block.GetEnumerator();
            bool reult = it.MoveNext();

            List <ByteString> witness_address = new List <ByteString>();

            this.db_manager.Witness.AllWitnesses.ForEach(witness =>
            {
                if (witness.IsJobs)
                {
                    witness_address.Add(witness.Address);
                }
            });

            SortWitness(ref witness_address);
            SetActiveWitnesses(witness_address);
            witness_address.ForEach(address => Logger.Info("InitializeWitness shuffled addresses : " + Wallet.AddressToBase58(address.ToByteArray())));
            SetCurrentShuffledWitnesses(witness_address);
        }
Пример #17
0
        public void UpdateWitness()
        {
            TryRemovePowerOfGr();
            Dictionary <ByteString, long> count_witness = GetVoteCount(this.db_manager.Votes);

            if (count_witness.IsNullOrEmpty())
            {
                Logger.Info("No vote, no change to witness.");
            }
            else
            {
                List <ByteString> active_witness  = GetActiveWitnesses();
                List <ByteString> witness_address = new List <ByteString>();
                this.db_manager.Witness.AllWitnesses.ForEach(witness =>
                {
                    witness_address.Add(witness.Address);
                });

                foreach (KeyValuePair <ByteString, long> pair in count_witness)
                {
                    WitnessCapsule witness = this.db_manager.Witness.Get(pair.Key.ToByteArray());
                    if (witness == null)
                    {
                        Logger.Warning(
                            string.Format("WitnessCapsule is null address is {0}", Wallet.AddressToBase58(pair.Key.ToByteArray())));

                        return;
                    }

                    AccountCapsule account = this.db_manager.Account.Get(pair.Key.ToByteArray());
                    if (account == null)
                    {
                        Logger.Warning("Witness account[" + Wallet.AddressToBase58(pair.Key.ToByteArray()) + "] not exists");
                    }
                    else
                    {
                        witness.VoteCount += pair.Value;
                        this.db_manager.Witness.Put(witness.CreateDatabaseKey(), witness);
                        Logger.Info(
                            string.Format(
                                "Address is {0}  ,count vote is {1}",
                                Wallet.AddressToBase58(witness.Address.ToByteArray()),
                                witness.VoteCount));
                    }
                }

                SortWitness(ref witness_address);
                if (witness_address.Count > Parameter.ChainParameters.MAX_ACTIVE_WITNESS_NUM)
                {
                    SetActiveWitnesses(witness_address.GetRange(0, Parameter.ChainParameters.MAX_ACTIVE_WITNESS_NUM));
                }
                else
                {
                    SetActiveWitnesses(witness_address);
                }

                if (witness_address.Count > Parameter.ChainParameters.WITNESS_STANDBY_LENGTH)
                {
                    PayStandbyWitness(witness_address.GetRange(0, Parameter.ChainParameters.WITNESS_STANDBY_LENGTH));
                }
                else
                {
                    PayStandbyWitness(witness_address);
                }

                List <ByteString> new_active_witness = GetActiveWitnesses();
                if (WitnessSetChanged(active_witness, new_active_witness))
                {
                    active_witness.ForEach(address =>
                    {
                        WitnessCapsule witness = GetWitnessesByAddress(address);
                        witness.IsJobs         = false;
                        this.db_manager.Witness.Put(witness.CreateDatabaseKey(), witness);
                    });

                    new_active_witness.ForEach(address =>
                    {
                        WitnessCapsule witness = GetWitnessesByAddress(address);
                        witness.IsJobs         = true;
                        this.db_manager.Witness.Put(witness.CreateDatabaseKey(), witness);
                    });
                }

                Logger.Info(
                    string.Format("Update Witness, Before:{0},\nAfter:{1}  ",
                                  string.Join(", ", active_witness.Select(x => Wallet.AddressToBase58(x.ToByteArray())).ToList()),
                                  string.Join(", ", new_active_witness.Select(x => Wallet.AddressToBase58(x.ToByteArray())).ToList()))
                    );
            }
        }
Пример #18
0
 public override string ToString()
 {
     return("Address" + Wallet.AddressToBase58(this.account?.Address.ToByteArray()) + "; " + this.account?.ToString());
 }