您好,登錄后才能下訂單哦!
這篇文章主要介紹“NEO DBFT共識算法源碼分析”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“NEO DBFT共識算法源碼分析”文章能幫助大家解決問題。
dbft改進自算法pbft算法,pbft算法通過多次網絡請求確認,最終獲得多數共識。其缺點在于隨著隨著節點的增加,網絡開銷呈指數級增長,網絡通信膨脹,難以快速達成一致。neo的解決方案是通過投票選取出一定數量的節點作為記賬人,由此減少網絡消耗又可以兼顧交易速度,這也是dbft中d的由來。
├── Consensus │ ├── ChangeView.cs //viewchange 消息 │ ├── ConsensusContext.cs //共識上下文 │ ├── ConsensusMessage.cs //共識消息 │ ├── ConsensusMessageType.cs //共識消息類型 ChangeView/PrepareRequest/PrepareResponse │ ├── ConsensusService.cs //共識核心代碼 │ ├── ConsensusState.cs //節點共識狀態 │ ├── PrepareRequest.cs //請求消息 │ └── PrepareResponse.cs //簽名返回消息
1:開啟共識的節點分為兩大類,非記賬人和記賬人節點,非記賬人的不參與共識,記賬人參與共識流程
2:選擇議長,Neo議長產生機制是根據當前塊高度和記賬人數量做MOD運算得到,議長實際上按順序當選
3:節點初始化,議長為primary節點,議員為backup節點。
4:滿足出塊條件后議長發送PrepareRequest
5:議員收到請求后,驗證通過簽名發送PrepareResponse
6:記賬節點接收到PrepareResponse后,節點保存對方的簽名信息,檢查如果超過三分之二則發送 block
7:節點接收到block,PersistCompleted事件觸發后整體重新初始化,
public const uint Version = 0; public ConsensusState State; //節點當前共識狀態 public UInt256 PrevHash; public uint BlockIndex; //塊高度 public byte ViewNumber; //試圖狀態 public ECPoint[] Validators; //記賬人 public int MyIndex; //當前記賬人次序 public uint PrimaryIndex; //當前記賬的記賬人 public uint Timestamp; public ulong Nonce; public UInt160 NextConsensus; //共識標識 public UInt256[] TransactionHashes; public Dictionary<UInt256, Transaction> Transactions; public byte[][] Signatures; //記賬人簽名 public byte[] ExpectedView; //記賬人試圖 public KeyPair KeyPair; public int M => Validators.Length - (Validators.Length - 1) / 3; //三分之二數量
ExpectedView 維護視圖狀態中,用于在議長無法正常工作時重新發起新一輪共識。
Signatures 用于維護共識過程中的確認狀態。
[Flags] internal enum ConsensusState : byte { Initial = 0x00, // 0 Primary = 0x01, // 1 Backup = 0x02, // 10 RequestSent = 0x04, // 100 RequestReceived = 0x08, // 1000 SignatureSent = 0x10, // 10000 BlockSent = 0x20, // 100000 ViewChanging = 0x40, //1000000 }
neo的dbft算法的delegate部分主要體現在一個函數上面,每次產生區塊后會重新排序資產,選擇前記賬人數量的節點出來參與下一輪共識。
/// <summary> /// 獲取下一個區塊的記賬人列表 /// </summary> /// <returns>返回一組公鑰,表示下一個區塊的記賬人列表</returns> public ECPoint[] GetValidators() { lock (_validators) { if (_validators.Count == 0) { _validators.AddRange(GetValidators(Enumerable.Empty<Transaction>())); } return _validators.ToArray(); } } public virtual IEnumerable<ECPoint> GetValidators(IEnumerable<Transaction> others) { DataCache<UInt160, AccountState> accounts = GetStates<UInt160, AccountState>(); DataCache<ECPoint, ValidatorState> validators = GetStates<ECPoint, ValidatorState>(); MetaDataCache<ValidatorsCountState> validators_count = GetMetaData<ValidatorsCountState>(); ///更新賬號資產情況 foreach (Transaction tx in others) { foreach (TransactionOutput output in tx.Outputs) { AccountState account = accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash)); if (account.Balances.ContainsKey(output.AssetId)) account.Balances[output.AssetId] += output.Value; else account.Balances[output.AssetId] = output.Value; if (output.AssetId.Equals(GoverningToken.Hash) && account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) validators.GetAndChange(pubkey, () => new ValidatorState(pubkey)).Votes += output.Value; validators_count.GetAndChange().Votes[account.Votes.Length - 1] += output.Value; } } foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash)) { Transaction tx_prev = GetTransaction(group.Key, out int height); foreach (CoinReference input in group) { TransactionOutput out_prev = tx_prev.Outputs[input.PrevIndex]; AccountState account = accounts.GetAndChange(out_prev.ScriptHash); if (out_prev.AssetId.Equals(GoverningToken.Hash)) { if (account.Votes.Length > 0) { foreach (ECPoint pubkey in account.Votes) { ValidatorState validator = validators.GetAndChange(pubkey); validator.Votes -= out_prev.Value; if (!validator.Registered && validator.Votes.Equals(Fixed8.Zero)) validators.Delete(pubkey); } validators_count.GetAndChange().Votes[account.Votes.Length - 1] -= out_prev.Value; } } account.Balances[out_prev.AssetId] -= out_prev.Value; } } switch (tx) { #pragma warning disable CS0612 case EnrollmentTransaction tx_enrollment: validators.GetAndChange(tx_enrollment.PublicKey, () => new ValidatorState(tx_enrollment.PublicKey)).Registered = true; break; #pragma warning restore CS0612 case StateTransaction tx_state: foreach (StateDescriptor descriptor in tx_state.Descriptors) switch (descriptor.Type) { case StateType.Account: ProcessAccountStateDescriptor(descriptor, accounts, validators, validators_count); break; case StateType.Validator: ProcessValidatorStateDescriptor(descriptor, validators); break; } break; } } //排序 int count = (int)validators_count.Get().Votes.Select((p, i) => new { Count = i, Votes = p }).Where(p => p.Votes > Fixed8.Zero).ToArray().WeightedFilter(0.25, 0.75, p => p.Votes.GetData(), (p, w) => new { p.Count, Weight = w }).WeightedAverage(p => p.Count, p => p.Weight); count = Math.Max(count, StandbyValidators.Length); HashSet<ECPoint> sv = new HashSet<ECPoint>(StandbyValidators); ECPoint[] pubkeys = validators.Find().Select(p => p.Value).Where(p => (p.Registered && p.Votes > Fixed8.Zero) || sv.Contains(p.PublicKey)).OrderByDescending(p => p.Votes).ThenBy(p => p.PublicKey).Select(p => p.PublicKey).Take(count).ToArray(); IEnumerable<ECPoint> result; if (pubkeys.Length == count) { result = pubkeys; } else { HashSet<ECPoint> hashSet = new HashSet<ECPoint>(pubkeys); for (int i = 0; i < StandbyValidators.Length && hashSet.Count < count; i++) hashSet.Add(StandbyValidators[i]); result = hashSet; } return result.OrderBy(p => p); }
在初始化共識狀態的時候會設置PrimaryIndex,獲知當前議長。原理就是簡單的MOD運算。 這里有分為兩種情況,如果節點正常則直接塊高度和記賬人數量mod運算即可,如果存在一場情況,則需要根據view_number進行調整。
//file /Consensus/ConsensusService.cs InitializeConsensus方法 if (view_number == 0) context.Reset(wallet); else context.ChangeView(view_number);
//file /Consensus/ConsensusContext.cs public void ChangeView(byte view_number) { int p = ((int)BlockIndex - view_number) % Validators.Length; State &= ConsensusState.SignatureSent; ViewNumber = view_number; PrimaryIndex = p >= 0 ? (uint)p : (uint)(p + Validators.Length);//當前記賬人 if (State == ConsensusState.Initial) { TransactionHashes = null; Signatures = new byte[Validators.Length][]; } ExpectedView[MyIndex] = view_number; _header = null; }
//file /Consensus/ConsensusContext.cs public void Reset(Wallet wallet) { State = ConsensusState.Initial; PrevHash = Blockchain.Default.CurrentBlockHash; BlockIndex = Blockchain.Default.Height + 1; ViewNumber = 0; Validators = Blockchain.Default.GetValidators(); MyIndex = -1; PrimaryIndex = BlockIndex % (uint)Validators.Length; //當前記賬人 TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length]; KeyPair = null; for (int i = 0; i < Validators.Length; i++) { WalletAccount account = wallet.GetAccount(Validators[i]); if (account?.HasKey == true) { MyIndex = i; KeyPair = account.GetKey(); break; } } _header = null; }
如果是議長則狀態標記為ConsensusState.Primary,同時改變定時器觸發事件,再上次出塊15s后觸發。議員則設置狀態為 ConsensusState.Backup,時間調整為30s后觸發,如果議長不能正常工作,則這個觸發器會開始起作用(具體后邊再詳細分析)。
//file /Consensus/ConsensusContext.cs private void InitializeConsensus(byte view_number) { lock (context) { if (view_number == 0) context.Reset(wallet); else context.ChangeView(view_number); if (context.MyIndex < 0) return; Log($"initialize: height={context.BlockIndex} view={view_number} index={context.MyIndex} role={(context.MyIndex == context.PrimaryIndex ? ConsensusState.Primary : ConsensusState.Backup)}"); if (context.MyIndex == context.PrimaryIndex) { context.State |= ConsensusState.Primary; if (!context.State.HasFlag(ConsensusState.SignatureSent)) { FillContext(); //生成mine區塊 } if (context.TransactionHashes.Length > 1) { //廣播自身的交易 InvPayload invPayload = InvPayload.Create(InventoryType.TX, context.TransactionHashes.Skip(1).ToArray()); foreach (RemoteNode node in localNode.GetRemoteNodes()) node.EnqueueMessage("inv", invPayload); } timer_height = context.BlockIndex; timer_view = view_number; TimeSpan span = DateTime.Now - block_received_time; if (span >= Blockchain.TimePerBlock) timer.Change(0, Timeout.Infinite); else timer.Change(Blockchain.TimePerBlock - span, Timeout.InfiniteTimeSpan); } else { context.State = ConsensusState.Backup; timer_height = context.BlockIndex; timer_view = view_number; timer.Change(TimeSpan.FromSeconds(Blockchain.SecondsPerBlock << (view_number + 1)), Timeout.InfiniteTimeSpan); } } }
議長到了該記賬的時間后,執行下面方法,發送MakePrepareRequest請求,自身狀態轉變為RequestSent,也設置了30s后重復觸發定時器(同樣也是再議長工作異常時起效)。
//file /Consensus/ConsensusContext.cs private void OnTimeout(object state) { lock (context) { if (timer_height != context.BlockIndex || timer_view != context.ViewNumber) return; Log($"timeout: height={timer_height} view={timer_view} state={context.State}"); if (context.State.HasFlag(ConsensusState.Primary) && !context.State.HasFlag(ConsensusState.RequestSent)) { Log($"send perpare request: height={timer_height} view={timer_view}"); context.State |= ConsensusState.RequestSent; if (!context.State.HasFlag(ConsensusState.SignatureSent)) { context.Timestamp = Math.Max(DateTime.Now.ToTimestamp(), Blockchain.Default.GetHeader(context.PrevHash).Timestamp + 1); context.Signatures[context.MyIndex] = context.MakeHeader().Sign(context.KeyPair); } SignAndRelay(context.MakePrepareRequest()); timer.Change(TimeSpan.FromSeconds(Blockchain.SecondsPerBlock << (timer_view + 1)), Timeout.InfiniteTimeSpan); } else if ((context.State.HasFlag(ConsensusState.Primary) && context.State.HasFlag(ConsensusState.RequestSent)) || context.State.HasFlag(ConsensusState.Backup)) { RequestChangeView(); } } } }
議員接收到PrepareRequest,會對節點信息進行驗證,自身不存在的交易會去同步交易。交易同步完成后,驗證通過會進行發送PrepareResponse ,包含自己的簽名信息,表示自己已經通過了節點驗證。狀態轉變為ConsensusState.SignatureSent。
//file /Consensus/ConsensusContext.cs private void OnPrepareRequestReceived(ConsensusPayload payload, PrepareRequest message) { Log($"{nameof(OnPrepareRequestReceived)}: height={payload.BlockIndex} view={message.ViewNumber} index={payload.ValidatorIndex} tx={message.TransactionHashes.Length}"); if (!context.State.HasFlag(ConsensusState.Backup) || context.State.HasFlag(ConsensusState.RequestReceived)) return; if (payload.ValidatorIndex != context.PrimaryIndex) return; if (payload.Timestamp <= Blockchain.Default.GetHeader(context.PrevHash).Timestamp || payload.Timestamp > DateTime.Now.AddMinutes(10).ToTimestamp()) { Log($"Timestamp incorrect: {payload.Timestamp}"); return; } context.State |= ConsensusState.RequestReceived; context.Timestamp = payload.Timestamp; context.Nonce = message.Nonce; context.NextConsensus = message.NextConsensus; context.TransactionHashes = message.TransactionHashes; context.Transactions = new Dictionary<UInt256, Transaction>(); if (!Crypto.Default.VerifySignature(context.MakeHeader().GetHashData(), message.Signature, context.Validators[payload.ValidatorIndex].EncodePoint(false))) return; context.Signatures = new byte[context.Validators.Length][]; context.Signatures[payload.ValidatorIndex] = message.Signature; Dictionary<UInt256, Transaction> mempool = LocalNode.GetMemoryPool().ToDictionary(p => p.Hash); foreach (UInt256 hash in context.TransactionHashes.Skip(1)) { if (mempool.TryGetValue(hash, out Transaction tx)) if (!AddTransaction(tx, false)) return; } if (!AddTransaction(message.MinerTransaction, true)) return; if (context.Transactions.Count < context.TransactionHashes.Length) { UInt256[] hashes = context.TransactionHashes.Where(i => !context.Transactions.ContainsKey(i)).ToArray(); LocalNode.AllowHashes(hashes); InvPayload msg = InvPayload.Create(InventoryType.TX, hashes); foreach (RemoteNode node in localNode.GetRemoteNodes()) node.EnqueueMessage("getdata", msg); } }
//file /Consensus/ConsensusContext.cs private bool AddTransaction(Transaction tx, bool verify) { if (Blockchain.Default.ContainsTransaction(tx.Hash) || (verify && !tx.Verify(context.Transactions.Values)) || !CheckPolicy(tx)) { Log($"reject tx: {tx.Hash}{Environment.NewLine}{tx.ToArray().ToHexString()}"); RequestChangeView(); return false; } context.Transactions[tx.Hash] = tx; if (context.TransactionHashes.Length == context.Transactions.Count) { if (Blockchain.GetConsensusAddress(Blockchain.Default.GetValidators(context.Transactions.Values).ToArray()).Equals(context.NextConsensus)) { Log($"send perpare response"); context.State |= ConsensusState.SignatureSent; context.Signatures[context.MyIndex] = context.MakeHeader().Sign(context.KeyPair); SignAndRelay(context.MakePrepareResponse(context.Signatures[context.MyIndex])); CheckSignatures(); } else { RequestChangeView(); return false; } } return true; }
其他節點接收到PrepareResponse后,在自己的簽名列表中記錄對方的簽名信息,再檢查自己的簽名列表是否有超過三分之二的簽名了,有則判斷共識達成開始廣播生成的區塊。狀態狀變為ConsensusState.BlockSent。
private void CheckSignatures() { if (context.Signatures.Count(p => p != null) >= context.M && context.TransactionHashes.All(p => context.Transactions.ContainsKey(p))) { Contract contract = Contract.CreateMultiSigContract(context.M, context.Validators); Block block = context.MakeHeader(); ContractParametersContext sc = new ContractParametersContext(block); for (int i = 0, j = 0; i < context.Validators.Length && j < context.M; i++) if (context.Signatures[i] != null) { sc.AddSignature(contract, context.Validators[i], context.Signatures[i]); j++; } sc.Verifiable.Scripts = sc.GetScripts(); block.Transactions = context.TransactionHashes.Select(p => context.Transactions[p]).ToArray(); Log($"relay block: {block.Hash}"); if (!localNode.Relay(block)) Log($"reject block: {block.Hash}"); context.State |= ConsensusState.BlockSent; } }
區塊廣播后,節點接收到這個信息,會保存區塊,保存完成后觸發PersistCompleted事件,最終回到初始狀態,重新開始新一輪的共識。
private void Blockchain_PersistCompleted(object sender, Block block) { Log($"persist block: {block.Hash}"); block_received_time = DateTime.Now; InitializeConsensus(0); }
這種情況下議長在超出時間之后依然無法達成共識,此時議員會增長自身的ExpectedView值,并且廣播出去,如果檢查到三分之二的成員viewnumber都加了1,則在這些相同viewnumber的節點之間開始新一輪共識,重新選擇議長,發起共識。如果此時原來的議長恢復正常,time到時間后會增長自身的viewnumber,慢慢追上當前的視圖狀態。
關于“NEO DBFT共識算法源碼分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。