public static bool OnGetBlockById(JToken id, string method, JArray parameters, out JToken result) { result = new JObject(); if (parameters == null || parameters.Count != 1) { result = RpcMessage.CreateErrorResult(id, RpcMessage.INVALID_PARAMS, "Invalid parameters"); return(false); } try { SHA256Hash hash = SHA256Hash.Wrap(parameters[0].ToString().HexToBytes()); BlockCapsule block = Manager.Instance.DBManager.GetBlockById(hash); BlockExtention block_extention = RpcApiService.CreateBlockExtention(block); result = JToken.FromObject(block_extention.ToByteArray()); } catch (System.Exception e) { result = RpcMessage.CreateErrorResult(id, RpcMessage.UNKNOWN_ERROR, e.Message); return(false); } return(true); }
public void PreExecute(BlockCapsule block) { this.block = block; this.execute = true; this.allow_generate_root = Manager.Instance.DBManager.DynamicProperties.AllowAccountStateRoot(); if (!Execute()) { return; } byte[] root_hash = null; try { BlockCapsule parent_block = Manager.Instance.DBManager.GetBlockById(this.block.ParentId); root_hash = parent_block.Instance.BlockHeader.RawData.AccountStateRoot.ToByteArray(); } catch (System.Exception e) { Logger.Error(e.Message); } if (root_hash.SequenceEqual(new byte[0])) { root_hash = Hash.EMPTY_TRIE_HASH; } trie = new Trie(Manager.Instance.DBManager.AccountStateTrie, root_hash); }
public static bool OnGetBlock(JToken id, string method, JArray parameters, out JToken result) { result = new JObject(); if (parameters == null || parameters.Count != 1) { result = RpcMessage.CreateErrorResult(id, RpcMessage.INVALID_PARAMS, "Invalid parameters"); return(false); } try { BlockCapsule block = Manager.Instance.DBManager.GetBlockByNum(parameters[0].Value <long>()); result = JToken.FromObject(RpcApiService.CreateBlockExtention(block).ToByteArray()); } catch (InvalidCastException e) { result = RpcMessage.CreateErrorResult(id, RpcMessage.INVALID_PARAMS, e.Message); return(false); } catch (System.Exception e) { result = RpcMessage.CreateErrorResult(id, RpcMessage.UNKNOWN_ERROR, e.Message); return(false); } return(true); }
private RunTime(Transaction tx, BlockCapsule block, Deposit deposit, IProgramInvokeFactory invoke_factory) { this.transaction = tx; this.deposit = deposit; this.invoke_factory = invoke_factory; this.executor_type = ExecutorType.ET_PRE_TYPE; this.block = block; this.energy_processor = new EnergyProcessor(deposit.DBManager); ContractType contract_type = tx.RawData.Contract[0].Type; switch (contract_type) { case ContractType.TriggerSmartContract: { this.transaction_type = TransactionType.TX_CONTRACT_CALL_TYPE; } break; case ContractType.CreateSmartContract: { this.transaction_type = TransactionType.TX_CONTRACT_CREATION_TYPE; } break; default: { this.transaction_type = TransactionType.TX_PRECOMPILED_TYPE; } break; } }
public bool ValidBlock(BlockCapsule block) { bool result = false; try { if (!block.ValidateSignature(Manager.Instance.DBManager)) { return(result); } foreach (WitnessCapsule witness in Manager.Instance.DBManager.Witness.AllWitnesses) { if (witness.Address.Equals(block.WitnessAddress)) { result = true; } } } catch (ValidateSignatureException e) { throw new P2pException(P2pException.ErrorType.BAD_BLOCK, e.Message, e); } return(result); }
public BlockCapsule GetBlock(byte[] hash) { BlockCapsule block = null; Key key = Key.Create(hash); if (this.block_cache.ContainsKey(key)) { block = this.block_cache[key].ToCapsule <BlockCapsule, Protocol.Block>(); } else { try { if (this.parent != null) { block = this.parent.GetBlock(hash); } else { block = this.db_manager.Block.Get(hash); } } catch { block = null; } if (block != null) { this.block_cache.Add(key, Value.Create(block.Data)); } } return(null); }
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)); }
public void Init(BlockCapsule block, bool event_plugin_loaded) { this.tx_start_time = Helper.CurrentTimeMillis(); Deposit deposit = Deposit.CreateRoot(this.db_manager); this.runtime = new RunTime(this, block, deposit, new ProgramInvokeFactory()); this.runtime.SetEnableEventListener(event_plugin_loaded); }
private void BroadcastBlock(BlockCapsule block) { try { this.net_service.Broadcast(new BlockMessage(block.Data)); } catch (System.Exception) { throw new System.Exception("BroadcastBlock error"); } }
public BlockCapsule GetBlockById(SHA256Hash hash) { BlockCapsule block = this.khaos_database.GetBlock(hash); if (block == null) { block = this.block_store.Get(hash.Hash); } return(block); }
public BlockMessage(byte[] raw_data) : base(raw_data) { this.type = (byte)MessageTypes.MsgType.BLOCK; this.block = new BlockCapsule(GetCodedInputStream(data)); if (Message.IsFilter) { Message.CompareBytes(data, block.Data); TransactionCapsule.ValidContractProto(new List <Protocol.Transaction>(block.Instance.Transactions)); } }
public List <AssetIssueCapsule> GetAllAssetIssues() { List <AssetIssueCapsule> result = new List <AssetIssueCapsule>(); long block_num = 1; long latest_header_num = this.db_manager.DynamicProperties.GetLatestBlockHeaderNumber(); while (block_num <= latest_header_num) { if (block_num % 100000 == 0) { Logger.Info( string.Format("The number of block that have processed:{0}", block_num)); } try { BlockCapsule block = this.db_manager.GetBlockByNum(block_num); foreach (TransactionCapsule tx in block.Transactions) { if (tx.Instance.RawData.Contract[0].Type == Protocol.Transaction.Types.Contract.Types.ContractType.AssetIssueContract) { AssetIssueContract contract = tx.Instance.RawData.Contract[0].Parameter.Unpack <AssetIssueContract>(); AssetIssueCapsule asset_issue = new AssetIssueCapsule(contract); result.Add(this.db_manager.AssetIssue.Get(asset_issue.CreateDatabaseKey())); } } } catch (System.Exception e) { throw new System.Exception("Block not exists,num:" + block_num, e); } block_num++; } Logger.Info( string.Format("Total block:{0}", block_num)); if (this.db_manager.AssetIssue.AllAssetIssues.Count != result.Count) { throw new System.Exception("Asset num is wrong!"); } return(result); }
public static BlockExtention CreateBlockExtention(BlockCapsule block) { if (block == null) { return(null); } BlockExtention block_extention = new BlockExtention(); block_extention.BlockHeader = block.Instance.BlockHeader; block_extention.Blockid = ByteString.CopyFrom(block.Id.Hash); foreach (Transaction transaction in block.Instance.Transactions) { block_extention.Transactions.Add(CreateTransactionExtention(new TransactionCapsule(transaction))); } return(block_extention); }
public RunTime(TransactionTrace trace, BlockCapsule block, Deposit deposit, IProgramInvokeFactory invoke_factory) { this.trace = trace; this.transaction = trace.Transaction.Instance; if (block != null) { this.block = block; this.executor_type = ExecutorType.ET_NORMAL_TYPE; } else { this.block = new BlockCapsule(new Block()); this.executor_type = ExecutorType.ET_PRE_TYPE; } this.deposit = deposit; this.invoke_factory = invoke_factory; this.energy_processor = new EnergyProcessor(deposit.DBManager); ContractType contract_type = this.transaction.RawData.Contract[0].Type; switch (contract_type) { case ContractType.TriggerSmartContract: { this.transaction_type = TransactionType.TX_CONTRACT_CALL_TYPE; } break; case ContractType.CreateSmartContract: { this.transaction_type = TransactionType.TX_CONTRACT_CREATION_TYPE; } break; default: { this.transaction_type = TransactionType.TX_PRECOMPILED_TYPE; } break; } }
public byte[] GetAccountStateRootHash(long latest_number) { byte[] root_hash = null; try { BlockCapsule block = Manager.Instance.DBManager.GetBlockByNum(latest_number); ByteString value = block.Instance.BlockHeader.RawData.AccountStateRoot; root_hash = value == null ? null : value.ToByteArray(); if (root_hash.SequenceEqual(new byte[0])) { root_hash = Hash.EMPTY_TRIE_HASH; } } catch (System.Exception e) { Logger.Error(string.Format("Get the {0} block error, {1}", latest_number, e.Message)); } return(root_hash); }
public void CheckDupWitness(BlockCapsule block) { if (block.IsGenerateMyself) { return; } if (need_sync_check) { return; } if (Helper.CurrentTimeMillis() - block.Timestamp > Parameter.ChainParameters.BLOCK_PRODUCED_INTERVAL) { return; } if (!this.privatekeys.ContainsKey(block.WitnessAddress)) { return; } if (this.backup_manager.Status != BackupManager.BackupStatus.MASTER) { return; } if (this.block_count == 0) { Interlocked.Exchange(ref this.block_count, new Random().Next(10)); } else { Interlocked.Exchange(ref this.block_count, 10); } Interlocked.Exchange(ref this.block_time, Helper.CurrentTimeMillis()); Logger.Warning("Duplicate block produced : " + block.ToString()); }
public void ProcessBlock(BlockCapsule block) { lock (locker_block) { try { if (!this.fresh_block_id.Contains(block.Id)) { Manager.Instance.DBManager.PushBlock(block); this.fresh_block_id.Enqueue(block.Id); Logger.Info("Success process block " + block.Id.GetString()); } } catch (System.Exception e) { if (e is ValidateSignatureException || e is ContractValidateException || e is ContractExeException || e is UnLinkedBlockException || e is ValidateScheduleException || e is AccountResourceInsufficientException || e is TaposException || e is TooBigTransactionException || e is TooBigTransactionResultException || e is DupTransactionException || e is TransactionExpirationException || e is BadNumberBlockException || e is BadBlockException || e is NonCommonBlockException || e is ReceiptCheckErrorException || e is VMIllegalException) { throw new P2pException(P2pException.ErrorType.BAD_BLOCK, e.Message, e); } throw e; } } }
public static int GetTransactionCountByBlockNum(long block_num) { int count = 0; try { BlockCapsule block = Manager.Instance.DBManager.GetBlockByNum(block_num); if (block != null) { count = block.Transactions.Count; } else { throw new ItemNotFoundException("Not found block"); } } catch (System.Exception e) { throw e; } return(count); }
public void ValidWitnessProductTwoBlock(BlockCapsule block) { try { BlockCapsule history_block = (BlockCapsule)this.history_block_cache.Get(block.Num.ToString()); if (history_block != null && history_block.WitnessAddress.ToByteArray().SequenceEqual(block.WitnessAddress.ToByteArray()) && !block.Id.Hash.SequenceEqual(history_block.Id.Hash)) { string key = block.WitnessAddress.ToByteArray().ToHexString(); if (!this.cheat_witnesses.TryGetValue(key, out CheatWitnessInfo value)) { CheatWitnessInfo cheat_witness = new CheatWitnessInfo(); this.cheat_witnesses.Add(key, cheat_witness); } value.Clear(); value.Time = Helper.CurrentTimeMillis(); value.LatestBlockNum = block.Num; value.Add(block); value.Add(history_block); value.Increment(); } else { this.history_block_cache.Add(block.Num.ToString(), block, new CacheItemPolicy()); } } catch (System.Exception) { Logger.Error( string.Format("valid witness same time product two block fail! blockNum: {0}, blockHash: {1}", block.Num, block.Id.ToString())); } }
private void ProcessSyncBlock(BlockCapsule block) { System.Exception exception = null; try { Logger.Refactoring( string.Format("Process sync block : {0}", block.Num)); Manager.Instance.NetDelegate.ProcessBlock(block); } catch (System.Exception e) { Logger.Error( string.Format("Process sync block {0} failed.", block.Id.GetString())); exception = e; } foreach (PeerConnection peer in Manager.Instance.NetDelegate.ActivePeers) { if (peer.SyncBlockProcess.Remove(block.Id)) { if (exception == null) { peer.BlockBothHave = block.Id; if (peer.SyncBlockFetch.IsEmpty) { SyncNext(peer); } } else { peer.Disconnect(Protocol.ReasonCode.BadBlock, exception.Message); } } } }
private void ProcessBlock(PeerConnection peer, BlockCapsule block) { BlockId block_id = block.Id; if (!Manager.Instance.NetDelegate.ContainBlock(block.ParentId)) { Logger.Warning( string.Format("Get unlink block {0} from {1}, head is {2}.", block.Id.GetString(), peer.Address.ToString(), Manager.Instance.NetDelegate.HeadBlockId.GetString())); Manager.Instance.SyncService.StartSync(peer); return; } if (Args.Instance.IsFastForward && Manager.Instance.NetDelegate.ValidBlock(block)) { Manager.Instance.AdvanceService.Broadcast(new BlockMessage(block)); } Manager.Instance.NetDelegate.ProcessBlock(block); Manager.Instance.WitnessBlockService.ValidWitnessProductTwoBlock(block); Manager.Instance.NetDelegate.ActivePeers.ForEach(p => { if (p.GetInventoryReceive(new Item(block.Id, InventoryType.Block)) != null) { p.BlockBothHave = block.Id; } }); if (!Args.Instance.IsFastForward) { Manager.Instance.AdvanceService.Broadcast(new BlockMessage(block)); } }
public bool ValidateWitnessSchedule(BlockCapsule block) { return(ValidateWitnessSchedule( block.Instance.BlockHeader.RawData.WitnessAddress, block.Timestamp)); }
public void Init(BlockCapsule block) { Init(block, false); }
public void Add(BlockCapsule block) { this.blocks.Add(block); }
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; } }
public RunTime(Transaction tx, BlockCapsule block, Deposit deposit, IProgramInvokeFactory invoke_factory, bool is_static_call) : this(tx, block, deposit, invoke_factory) { this.is_static_call = is_static_call; }
public KhaosBlock(BlockCapsule block) { this.block = block; this.id = block.Id; this.num = block.Num; }
public BlockMessage(BlockCapsule block) { this.data = block.Data; this.type = (byte)MessageTypes.MsgType.BLOCK; this.block = block; }