-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathConsensusService.cs
347 lines (318 loc) · 15.1 KB
/
ConsensusService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright (C) 2015-2024 The Neo Project.
//
// ConsensusService.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Akka.Actor;
using Neo.Extensions;
using Neo.IO;
using Neo.Ledger;
using Neo.Network.P2P;
using Neo.Network.P2P.Payloads;
using Neo.Plugins.DBFTPlugin.Messages;
using Neo.Plugins.DBFTPlugin.Types;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.Linq;
using static Neo.Ledger.Blockchain;
namespace Neo.Plugins.DBFTPlugin.Consensus
{
partial class ConsensusService : UntypedActor
{
public class Start { }
private class Timer { public uint Height; public byte ViewNumber; }
private readonly ConsensusContext context;
private readonly IActorRef localNode;
private readonly IActorRef taskManager;
private readonly IActorRef blockchain;
private ICancelable timer_token;
private DateTime block_received_time;
private uint block_received_index;
private bool started = false;
/// <summary>
/// This will record the information from last scheduled timer
/// </summary>
private DateTime clock_started = TimeProvider.Current.UtcNow;
private TimeSpan expected_delay = TimeSpan.Zero;
/// <summary>
/// This will be cleared every block (so it will not grow out of control, but is used to prevent repeatedly
/// responding to the same message.
/// </summary>
private readonly HashSet<UInt256> knownHashes = new();
/// <summary>
/// This variable is only true during OnRecoveryMessageReceived
/// </summary>
private bool isRecovering = false;
private readonly Settings dbftSettings;
private readonly NeoSystem neoSystem;
public ConsensusService(NeoSystem neoSystem, Settings settings, Wallet wallet)
: this(neoSystem, settings, new ConsensusContext(neoSystem, settings, wallet)) { }
internal ConsensusService(NeoSystem neoSystem, Settings settings, ConsensusContext context)
{
this.neoSystem = neoSystem;
localNode = neoSystem.LocalNode;
taskManager = neoSystem.TaskManager;
blockchain = neoSystem.Blockchain;
dbftSettings = settings;
this.context = context;
Context.System.EventStream.Subscribe(Self, typeof(Blockchain.PersistCompleted));
Context.System.EventStream.Subscribe(Self, typeof(Blockchain.RelayResult));
}
private void OnPersistCompleted(Block block)
{
Log($"Persisted {nameof(Block)}: height={block.Index} hash={block.Hash} tx={block.Transactions.Length} nonce={block.Nonce}");
knownHashes.Clear();
InitializeConsensus(0);
}
private void InitializeConsensus(byte viewNumber)
{
context.Reset(viewNumber);
if (viewNumber > 0)
Log($"View changed: view={viewNumber} primary={context.Validators[context.GetPrimaryIndex((byte)(viewNumber - 1u))]}", LogLevel.Warning);
Log($"Initialize: height={context.Block.Index} view={viewNumber} index={context.MyIndex} role={(context.IsPrimary ? "Primary" : context.WatchOnly ? "WatchOnly" : "Backup")}");
if (context.WatchOnly) return;
if (context.IsPrimary)
{
if (isRecovering)
{
ChangeTimer(TimeSpan.FromMilliseconds(neoSystem.Settings.MillisecondsPerBlock << (viewNumber + 1)));
}
else
{
TimeSpan span = neoSystem.Settings.TimePerBlock;
if (block_received_index + 1 == context.Block.Index)
{
var diff = TimeProvider.Current.UtcNow - block_received_time;
if (diff >= span)
span = TimeSpan.Zero;
else
span -= diff;
}
ChangeTimer(span);
}
}
else
{
ChangeTimer(TimeSpan.FromMilliseconds(neoSystem.Settings.MillisecondsPerBlock << (viewNumber + 1)));
}
}
protected override void OnReceive(object message)
{
if (message is Start)
{
if (started) return;
OnStart();
}
else
{
if (!started) return;
switch (message)
{
case Timer timer:
OnTimer(timer);
break;
case Transaction transaction:
OnTransaction(transaction);
break;
case Blockchain.PersistCompleted completed:
OnPersistCompleted(completed.Block);
break;
case Blockchain.RelayResult rr:
if (rr.Result == VerifyResult.Succeed && rr.Inventory is ExtensiblePayload payload && payload.Category == "dBFT")
OnConsensusPayload(payload);
break;
}
}
}
private void OnStart()
{
Log("OnStart");
started = true;
if (!dbftSettings.IgnoreRecoveryLogs && context.Load())
{
if (context.Transactions != null)
{
blockchain.Ask<Blockchain.FillCompleted>(new Blockchain.FillMemoryPool
{
Transactions = context.Transactions.Values
}).Wait();
}
if (context.CommitSent)
{
CheckPreparations();
return;
}
}
InitializeConsensus(context.ViewNumber);
// Issue a recovery request on start-up in order to possibly catch up with other nodes
if (!context.WatchOnly)
RequestRecovery();
}
private void OnTimer(Timer timer)
{
if (context.WatchOnly || context.BlockSent) return;
if (timer.Height != context.Block.Index || timer.ViewNumber != context.ViewNumber) return;
if (context.IsPrimary && !context.RequestSentOrReceived)
{
SendPrepareRequest();
}
else if ((context.IsPrimary && context.RequestSentOrReceived) || context.IsBackup)
{
if (context.CommitSent)
{
// Re-send commit periodically by sending recover message in case of a network issue.
Log($"Sending {nameof(RecoveryMessage)} to resend {nameof(Commit)}");
localNode.Tell(new LocalNode.SendDirectly { Inventory = context.MakeRecoveryMessage() });
ChangeTimer(TimeSpan.FromMilliseconds(neoSystem.Settings.MillisecondsPerBlock << 1));
}
else
{
var reason = ChangeViewReason.Timeout;
if (context.Block != null && context.TransactionHashes?.Length > context.Transactions?.Count)
{
reason = ChangeViewReason.TxNotFound;
}
RequestChangeView(reason);
}
}
}
private void SendPrepareRequest()
{
Log($"Sending {nameof(PrepareRequest)}: height={context.Block.Index} view={context.ViewNumber}");
localNode.Tell(new LocalNode.SendDirectly { Inventory = context.MakePrepareRequest() });
if (context.Validators.Length == 1)
CheckPreparations();
if (context.TransactionHashes.Length > 0)
{
foreach (InvPayload payload in InvPayload.CreateGroup(InventoryType.TX, context.TransactionHashes))
localNode.Tell(Message.Create(MessageCommand.Inv, payload));
}
ChangeTimer(TimeSpan.FromMilliseconds((neoSystem.Settings.MillisecondsPerBlock << (context.ViewNumber + 1)) - (context.ViewNumber == 0 ? neoSystem.Settings.MillisecondsPerBlock : 0)));
}
private void RequestRecovery()
{
Log($"Sending {nameof(RecoveryRequest)}: height={context.Block.Index} view={context.ViewNumber} nc={context.CountCommitted} nf={context.CountFailed}");
localNode.Tell(new LocalNode.SendDirectly { Inventory = context.MakeRecoveryRequest() });
}
private void RequestChangeView(ChangeViewReason reason)
{
if (context.WatchOnly) return;
// Request for next view is always one view more than the current context.ViewNumber
// Nodes will not contribute for changing to a view higher than (context.ViewNumber+1), unless they are recovered
// The latter may happen by nodes in higher views with, at least, `M` proofs
byte expectedView = context.ViewNumber;
expectedView++;
ChangeTimer(TimeSpan.FromMilliseconds(neoSystem.Settings.MillisecondsPerBlock << (expectedView + 1)));
if ((context.CountCommitted + context.CountFailed) > context.F)
{
RequestRecovery();
}
else
{
Log($"Sending {nameof(ChangeView)}: height={context.Block.Index} view={context.ViewNumber} nv={expectedView} nc={context.CountCommitted} nf={context.CountFailed} reason={reason}");
localNode.Tell(new LocalNode.SendDirectly { Inventory = context.MakeChangeView(reason) });
CheckExpectedView(expectedView);
}
}
private bool ReverifyAndProcessPayload(ExtensiblePayload payload)
{
RelayResult relayResult = blockchain.Ask<RelayResult>(new Blockchain.Reverify { Inventories = new IInventory[] { payload } }).Result;
if (relayResult.Result != VerifyResult.Succeed) return false;
OnConsensusPayload(payload);
return true;
}
private void OnTransaction(Transaction transaction)
{
if (!context.IsBackup || context.NotAcceptingPayloadsDueToViewChanging || !context.RequestSentOrReceived || context.ResponseSent || context.BlockSent)
return;
if (context.Transactions.ContainsKey(transaction.Hash)) return;
if (!context.TransactionHashes.Contains(transaction.Hash)) return;
AddTransaction(transaction, true);
}
private bool AddTransaction(Transaction tx, bool verify)
{
if (verify)
{
// At this step we're sure that there's no on-chain transaction that conflicts with
// the provided tx because of the previous Blockchain's OnReceive check. Thus, we only
// need to check that current context doesn't contain conflicting transactions.
VerifyResult result;
// Firstly, check whether tx has Conlicts attribute with the hash of one of the context's transactions.
foreach (var h in tx.GetAttributes<Conflicts>().Select(attr => attr.Hash))
{
if (context.TransactionHashes.Contains(h))
{
result = VerifyResult.HasConflicts;
Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning);
RequestChangeView(ChangeViewReason.TxInvalid);
return false;
}
}
// After that, check whether context's transactions have Conflicts attribute with tx's hash.
foreach (var pooledTx in context.Transactions.Values)
{
if (pooledTx.GetAttributes<Conflicts>().Select(attr => attr.Hash).Contains(tx.Hash))
{
result = VerifyResult.HasConflicts;
Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning);
RequestChangeView(ChangeViewReason.TxInvalid);
return false;
}
}
// We've ensured that there's no conlicting transactions in the context, thus, can safely provide an empty conflicting list
// for futher verification.
var conflictingTxs = new List<Transaction>();
result = tx.Verify(neoSystem.Settings, context.Snapshot, context.VerificationContext, conflictingTxs);
if (result != VerifyResult.Succeed)
{
Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning);
RequestChangeView(result == VerifyResult.PolicyFail ? ChangeViewReason.TxRejectedByPolicy : ChangeViewReason.TxInvalid);
return false;
}
}
context.Transactions[tx.Hash] = tx;
context.VerificationContext.AddTransaction(tx);
return CheckPrepareResponse();
}
private void ChangeTimer(TimeSpan delay)
{
clock_started = TimeProvider.Current.UtcNow;
expected_delay = delay;
timer_token.CancelIfNotNull();
timer_token = Context.System.Scheduler.ScheduleTellOnceCancelable(delay, Self, new Timer
{
Height = context.Block.Index,
ViewNumber = context.ViewNumber
}, ActorRefs.NoSender);
}
// this function increases existing timer (never decreases) with a value proportional to `maxDelayInBlockTimes`*`Blockchain.MillisecondsPerBlock`
private void ExtendTimerByFactor(int maxDelayInBlockTimes)
{
TimeSpan nextDelay = expected_delay - (TimeProvider.Current.UtcNow - clock_started) + TimeSpan.FromMilliseconds(maxDelayInBlockTimes * neoSystem.Settings.MillisecondsPerBlock / (double)context.M);
if (!context.WatchOnly && !context.ViewChanging && !context.CommitSent && (nextDelay > TimeSpan.Zero))
ChangeTimer(nextDelay);
}
protected override void PostStop()
{
Log("OnStop");
started = false;
Context.System.EventStream.Unsubscribe(Self);
context.Dispose();
base.PostStop();
}
public static Props Props(NeoSystem neoSystem, Settings dbftSettings, Wallet wallet)
{
return Akka.Actor.Props.Create(() => new ConsensusService(neoSystem, dbftSettings, wallet));
}
private static void Log(string message, LogLevel level = LogLevel.Info)
{
Utility.Log(nameof(ConsensusService), level, message);
}
}
}