From de67e4e0d93a164a2c7f08b5eb83fa15196f3b5c Mon Sep 17 00:00:00 2001 From: Risto Laanoja Date: Sun, 8 Nov 2026 02:50:24 +0200 Subject: [PATCH] UTB parity 3/4: pinned append-only history and complete tag-39015 bundles; weighted quorum, overlap and 256-to-4 tests TrustBaseHistory (create(pin), append -> APPENDED/ALREADY_HELD, entryForEpoch, epochEndRound, toBundle, fromBundle), TrustBaseBundle/Limits, TrustBaseResponseWire (public, shared with the page decoder), typed errors (Bundle, Network, BeforeGenesis, Gap, Conflict with details). Appends are serialised under a lock without I/O; epochs and rounds compare as unsigned. Shared bft-go-base history, weightedQuorum and bundles vectors. --- .../bft/trustbase/TrustBaseAppendOutcome.java | 9 + .../TrustBaseBeforeGenesisException.java | 14 + .../api/bft/trustbase/TrustBaseBundle.java | 205 ++++++++++++ .../trustbase/TrustBaseBundleException.java | 14 + .../bft/trustbase/TrustBaseBundleLimits.java | 54 +++ .../trustbase/TrustBaseConflictDetails.java | 101 ++++++ .../trustbase/TrustBaseConflictException.java | 49 +++ .../bft/trustbase/TrustBaseGapException.java | 41 +++ .../api/bft/trustbase/TrustBaseHistory.java | 231 +++++++++++++ .../trustbase/TrustBaseNetworkException.java | 14 + .../bft/trustbase/TrustBaseResponseWire.java | 199 +++++++++++ .../bft/trustbase/TrustBaseBundleTest.java | 160 +++++++++ .../trustbase/TrustBaseHistoryRulesTest.java | 313 ++++++++++++++++++ .../TrustBaseHistoryVectorsTest.java | 130 ++++++++ .../api/bft/trustbase/TrustBaseTestChain.java | 90 +++++ 15 files changed, 1624 insertions(+) create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseAppendOutcome.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBeforeGenesisException.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundle.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleException.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleLimits.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictDetails.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictException.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseGapException.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistory.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseNetworkException.java create mode 100644 src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseResponseWire.java create mode 100644 src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleTest.java create mode 100644 src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryRulesTest.java create mode 100644 src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryVectorsTest.java create mode 100644 src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseTestChain.java diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseAppendOutcome.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseAppendOutcome.java new file mode 100644 index 0000000..789d71c --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseAppendOutcome.java @@ -0,0 +1,9 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +/** What {@link TrustBaseHistory#append} did with an entry that passed. */ +public enum TrustBaseAppendOutcome { + /** The entry was added. */ + APPENDED, + /** The entry was already held: nothing changed. */ + ALREADY_HELD +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBeforeGenesisException.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBeforeGenesisException.java new file mode 100644 index 0000000..be43f8c --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBeforeGenesisException.java @@ -0,0 +1,14 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +/** An entry is of an epoch before the genesis epoch of the history. */ +public class TrustBaseBeforeGenesisException extends TrustBaseChainException { + + /** + * Create the exception. + * + * @param message what failed + */ + public TrustBaseBeforeGenesisException(String message) { + super(message); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundle.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundle.java new file mode 100644 index 0000000..0305865 --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundle.java @@ -0,0 +1,205 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import org.unicitylabs.sdk.api.NetworkId; +import org.unicitylabs.sdk.util.UnsignedLongs; + +/** + * A complete Unicity Trust Base release bundle: the GetTrustBase response (CBOR tag 39015) with + * status OK, starting at the genesis entry, ending at the release tip, with no continuation + * cursor. The reference is bft-core {@code gettrustbase.DecodeBundle}. + * + *

Wire form: tag 39015 over {@code [1, networkId, 0, fromEpoch, effectiveEnd, endEntryId, + * [entry...], null]}, each entry a complete tag-39000 {@link TrustBaseEntry}, consecutive and + * ascending from the genesis, each linked to its predecessor by entry id. A one-entry bundle holds + * a genesis entry only. + * + *

Decoding checks the structure and the links, not the signatures: the history that installs + * the bundle authenticates every entry after the genesis, and the genesis against a pinned entry + * id. + */ +public final class TrustBaseBundle { + + private final NetworkId networkId; + private final List entries; + private final List raw; + + private TrustBaseBundle(NetworkId networkId, List entries, List raw) { + this.networkId = networkId; + this.entries = Collections.unmodifiableList(new ArrayList<>(entries)); + this.raw = raw; + } + + /** + * Get the network. + * + * @return network id + */ + public NetworkId getNetworkId() { + return this.networkId; + } + + /** + * Get the entries, ascending from the genesis. + * + * @return immutable list + */ + public List getEntries() { + return this.entries; + } + + /** + * Get the canonical bytes of each entry, ascending from the genesis. + * + * @return copies + */ + public List getRaw() { + List copy = new ArrayList<>(this.raw.size()); + for (byte[] bytes : this.raw) { + copy.add(Arrays.copyOf(bytes, bytes.length)); + } + return copy; + } + + /** + * Get the release tip. + * + * @return the last entry + */ + public TrustBaseEntry getTip() { + return this.entries.get(this.entries.size() - 1); + } + + /** + * Strictly decode a complete bundle. + * + * @param bytes tagged bundle + * @param limits size budget, checked before allocation + * @return the bundle + * @throws TrustBaseEncodingException if the bytes (or an entry) are not the deterministic + * encoding, or exceed the budget + * @throws TrustBaseInvalidException if an embedded entry fails a structure rule + * @throws TrustBaseBundleException if the response is not a complete, linked history from a + * genesis entry + */ + public static TrustBaseBundle decode(byte[] bytes, TrustBaseBundleLimits limits) { + Objects.requireNonNull(bytes, "bytes cannot be null"); + Objects.requireNonNull(limits, "limits cannot be null"); + if (bytes.length > limits.getMaxBytes()) { + throw new TrustBaseEncodingException( + bytes.length + " bytes exceed the budget of " + limits.getMaxBytes() + "."); + } + + TrustBaseResponseWire.Fields header = TrustBaseResponseWire.parse(bytes, limits.getMaxEntries()); + if (header.getStatus() != TrustBaseResponseWire.STATUS_OK) { + throw new TrustBaseBundleException( + "Status " + Long.toUnsignedString(header.getStatus()) + ": not a complete bundle."); + } + if (header.getNextEpoch() != null) { + throw new TrustBaseBundleException("A continuation cursor: not a complete bundle."); + } + List rawEntries = header.getEntries(); + if (rawEntries.isEmpty()) { + throw new TrustBaseBundleException("An OK response without entries."); + } + byte[] endEntryId = header.getEndEntryId(); + if (endEntryId == null) { + throw new TrustBaseBundleException("No end entry id."); + } + + List entries = new ArrayList<>(rawEntries.size()); + byte[] previousId = null; + for (int index = 0; index < rawEntries.size(); index++) { + byte[] rawEntry = rawEntries.get(index); + if (rawEntry.length > limits.getMaxEntryBytes()) { + throw new TrustBaseEncodingException("Entry " + index + " of " + rawEntry.length + " bytes."); + } + TrustBaseEntry entry = TrustBaseEntry.decode(rawEntry); + if (entry.getNetworkId().getId() != header.getNetwork()) { + throw new TrustBaseBundleException("Entry " + index + " of network " + + entry.getNetworkId().getId() + " in a bundle for " + header.getNetwork() + "."); + } + if (index == 0) { + if (!entry.isGenesis()) { + throw new TrustBaseBundleException("Epoch " + UnsignedLongs.toDecimal(entry.getEpoch()) + + " is not a genesis entry (a partial range)."); + } + if (entry.getEpoch() != header.getFromEpoch()) { + throw new TrustBaseBundleException("First entry is epoch " + + UnsignedLongs.toDecimal(entry.getEpoch()) + ", the bundle starts at " + + UnsignedLongs.toDecimal(header.getFromEpoch()) + "."); + } + } else { + TrustBaseEntry previous = entries.get(index - 1); + if (entry.getEpoch() != previous.getEpoch() + 1) { + throw new TrustBaseBundleException("Epoch " + UnsignedLongs.toDecimal(entry.getEpoch()) + + " does not follow " + UnsignedLongs.toDecimal(previous.getEpoch()) + "."); + } + if (!Arrays.equals(entry.getPreviousEntryId(), previousId)) { + throw new TrustBaseBundleException("Epoch " + UnsignedLongs.toDecimal(entry.getEpoch()) + + " does not link to its predecessor."); + } + } + previousId = entry.entryId(); + entries.add(entry); + } + + TrustBaseEntry tip = entries.get(entries.size() - 1); + if (tip.getEpoch() != header.getEffectiveEnd()) { + throw new TrustBaseBundleException("The bundle ends at epoch " + + UnsignedLongs.toDecimal(tip.getEpoch()) + ", its header says " + + UnsignedLongs.toDecimal(header.getEffectiveEnd()) + "."); + } + if (!Arrays.equals(endEntryId, previousId)) { + throw new TrustBaseBundleException("The end entry id differs from the last entry."); + } + return new TrustBaseBundle(entries.get(0).getNetworkId(), entries, rawEntries); + } + + /** + * Encode entries as a complete bundle (status OK, no cursor, end entry id of the last entry). + * The inverse of {@link #decode}: a decoded bundle re-encodes to the same bytes. The entries are + * not authenticated here; a bundle that does not link is not produced. + * + * @param entries consecutive entries ascending from the genesis, at least one + * @return tagged bundle + * @throws TrustBaseBundleException if the list is empty or the entries do not form one linked + * chain of one network + */ + public static byte[] encode(List entries) { + Objects.requireNonNull(entries, "entries cannot be null"); + if (entries.isEmpty()) { + throw new TrustBaseBundleException("A bundle needs at least one entry."); + } + + byte[] previousId = null; + List raw = new ArrayList<>(entries.size()); + for (int index = 0; index < entries.size(); index++) { + TrustBaseEntry entry = entries.get(index); + if (index == 0) { + if (!entry.isGenesis()) { + throw new TrustBaseBundleException("Entry 0 does not continue the chain."); + } + } else if (entry.getEpoch() != entries.get(index - 1).getEpoch() + 1) { + throw new TrustBaseBundleException("Entry " + index + " does not continue the chain."); + } + if (previousId != null && !Arrays.equals(entry.getPreviousEntryId(), previousId)) { + throw new TrustBaseBundleException("Entry " + index + " does not link to its predecessor."); + } + if (entry.getNetworkId().getId() != entries.get(0).getNetworkId().getId()) { + throw new TrustBaseBundleException("Entry " + index + " is of another network."); + } + previousId = entry.entryId(); + raw.add(entry.encode()); + } + + TrustBaseEntry tip = entries.get(entries.size() - 1); + return TrustBaseResponseWire.encode(new TrustBaseResponseWire.Fields(tip.getEpoch(), + previousId, raw, entries.get(0).getEpoch(), tip.getNetworkId().getId(), null, + TrustBaseResponseWire.STATUS_OK)); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleException.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleException.java new file mode 100644 index 0000000..3e168f5 --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleException.java @@ -0,0 +1,14 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +/** A GetTrustBase response is not a complete, linked history from a genesis entry (status, cursor, range, links, end identity). */ +public class TrustBaseBundleException extends TrustBaseException { + + /** + * Create the exception. + * + * @param message what failed + */ + public TrustBaseBundleException(String message) { + super(message); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleLimits.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleLimits.java new file mode 100644 index 0000000..a9353d0 --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleLimits.java @@ -0,0 +1,54 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +/** + * Budget of a bundle decode; a release supplies it, there is no fixed history length. + * {@code maxBytes} is checked before anything is read; {@code maxEntries} from the array header + * before any entry is read. + */ +public final class TrustBaseBundleLimits { + + private final int maxBytes; + private final int maxEntries; + private final int maxEntryBytes; + + /** + * Create a budget with the default per-entry bound ({@link TrustBaseEntry#MAX_ENTRY_BYTES}). + * + * @param maxBytes most bytes of the whole bundle + * @param maxEntries most entries + */ + public TrustBaseBundleLimits(int maxBytes, int maxEntries) { + this(maxBytes, maxEntries, TrustBaseEntry.MAX_ENTRY_BYTES); + } + + /** + * Create a budget. + * + * @param maxBytes most bytes of the whole bundle + * @param maxEntries most entries + * @param maxEntryBytes most bytes of one entry + */ + public TrustBaseBundleLimits(int maxBytes, int maxEntries, int maxEntryBytes) { + if (maxBytes <= 0 || maxEntries <= 0 || maxEntryBytes <= 0) { + throw new IllegalArgumentException("Limits must be positive."); + } + this.maxBytes = maxBytes; + this.maxEntries = maxEntries; + this.maxEntryBytes = maxEntryBytes; + } + + /** Get the byte budget of the whole bundle. */ + public int getMaxBytes() { + return this.maxBytes; + } + + /** Get the entry-count budget. */ + public int getMaxEntries() { + return this.maxEntries; + } + + /** Get the byte budget of one entry. */ + public int getMaxEntryBytes() { + return this.maxEntryBytes; + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictDetails.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictDetails.java new file mode 100644 index 0000000..103e0a8 --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictDetails.java @@ -0,0 +1,101 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import java.util.Arrays; + +/** What is known about two different entries of one epoch: bounded, identities and optionally the entries. */ +public final class TrustBaseConflictDetails { + + private final boolean authenticated; + private final long epoch; + private final byte[] heldEntry; + private final byte[] heldEntryId; + private final int network; + private final byte[] offeredEntry; + private final byte[] offeredEntryId; + + /** + * Create the details. + * + * @param authenticated whether the offered entry is signed by a quorum of its predecessor + * @param epoch epoch of both entries, unsigned + * @param heldEntry the held entry bytes, or null + * @param heldEntryId id of the held entry + * @param network network id of the offered entry + * @param offeredEntry the offered entry bytes, or null + * @param offeredEntryId id of the offered entry + */ + public TrustBaseConflictDetails(boolean authenticated, long epoch, byte[] heldEntry, + byte[] heldEntryId, int network, byte[] offeredEntry, byte[] offeredEntryId) { + this.authenticated = authenticated; + this.epoch = epoch; + this.heldEntry = heldEntry == null ? null : Arrays.copyOf(heldEntry, heldEntry.length); + this.heldEntryId = Arrays.copyOf(heldEntryId, heldEntryId.length); + this.network = network; + this.offeredEntry = offeredEntry == null ? null : Arrays.copyOf(offeredEntry, offeredEntry.length); + this.offeredEntryId = Arrays.copyOf(offeredEntryId, offeredEntryId.length); + } + + /** + * Tell whether the offered entry was authenticated by a quorum of its predecessor. + * + * @return true if authenticated; false if only its identity differs + */ + public boolean isAuthenticated() { + return this.authenticated; + } + + /** + * Get the epoch. + * + * @return epoch, unsigned bits + */ + public long getEpoch() { + return this.epoch; + } + + /** + * Get the held entry bytes. + * + * @return copy, or null when not kept + */ + public byte[] getHeldEntry() { + return this.heldEntry == null ? null : Arrays.copyOf(this.heldEntry, this.heldEntry.length); + } + + /** + * Get the id of the held entry. + * + * @return copy + */ + public byte[] getHeldEntryId() { + return Arrays.copyOf(this.heldEntryId, this.heldEntryId.length); + } + + /** + * Get the network id. + * + * @return network id + */ + public int getNetwork() { + return this.network; + } + + /** + * Get the offered entry bytes. + * + * @return copy, or null when not kept + */ + public byte[] getOfferedEntry() { + return this.offeredEntry == null ? null + : Arrays.copyOf(this.offeredEntry, this.offeredEntry.length); + } + + /** + * Get the id of the offered entry. + * + * @return copy + */ + public byte[] getOfferedEntryId() { + return Arrays.copyOf(this.offeredEntryId, this.offeredEntryId.length); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictException.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictException.java new file mode 100644 index 0000000..f4caded --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseConflictException.java @@ -0,0 +1,49 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import org.unicitylabs.sdk.util.UnsignedLongs; + +/** A different entry is offered for an epoch the history already holds. */ +public class TrustBaseConflictException extends TrustBaseException { + + private final long epoch; + private final TrustBaseConflictDetails details; + + /** + * Create the exception. + * + * @param epoch the epoch, unsigned + * @param details bounded evidence, may be null + */ + public TrustBaseConflictException(long epoch, TrustBaseConflictDetails details) { + super("A different entry is held for epoch " + UnsignedLongs.toDecimal(epoch) + "."); + this.epoch = epoch; + this.details = details; + } + + /** + * Get the epoch. + * + * @return epoch, unsigned bits + */ + public long getEpoch() { + return this.epoch; + } + + /** + * Get the evidence. + * + * @return details, or null + */ + public TrustBaseConflictDetails getDetails() { + return this.details; + } + + /** + * Tell whether the offered entry is signed by a quorum of its predecessor. + * + * @return true if the evidence says it is authenticated + */ + public boolean isAuthenticated() { + return this.details != null && this.details.isAuthenticated(); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseGapException.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseGapException.java new file mode 100644 index 0000000..d4508ec --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseGapException.java @@ -0,0 +1,41 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import org.unicitylabs.sdk.util.UnsignedLongs; + +/** An entry is more than one epoch ahead of the tip: the entries in between must be fetched first. */ +public class TrustBaseGapException extends TrustBaseException { + + private final long epoch; + private final long tipEpoch; + + /** + * Create the exception. + * + * @param epoch epoch of the offered entry, unsigned + * @param tipEpoch epoch of the held tip, unsigned + */ + public TrustBaseGapException(long epoch, long tipEpoch) { + super("Epoch " + UnsignedLongs.toDecimal(epoch) + " is ahead of the tip " + + UnsignedLongs.toDecimal(tipEpoch) + "."); + this.epoch = epoch; + this.tipEpoch = tipEpoch; + } + + /** + * Get the epoch of the offered entry. + * + * @return epoch, unsigned bits + */ + public long getEpoch() { + return this.epoch; + } + + /** + * Get the epoch of the held tip. + * + * @return epoch, unsigned bits + */ + public long getTipEpoch() { + return this.tipEpoch; + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistory.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistory.java new file mode 100644 index 0000000..8f70706 --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistory.java @@ -0,0 +1,231 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalLong; +import org.unicitylabs.sdk.api.NetworkId; +import org.unicitylabs.sdk.util.UnsignedLongs; + +/** + * The append-only Unicity Trust Base history a verifier holds: consecutive entries from a genesis + * entry pinned out of band by its entry id, each authenticated by a strict quorum of its + * predecessor's members. The reference is the shared vectors' history model (bft-go-base + * {@code types/root_trust_base_v2_vectors_test.go}) and bft-core {@code utbstore}. + * + *

{@link #append(TrustBaseEntry)} is the only way in, for the genesis and for every later + * entry, including those of a loaded bundle. An entry of a held epoch changes nothing: the same + * entry id is {@link TrustBaseAppendOutcome#ALREADY_HELD} (its signature set must still verify, so + * a bad witness is an error), a different one is a conflict. An entry more than one epoch ahead is + * a gap. Appends are serialised and every reader sees a consistent chain; no I/O happens under the + * lock. Epochs and rounds are unsigned 64-bit numbers carried as {@code long} bits. + */ +public final class TrustBaseHistory { + + private final Object lock = new Object(); + private final List entries = new ArrayList<>(); + private final byte[] genesisPin; + + private TrustBaseHistory(byte[] genesisPin) { + this.genesisPin = genesisPin; + } + + /** + * An empty history bound to the genesis it will accept. + * + * @param genesisPin entry id of the genesis entry, from outside the history (a release pin); + * copied + * @return empty history + * @throws TrustBaseInvalidException if the pin is not a 32-byte entry id + */ + public static TrustBaseHistory create(byte[] genesisPin) { + Objects.requireNonNull(genesisPin, "genesisPin cannot be null"); + if (genesisPin.length != TrustBaseEntry.ID_LENGTH) { + throw new TrustBaseInvalidException("Genesis pin of " + genesisPin.length + " bytes."); + } + return new TrustBaseHistory(Arrays.copyOf(genesisPin, genesisPin.length)); + } + + /** + * Load a complete bundle through {@link #append}, like every later entry. + * + * @param bundle decoded bundle + * @param genesisPin entry id of the genesis entry + * @return history holding every entry of the bundle + * @throws TrustBaseChainException if the genesis is not the pinned one or an entry does not + * extend its predecessor + * @throws TrustBaseSignatureException if an entry is not signed by a quorum of its predecessor + */ + public static TrustBaseHistory fromBundle(TrustBaseBundle bundle, byte[] genesisPin) { + TrustBaseHistory history = create(genesisPin); + for (TrustBaseEntry entry : bundle.getEntries()) { + history.append(entry); + } + return history; + } + + /** + * Get a snapshot of the held entries. + * + * @return immutable list, ascending from the genesis + */ + public List getEntries() { + synchronized (this.lock) { + return List.copyOf(this.entries); + } + } + + /** + * Get the pinned entry id of the genesis. + * + * @return copy + */ + public byte[] getGenesisPin() { + return Arrays.copyOf(this.genesisPin, this.genesisPin.length); + } + + /** + * Tell whether no entry is held yet. + * + * @return true if empty + */ + public boolean isEmpty() { + synchronized (this.lock) { + return this.entries.isEmpty(); + } + } + + /** + * Get the network of the held entries. + * + * @return the network, empty when the history is empty + */ + public Optional getNetworkId() { + synchronized (this.lock) { + return this.entries.isEmpty() ? Optional.empty() + : Optional.of(this.entries.get(0).getNetworkId()); + } + } + + /** + * Get the latest held entry. + * + * @return the tip, empty when the history is empty + */ + public Optional getTip() { + synchronized (this.lock) { + return this.entries.isEmpty() ? Optional.empty() + : Optional.of(this.entries.get(this.entries.size() - 1)); + } + } + + /** + * Add an entry. + * + * @param entry decoded entry + * @return {@link TrustBaseAppendOutcome#APPENDED}, or + * {@link TrustBaseAppendOutcome#ALREADY_HELD} when the entry is already held + * @throws TrustBaseInvalidException if the first entry is not a genesis entry + * @throws TrustBaseChainException if the first entry is not the pinned genesis, or the entry does + * not extend the tip (or its held predecessor) + * @throws TrustBaseSignatureException if the predecessor's members did not sign it with a quorum + * @throws TrustBaseConflictException if a different entry is held for the epoch + * @throws TrustBaseGapException if the entry is more than one epoch ahead of the tip + */ + public TrustBaseAppendOutcome append(TrustBaseEntry entry) { + Objects.requireNonNull(entry, "entry cannot be null"); + synchronized (this.lock) { + if (this.entries.isEmpty()) { + entry.verifyGenesis(); + if (!Arrays.equals(entry.entryId(), this.genesisPin)) { + throw new TrustBaseChainException("The genesis is not the pinned identity."); + } + this.entries.add(entry); + return TrustBaseAppendOutcome.APPENDED; + } + + TrustBaseEntry first = this.entries.get(0); + TrustBaseEntry tip = this.entries.get(this.entries.size() - 1); + if (UnsignedLongs.compare(entry.getEpoch(), tip.getEpoch()) <= 0) { + if (UnsignedLongs.compare(entry.getEpoch(), first.getEpoch()) < 0) { + throw new TrustBaseBeforeGenesisException("Epoch " + + UnsignedLongs.toDecimal(entry.getEpoch()) + " is before the genesis epoch " + + UnsignedLongs.toDecimal(first.getEpoch()) + "."); + } + int index = (int) (entry.getEpoch() - first.getEpoch()); + byte[] heldId = this.entries.get(index).entryId(); + byte[] offeredId = entry.entryId(); + if (!Arrays.equals(heldId, offeredId)) { + // Different, but not authenticated: the caller that wants to know whether it is a fork + // verifies the entry against the predecessor. + throw new TrustBaseConflictException(entry.getEpoch(), new TrustBaseConflictDetails( + false, entry.getEpoch(), null, heldId, entry.getNetworkId().getId(), null, + offeredId)); + } + if (index > 0) { + entry.verifySuccessor(this.entries.get(index - 1)); + } + return TrustBaseAppendOutcome.ALREADY_HELD; + } + if (entry.getEpoch() != tip.getEpoch() + 1) { + throw new TrustBaseGapException(entry.getEpoch(), tip.getEpoch()); + } + entry.verifySuccessor(tip); + this.entries.add(entry); + return TrustBaseAppendOutcome.APPENDED; + } + } + + /** + * Get the held entry of an epoch. + * + * @param epoch epoch, unsigned bits + * @return the entry, empty when the epoch is before the genesis or after the tip (the caller may + * fetch and append) + */ + public Optional entryForEpoch(long epoch) { + synchronized (this.lock) { + if (this.entries.isEmpty()) { + return Optional.empty(); + } + TrustBaseEntry first = this.entries.get(0); + if (UnsignedLongs.compare(epoch, first.getEpoch()) < 0) { + return Optional.empty(); + } + long offset = epoch - first.getEpoch(); + if (UnsignedLongs.compare(offset, this.entries.size()) >= 0) { + return Optional.empty(); + } + return Optional.of(this.entries.get((int) offset)); + } + } + + /** + * Get the round at which the held successor of an epoch starts, which ends the epoch's interval. + * + * @param epoch epoch, unsigned bits + * @return start round of the entry for {@code epoch + 1}, empty when none is held (the epoch is + * open-ended as far as this history knows) + */ + public OptionalLong epochEndRound(long epoch) { + if (epoch == -1L) { + return OptionalLong.empty(); + } + return entryForEpoch(epoch + 1) + .map(entry -> OptionalLong.of(entry.getEpochStartRound())) + .orElse(OptionalLong.empty()); + } + + /** + * Get the held entries as one complete bundle (tag 39015), the form a cache stores. Round-trips + * through {@link TrustBaseBundle#decode}. + * + * @return tagged bundle + * @throws TrustBaseBundleException if the history is empty + */ + public byte[] toBundle() { + return TrustBaseBundle.encode(getEntries()); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseNetworkException.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseNetworkException.java new file mode 100644 index 0000000..c3b29ee --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseNetworkException.java @@ -0,0 +1,14 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +/** An entry or response belongs to another network than the history it is offered to. */ +public class TrustBaseNetworkException extends TrustBaseChainException { + + /** + * Create the exception. + * + * @param message what failed + */ + public TrustBaseNetworkException(String message) { + super(message); + } +} diff --git a/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseResponseWire.java b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseResponseWire.java new file mode 100644 index 0000000..26f0e7f --- /dev/null +++ b/src/main/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseResponseWire.java @@ -0,0 +1,199 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import org.unicitylabs.sdk.serializer.cbor.CborDeserializer; +import org.unicitylabs.sdk.serializer.cbor.CborSerializationException; +import org.unicitylabs.sdk.serializer.cbor.CborSerializer; +import org.unicitylabs.sdk.util.UnsignedLongs; + +/** + * The envelope of a GetTrustBase response (and of a release bundle, which is the same object): + * {@code [1, network, status, fromEpoch, effectiveEnd, endEntryId|null, [entry...], + * nextEpoch|null]} under tag 39015, the entries embedded verbatim. Only the envelope is checked + * here; each user of the response applies its own rules to the contents. + */ +public final class TrustBaseResponseWire { + + /** CBOR tag of the response. */ + public static final long RESPONSE_TAG = 39015L; + /** Version of the response. */ + public static final long RESPONSE_VERSION = 1L; + /** Number of defined response statuses. */ + public static final long STATUS_COUNT = 8L; + /** Status of a response that carries entries. */ + public static final long STATUS_OK = 0L; + + private static final int FIELD_COUNT = 8; + + private TrustBaseResponseWire() { + } + + /** The fields of a response. Epochs, rounds and the status are unsigned bits. */ + public static final class Fields { + + private final long effectiveEnd; + private final byte[] endEntryId; + private final List entries; + private final long fromEpoch; + private final int network; + private final Long nextEpoch; + private final long status; + + /** + * Create the fields. + * + * @param effectiveEnd last epoch of the range, unsigned + * @param endEntryId id of the last entry, or null (copied) + * @param entries complete tagged entries (copied) + * @param fromEpoch first epoch of the range, unsigned + * @param network network id, 0 to 65535 + * @param nextEpoch continuation cursor, or null + * @param status response status, 0 to 7 + */ + public Fields(long effectiveEnd, byte[] endEntryId, List entries, long fromEpoch, + int network, Long nextEpoch, long status) { + this.effectiveEnd = effectiveEnd; + this.endEntryId = endEntryId == null ? null : Arrays.copyOf(endEntryId, endEntryId.length); + List copy = new ArrayList<>(entries.size()); + for (byte[] entry : entries) { + copy.add(Arrays.copyOf(entry, entry.length)); + } + this.entries = copy; + this.fromEpoch = fromEpoch; + this.network = network; + this.nextEpoch = nextEpoch; + this.status = status; + } + + /** Get the last epoch of the range, unsigned bits. */ + public long getEffectiveEnd() { + return this.effectiveEnd; + } + + /** Get the end entry id, or null (copy). */ + public byte[] getEndEntryId() { + return this.endEntryId == null ? null + : Arrays.copyOf(this.endEntryId, this.endEntryId.length); + } + + /** Get the embedded entries (copies). */ + public List getEntries() { + List copy = new ArrayList<>(this.entries.size()); + for (byte[] entry : this.entries) { + copy.add(Arrays.copyOf(entry, entry.length)); + } + return copy; + } + + /** Get the first epoch of the range, unsigned bits. */ + public long getFromEpoch() { + return this.fromEpoch; + } + + /** Get the network id of the header. */ + public int getNetwork() { + return this.network; + } + + /** Get the continuation cursor, or null. */ + public Long getNextEpoch() { + return this.nextEpoch; + } + + /** Get the status, unsigned bits. */ + public long getStatus() { + return this.status; + } + } + + /** + * Parse the envelope of a tagged response. + * + * @param bytes tagged response + * @param maxEntries most entries accepted, checked from the array header before any entry is read + * @return the fields + * @throws TrustBaseEncodingException if the bytes are not the deterministic envelope or exceed + * the entry budget + */ + public static Fields parse(byte[] bytes, int maxEntries) { + Objects.requireNonNull(bytes, "bytes cannot be null"); + try { + CborDeserializer.CborTag tagged = CborDeserializer.decodeTag(bytes); + if (tagged.getTag() != RESPONSE_TAG) { + throw new TrustBaseEncodingException( + "Tag " + Long.toUnsignedString(tagged.getTag()) + ", expected " + RESPONSE_TAG + "."); + } + + List fields = CborDeserializer.decodeArrayAtMost(tagged.getData(), FIELD_COUNT); + if (fields.size() != FIELD_COUNT) { + throw new TrustBaseEncodingException( + "Expected " + FIELD_COUNT + " fields, got " + fields.size() + "."); + } + + long version = uint(fields.get(0)); + if (version != RESPONSE_VERSION) { + throw new TrustBaseEncodingException( + "Version " + Long.toUnsignedString(version) + ", expected " + RESPONSE_VERSION + "."); + } + long network = uint(fields.get(1)); + // A header network of 0 is not refused here: no entry has network 0, so the entries cannot + // match it and the response is refused as such by its user. + if (UnsignedLongs.compare(network, 0xFFFFL) > 0) { + throw new TrustBaseEncodingException( + "Network identifier " + Long.toUnsignedString(network) + " above 65535."); + } + long status = uint(fields.get(2)); + if (UnsignedLongs.compare(status, STATUS_COUNT) >= 0) { + throw new TrustBaseEncodingException( + "Status " + Long.toUnsignedString(status) + " is not defined."); + } + byte[] endEntryId = CborDeserializer.decodeNullable(fields.get(5), + CborDeserializer::decodeByteString); + if (endEntryId != null && endEntryId.length != TrustBaseEntry.ID_LENGTH) { + throw new TrustBaseEncodingException("End id of " + endEntryId.length + " bytes."); + } + List entries; + try { + entries = CborDeserializer.decodeArrayAtMost(fields.get(6), maxEntries); + } catch (CborSerializationException e) { + if (e.getMessage() != null && e.getMessage().startsWith("Array of more than")) { + throw new TrustBaseEncodingException("More than " + maxEntries + " entries."); + } + throw e; + } + Long nextEpoch = CborDeserializer.decodeNullable(fields.get(7), TrustBaseResponseWire::uint); + return new Fields(uint(fields.get(4)), endEntryId, entries, uint(fields.get(3)), + (int) network, nextEpoch, status); + } catch (TrustBaseEncodingException e) { + throw e; + } catch (RuntimeException e) { + throw new TrustBaseEncodingException(String.valueOf(e.getMessage())); + } + } + + private static long uint(byte[] data) { + return CborDeserializer.decodeUnsignedInteger(data).asLong(); + } + + /** + * Encode a response, the entries embedded verbatim: the inverse of {@link #parse}. + * + * @param fields the fields; entries are complete tagged entries + * @return tagged response + */ + public static byte[] encode(Fields fields) { + byte[][] entries = fields.entries.toArray(new byte[0][]); + return CborSerializer.encodeTag(RESPONSE_TAG, CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(RESPONSE_VERSION), + CborSerializer.encodeUnsignedInteger(fields.network), + CborSerializer.encodeUnsignedInteger(fields.status), + CborSerializer.encodeUnsignedInteger(fields.fromEpoch), + CborSerializer.encodeUnsignedInteger(fields.effectiveEnd), + CborSerializer.encodeNullable(fields.endEntryId, CborSerializer::encodeByteString), + CborSerializer.encodeArray(entries), + CborSerializer.encodeNullable(fields.nextEpoch, CborSerializer::encodeUnsignedInteger))); + } +} diff --git a/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleTest.java b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleTest.java new file mode 100644 index 0000000..6df8b37 --- /dev/null +++ b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseBundleTest.java @@ -0,0 +1,160 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.unicitylabs.sdk.api.bft.trustbase.TrustBaseResponseWire.Fields; +import org.unicitylabs.sdk.api.bft.trustbase.TrustBaseTestChain.Committee; +import org.unicitylabs.sdk.serializer.cbor.CborSerializer; + +/** The complete-bundle decoder and encoder, one refusal at a time. */ +class TrustBaseBundleTest { + + private static final TrustBaseBundleLimits LIMITS = new TrustBaseBundleLimits(1 << 20, 64); + + private final Committee c1 = new Committee(4, 1, 1); + private final Committee c2 = new Committee(4, 1, 2); + private final TrustBaseEntry g = TrustBaseTestChain.genesis(5, 1, 1, c1); + private final TrustBaseEntry e2 = + TrustBaseTestChain.successor(g, c1, c2, 10, TrustBaseTestChain.firstN(c1, 3)); + + private Fields fields(long status, Long next, byte[] end, long from, long effectiveEnd, + int network, TrustBaseEntry... entries) { + List raw = new ArrayList<>(); + for (TrustBaseEntry entry : entries) { + raw.add(entry.encode()); + } + return new Fields(effectiveEnd, end, raw, from, network, next, status); + } + + private Fields good() { + return fields(0, null, e2.entryId(), 1, 2, 5, g, e2); + } + + private static Fields with(Fields f, Long next, long status, byte[] end, long from, long effective, + int network) { + return new Fields(effective, end, f.getEntries(), from, network, next, status); + } + + private static TrustBaseBundleException refused(Fields f) { + return assertThrows(TrustBaseBundleException.class, + () -> TrustBaseBundle.decode(TrustBaseResponseWire.encode(f), LIMITS)); + } + + @Test + void aGoodBundleRoundTripsAndKeepsTheCanonicalBytesOfEachEntry() { + byte[] bytes = TrustBaseResponseWire.encode(good()); + TrustBaseBundle bundle = TrustBaseBundle.decode(bytes, LIMITS); + assertEquals(5, bundle.getNetworkId().getId()); + assertEquals(2, bundle.getEntries().size()); + assertArrayEquals(e2.encode(), bundle.getRaw().get(1)); + assertArrayEquals(bytes, TrustBaseBundle.encode(bundle.getEntries())); + assertArrayEquals(e2.entryId(), bundle.getTip().entryId()); + } + + @Test + void aOneEntryBundleHoldsAGenesisOnly() { + byte[] one = TrustBaseBundle.encode(List.of(g)); + assertEquals(1, TrustBaseBundle.decode(one, LIMITS).getEntries().size()); + byte[] partial = TrustBaseResponseWire.encode(fields(0, null, e2.entryId(), 2, 2, 5, e2)); + assertThrows(TrustBaseBundleException.class, () -> TrustBaseBundle.decode(partial, LIMITS)); + } + + @Test + void aStatusThatIsNotOkOrACursorOrNoEntriesOrNoEndIdIsRefused() { + Fields f = good(); + assertTrue(refused(with(f, null, 1, e2.entryId(), 1, 2, 5)).getMessage().contains("Status 1")); + assertTrue(refused(with(f, 3L, 0, e2.entryId(), 1, 2, 5)).getMessage().contains("cursor")); + assertTrue(refused(new Fields(2, e2.entryId(), List.of(), 1, 5, null, 0)).getMessage() + .contains("without entries")); + assertTrue(refused(with(f, null, 0, null, 1, 2, 5)).getMessage().contains("No end entry id")); + } + + @Test + void aWrongNetworkRangeOrEndIsRefused() { + Fields f = good(); + assertTrue(refused(with(f, null, 0, e2.entryId(), 1, 2, 6)).getMessage().contains("network")); + assertTrue(refused(with(f, null, 0, e2.entryId(), 2, 2, 5)).getMessage().contains("starts at")); + assertTrue(refused(with(f, null, 0, e2.entryId(), 1, 3, 5)).getMessage().contains("ends at")); + assertTrue(refused(with(f, null, 0, g.entryId(), 1, 2, 5)).getMessage().contains("end entry id")); + } + + @Test + void entriesThatSkipAnEpochOrDoNotLinkAreRefused() { + Committee c3 = new Committee(4, 1, 3); + TrustBaseEntry e3 = TrustBaseTestChain.successor(e2, c2, c3, 20, TrustBaseTestChain.firstN(c2, 3)); + assertTrue(refused(fields(0, null, e3.entryId(), 1, 3, 5, g, e3)).getMessage().contains("does not follow")); + TrustBaseEntry stranger = TrustBaseTestChain.successor( + TrustBaseTestChain.genesis(5, 1, 2, c2), c2, c3, 20, TrustBaseTestChain.firstN(c2, 3)); + assertTrue(refused(fields(0, null, stranger.entryId(), 1, 2, 5, g, stranger)).getMessage() + .contains("does not link")); + } + + @Test + void theBudgetsAreCheckedBeforeAnythingIsRead() { + byte[] bytes = TrustBaseResponseWire.encode(good()); + assertThrows(TrustBaseEncodingException.class, + () -> TrustBaseBundle.decode(bytes, new TrustBaseBundleLimits(bytes.length - 1, 64))); + TrustBaseEncodingException count = assertThrows(TrustBaseEncodingException.class, + () -> TrustBaseBundle.decode(bytes, new TrustBaseBundleLimits(1 << 20, 1))); + assertTrue(count.getMessage().contains("entries"), count.getMessage()); + assertThrows(TrustBaseEncodingException.class, + () -> TrustBaseBundle.decode(bytes, new TrustBaseBundleLimits(1 << 20, 64, e2.encode().length - 1))); + TrustBaseBundle.decode(bytes, new TrustBaseBundleLimits(bytes.length, 2, e2.encode().length)); + } + + private static byte[] envelopeWithEntries(byte[] entryArray) { + return CborSerializer.encodeTag(TrustBaseResponseWire.RESPONSE_TAG, + CborSerializer.encodeArray(CborSerializer.encodeUnsignedInteger(1), + CborSerializer.encodeUnsignedInteger(5), CborSerializer.encodeUnsignedInteger(0), + CborSerializer.encodeUnsignedInteger(1), CborSerializer.encodeUnsignedInteger(1), + CborSerializer.encodeNull(), entryArray, CborSerializer.encodeNull())); + } + + @Test + void moreEntriesThanTheBudgetAreRefusedFromTheArrayHeader() { + byte[][] hundred = new byte[100][]; + Arrays.fill(hundred, CborSerializer.encodeNull()); + byte[] bytes = envelopeWithEntries(CborSerializer.encodeArray(hundred)); + TrustBaseEncodingException e = assertThrows(TrustBaseEncodingException.class, + () -> TrustBaseBundle.decode(bytes, LIMITS)); + assertEquals("More than 64 entries.", e.getMessage()); + } + + @Test + void anEntryCountHeaderOfFourBillionIsRefusedAsAnEncodingError() { + byte[] hugeArray = {(byte) 0x9a, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; + byte[] bytes = envelopeWithEntries(hugeArray); + assertThrows(TrustBaseEncodingException.class, () -> TrustBaseBundle.decode(bytes, LIMITS)); + } + + @Test + void theEnvelopeIsStrict() { + byte[] good = TrustBaseResponseWire.encode(good()); + byte[] trailing = Arrays.copyOf(good, good.length + 1); + assertThrows(TrustBaseEncodingException.class, () -> TrustBaseBundle.decode(trailing, LIMITS)); + byte[] wrongTag = CborSerializer.encodeTag(39016L, CborSerializer.encodeArray()); + assertThrows(TrustBaseEncodingException.class, () -> TrustBaseBundle.decode(wrongTag, LIMITS)); + // status 8 is undefined, a network above 65535 is a bad encoding + byte[] status8 = TrustBaseResponseWire.encode(with(good(), null, 8, e2.entryId(), 1, 2, 5)); + assertThrows(TrustBaseEncodingException.class, () -> TrustBaseBundle.decode(status8, LIMITS)); + byte[] shortEnd = TrustBaseResponseWire.encode(with(good(), null, 0, new byte[31], 1, 2, 5)); + assertThrows(TrustBaseEncodingException.class, () -> TrustBaseBundle.decode(shortEnd, LIMITS)); + } + + @Test + void encodeRefusesEmptyUnlinkedOrMixedNetworkChains() { + assertThrows(TrustBaseBundleException.class, () -> TrustBaseBundle.encode(List.of())); + assertThrows(TrustBaseBundleException.class, () -> TrustBaseBundle.encode(List.of(e2))); + TrustBaseEntry other = TrustBaseTestChain.successor(TrustBaseTestChain.genesis(5, 1, 2, c2), c2, c1, + 10, TrustBaseTestChain.firstN(c2, 3)); + assertThrows(TrustBaseBundleException.class, () -> TrustBaseBundle.encode(List.of(g, other))); + assertThrows(TrustBaseBundleException.class, () -> TrustBaseBundle.encode(List.of(g, g))); + } +} diff --git a/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryRulesTest.java b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryRulesTest.java new file mode 100644 index 0000000..08614c6 --- /dev/null +++ b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryRulesTest.java @@ -0,0 +1,313 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; +import org.unicitylabs.sdk.api.bft.trustbase.TrustBaseTestChain.Committee; +import org.unicitylabs.sdk.util.HexConverter; + +/** History rules one at a time, weighted quorums, 256 to 4, the maximum entry, concurrency. */ +class TrustBaseHistoryRulesTest { + + private static final JsonNode MAX = TrustBaseVectors.maxEntry(); + private static final TrustBaseBundleLimits LIMITS = new TrustBaseBundleLimits(1 << 20, 64); + + private final Committee c1 = new Committee(4, 1, 1); + private final Committee c2 = new Committee(4, 1, 2); + private final Committee c3 = new Committee(4, 1, 3); + private final TrustBaseEntry g = TrustBaseTestChain.genesis(5, 1, 1, c1); + private final TrustBaseEntry e2 = + TrustBaseTestChain.successor(g, c1, c2, 10, TrustBaseTestChain.firstN(c1, 3)); + private final TrustBaseEntry e3 = + TrustBaseTestChain.successor(e2, c2, c3, 20, TrustBaseTestChain.firstN(c2, 3)); + + private TrustBaseHistory pinned() { + TrustBaseHistory history = TrustBaseHistory.create(g.entryId()); + history.append(g); + return history; + } + + @Test + void startsEmptyAndAcceptsThePinnedGenesisOnly() { + TrustBaseHistory history = TrustBaseHistory.create(g.entryId()); + assertTrue(history.isEmpty()); + assertFalse(history.getTip().isPresent()); + assertFalse(history.getNetworkId().isPresent()); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(g)); + assertFalse(history.isEmpty()); + assertEquals(1, history.getTip().get().getEpoch()); + assertEquals(5, history.getNetworkId().get().getId()); + } + + @Test + void keepsItsOwnCopyOfThePinAndAnswersACopy() { + byte[] pin = g.entryId(); + TrustBaseHistory history = TrustBaseHistory.create(pin); + java.util.Arrays.fill(pin, (byte) 0); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(g)); + byte[] answered = history.getGenesisPin(); + java.util.Arrays.fill(answered, (byte) 0); + assertArrayEquals(g.entryId(), history.getGenesisPin()); + } + + @Test + void refusesAGenesisThatIsNotThePinnedIdentityAndAPinThatIsNot32Bytes() { + TrustBaseHistory history = TrustBaseHistory.create(new byte[32]); + TrustBaseChainException e = assertThrows(TrustBaseChainException.class, () -> history.append(g)); + assertTrue(e.getMessage().contains("not the pinned identity")); + assertTrue(history.isEmpty()); + assertThrows(TrustBaseInvalidException.class, () -> TrustBaseHistory.create(new byte[31])); + } + + @Test + void refusesAFirstEntryThatIsNotAGenesisWhateverThePin() { + TrustBaseHistory history = TrustBaseHistory.create(e2.entryId()); + assertThrows(TrustBaseInvalidException.class, () -> history.append(e2)); + } + + @Test + void appendsConsecutiveEntriesAndReSentOnesAreAlreadyHeld() { + TrustBaseHistory history = pinned(); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(e2)); + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(e2)); + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(g)); + TrustBaseEntry otherQuorum = + TrustBaseTestChain.successor(g, c1, c2, 10, List.of("m0001", "m0002", "m0003")); + assertArrayEquals(e2.entryId(), otherQuorum.entryId()); + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(otherQuorum)); + assertEquals(2, history.getEntries().size()); + } + + @Test + void aBadWitnessForAHeldEpochIsAnErrorNotAnAlreadyHeld() { + TrustBaseHistory history = pinned(); + history.append(e2); + TrustBaseEntry badWitness = + TrustBaseTestChain.successor(g, c1, c2, 10, TrustBaseTestChain.firstN(c1, 2)); + assertThrows(TrustBaseSignatureException.class, () -> history.append(badWitness)); + } + + @Test + void aGapIsReportedWithBothEpochsAndAppendsNothing() { + TrustBaseHistory history = pinned(); + TrustBaseGapException gap = assertThrows(TrustBaseGapException.class, () -> history.append(e3)); + assertEquals(3, gap.getEpoch()); + assertEquals(1, gap.getTipEpoch()); + assertEquals(1, history.getEntries().size()); + } + + @Test + void aDifferentEntryForAHeldEpochIsAConflictWithBothIdsAndNothingChanges() { + TrustBaseHistory history = pinned(); + history.append(e2); + Committee other = new Committee(4, 1, 9); + TrustBaseEntry fork = TrustBaseTestChain.successor(g, c1, other, 10, TrustBaseTestChain.firstN(c1, 3)); + TrustBaseConflictException e = + assertThrows(TrustBaseConflictException.class, () -> history.append(fork)); + assertEquals(2, e.getEpoch()); + assertFalse(e.isAuthenticated()); + assertArrayEquals(e2.entryId(), e.getDetails().getHeldEntryId()); + assertArrayEquals(fork.entryId(), e.getDetails().getOfferedEntryId()); + assertEquals(2, history.getEntries().size()); + assertArrayEquals(e2.entryId(), history.getTip().get().entryId()); + } + + @Test + void anEntryBeforeTheGenesisEpochIsRefusedAsSuch() { + TrustBaseEntry late = TrustBaseTestChain.genesis(5, 4, 100, c1); + TrustBaseHistory history = TrustBaseHistory.create(late.entryId()); + history.append(late); + TrustBaseEntry early = TrustBaseTestChain.genesis(5, 2, 50, c2); + assertThrows(TrustBaseBeforeGenesisException.class, () -> history.append(early)); + } + + @Test + void aSuccessorWithAWrongPredecessorOrNetworkOrStartRoundIsAChainError() { + TrustBaseHistory history = pinned(); + // predecessor link of another chain + TrustBaseEntry elsewhere = TrustBaseTestChain.successor(TrustBaseTestChain.genesis(5, 1, 2, c3), + c3, c2, 10, TrustBaseTestChain.firstN(c3, 3)); + assertThrows(TrustBaseChainException.class, () -> history.append(elsewhere)); + // a start round that does not advance + TrustBaseEntry flat = TrustBaseTestChain.successor(g, c1, c2, 1, TrustBaseTestChain.firstN(c1, 3)); + assertThrows(TrustBaseChainException.class, () -> history.append(flat)); + // another network + TrustBaseEntry g6 = TrustBaseTestChain.genesis(6, 1, 1, c1); + TrustBaseEntry n6 = TrustBaseTestChain.successor(g6, c1, c2, 10, TrustBaseTestChain.firstN(c1, 3)); + assertThrows(TrustBaseChainException.class, () -> history.append(n6)); + assertEquals(1, history.getEntries().size()); + } + + @Test + void aStartRoundAbove2To63OrdersAsUnsignedAndEpochsCountAsUnsigned() { + long high = Long.MIN_VALUE + 5; // 2^63 + 5 + TrustBaseEntry e = TrustBaseTestChain.successor(g, c1, c2, high, TrustBaseTestChain.firstN(c1, 3)); + TrustBaseHistory history = pinned(); + history.append(e); + TrustBaseEntry next = TrustBaseTestChain.successor(e, c2, c3, -1L, TrustBaseTestChain.firstN(c2, 3)); + history.append(next); + // a round that would be larger signed but is smaller unsigned + TrustBaseEntry back = TrustBaseTestChain.successor(next, c3, c1, 7, TrustBaseTestChain.firstN(c3, 3)); + assertThrows(TrustBaseChainException.class, () -> history.append(back)); + assertEquals(high, history.epochEndRound(1).getAsLong()); + } + + @Test + void epochsCrossingTwoToThe63CountAsUnsigned() { + TrustBaseEntry high = TrustBaseTestChain.genesis(5, Long.MAX_VALUE, 1, c1); + TrustBaseHistory history = TrustBaseHistory.create(high.entryId()); + history.append(high); + TrustBaseEntry next = TrustBaseTestChain.successor(high, c1, c2, 10, TrustBaseTestChain.firstN(c1, 3)); + assertEquals(Long.MIN_VALUE, next.getEpoch()); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(next)); + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(next)); + assertTrue(history.entryForEpoch(Long.MIN_VALUE).isPresent()); + assertEquals(10, history.epochEndRound(Long.MAX_VALUE).getAsLong()); + // two epochs ahead is a gap, not "an older entry" + TrustBaseEntry far = TrustBaseTestChain.successor(next, c2, c3, 20, TrustBaseTestChain.firstN(c2, 3)); + TrustBaseHistory fresh = TrustBaseHistory.create(high.entryId()); + fresh.append(high); + assertThrows(TrustBaseGapException.class, () -> fresh.append(far)); + } + + @Test + void entryForEpochAndEpochEndRound() { + TrustBaseHistory history = pinned(); + history.append(e2); + assertFalse(history.entryForEpoch(0).isPresent()); + assertTrue(history.entryForEpoch(1).isPresent()); + assertTrue(history.entryForEpoch(2).isPresent()); + assertFalse(history.entryForEpoch(3).isPresent()); + assertFalse(history.entryForEpoch(-1L).isPresent()); + assertEquals(10, history.epochEndRound(1).getAsLong()); + assertFalse(history.epochEndRound(2).isPresent()); + assertFalse(history.epochEndRound(-1L).isPresent()); + } + + @Test + void aWeightedQuorumNeedsMoreThanTwoThirdsOfTheWeightNotOfTheSigners() { + // weights 5,1,1,1: a alone is 5 of 6 needed, a+b is 6 + List members = new ArrayList<>(); + Committee base = new Committee(4, 1, 4); + long[] weights = {5, 1, 1, 1}; + for (int i = 0; i < 4; i++) { + TrustBaseMember m = base.members.get(i); + members.add(new TrustBaseMember(m.getNodeId(), m.getSigKey(), weights[i])); + } + TrustBaseEntry heavy = new TrustBaseEntry(5, 1, 1, members, 6, null, null, new byte[32], null); + heavy.validate(); + TrustBaseHistory history = TrustBaseHistory.create(heavy.entryId()); + history.append(heavy); + for (List signers : List.of(List.of("m0000"), List.of("m0001", "m0002", "m0003"))) { + TrustBaseEntry below = successorOf(heavy, base, signers); + assertThrows(TrustBaseSignatureException.class, () -> history.append(below)); + } + history.append(successorOf(heavy, base, List.of("m0000", "m0001"))); + } + + private TrustBaseEntry successorOf(TrustBaseEntry previous, Committee signing, List signers) { + return TrustBaseTestChain.successor(previous, signing, c2, 10, signers); + } + + @Test + void overlapOfTwoSignerSetsIsEnoughTheSameEntryIsHeldOnce() { + Committee big = new Committee(256, 1, 5); + TrustBaseEntry big1 = TrustBaseTestChain.genesis(5, 1, 1, big); + assertEquals(171, big1.getQuorumThreshold()); + TrustBaseHistory history = TrustBaseHistory.create(big1.entryId()); + history.append(big1); + TrustBaseEntry exact = TrustBaseTestChain.successor(big1, big, c2, 10, TrustBaseTestChain.firstN(big, 171)); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(exact)); + List tail = new ArrayList<>(big.secrets.keySet()).subList(85, 256); + TrustBaseEntry overlap = TrustBaseTestChain.successor(big1, big, c2, 10, tail); + assertEquals(171, tail.size()); + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(overlap)); + TrustBaseEntry short1 = TrustBaseTestChain.successor(big1, big, c2, 10, TrustBaseTestChain.firstN(big, 170)); + assertThrows(TrustBaseSignatureException.class, () -> new TrustBaseHistoryProbe(big1).append(short1)); + } + + /** A fresh history holding only the genesis. */ + private static final class TrustBaseHistoryProbe { + + private final TrustBaseHistory history; + + TrustBaseHistoryProbe(TrustBaseEntry genesis) { + this.history = TrustBaseHistory.create(genesis.entryId()); + this.history.append(genesis); + } + + void append(TrustBaseEntry entry) { + this.history.append(entry); + } + } + + @Test + void a256MemberCommitteeHandsOverToFourMembersWith256PredecessorSignatures() { + Committee big = new Committee(256, 1, 6); + TrustBaseEntry big1 = TrustBaseTestChain.genesis(5, 1, 1, big); + Committee four = new Committee(4, 1, 7); + TrustBaseEntry small = TrustBaseTestChain.successor(big1, big, four, 10, new ArrayList<>(big.secrets.keySet())); + assertEquals(256, small.getSignatures().size()); + assertEquals(4, small.getMembers().size()); + TrustBaseEntry decoded = TrustBaseEntry.decode(small.encode()); + TrustBaseHistory history = TrustBaseHistory.create(big1.entryId()); + history.append(big1); + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(decoded)); + assertEquals(4, history.getTip().get().getMembers().size()); + } + + @Test + void theMaximumEntryBundleDecodesAndInstallsFromItsPin() { + byte[] bytes = HexConverter.decode(MAX.get("bundle").asText()); + TrustBaseBundle bundle = TrustBaseBundle.decode(bytes, LIMITS); + assertEquals(2, bundle.getEntries().size()); + assertEquals(MAX.get("genesisId").asText(), HexConverter.encode(bundle.getEntries().get(0).entryId())); + assertEquals(MAX.get("entryId").asText(), HexConverter.encode(bundle.getTip().entryId())); + TrustBaseHistory history = + TrustBaseHistory.fromBundle(bundle, HexConverter.decode(MAX.get("genesisId").asText())); + assertEquals(2, history.getEntries().size()); + assertArrayEquals(bytes, history.toBundle()); + assertEquals(MAX.get("members").asInt(), bundle.getEntries().get(0).getMembers().size()); + } + + @Test + void concurrentAppendersSeeOneConsistentChain() throws Exception { + TrustBaseHistory history = pinned(); + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + List> tasks = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + final int n = i; + tasks.add(() -> { + try { + return history.append(n % 2 == 0 ? e2 : e3); + } catch (TrustBaseGapException e) { + return e; + } + }); + } + for (Future f : pool.invokeAll(tasks)) { + f.get(); + } + } finally { + pool.shutdownNow(); + } + List held = history.getEntries(); + assertTrue(held.size() == 2 || held.size() == 3); + for (int i = 1; i < held.size(); i++) { + assertArrayEquals(held.get(i - 1).entryId(), held.get(i).getPreviousEntryId()); + } + assertEquals(1, held.stream().filter(e -> e.getEpoch() == 2).count()); + } +} diff --git a/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryVectorsTest.java b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryVectorsTest.java new file mode 100644 index 0000000..9de0221 --- /dev/null +++ b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseHistoryVectorsTest.java @@ -0,0 +1,130 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.unicitylabs.sdk.util.HexConverter; + +/** The shared bft-go-base history, weighted-quorum and bundle vectors. */ +class TrustBaseHistoryVectorsTest { + + private static final JsonNode VECTORS = TrustBaseVectors.shared(); + private static final TrustBaseBundleLimits LIMITS = new TrustBaseBundleLimits(1 << 20, 64); + + private static final Map> OUTCOME_ERRORS = Map.of( + "conflict", TrustBaseConflictException.class, + "error:chain", TrustBaseChainException.class, + "error:invalid", TrustBaseInvalidException.class, + "error:signature", TrustBaseSignatureException.class, + "gap", TrustBaseGapException.class); + + private static TrustBaseEntry entry(String hex) { + return TrustBaseEntry.decode(HexConverter.decode(hex)); + } + + private static TrustBaseEntry named(String name) { + for (JsonNode vector : VECTORS.get("entries")) { + if (vector.get("name").asText().equals(name)) { + return entry(vector.get("hex").asText()); + } + } + throw new AssertionError(name); + } + + @Test + void everyHistoryVectorHasTheSharedOutcomeAndTheSharedFinalChain() { + int seen = 0; + for (JsonNode vector : VECTORS.get("history")) { + String name = vector.get("name").asText(); + JsonNode steps = vector.get("steps"); + // the reference pins nothing; the first entry of every vector is the genesis, so its id is the pin + TrustBaseHistory history = TrustBaseHistory.create(entry(steps.get(0).get("entry").asText()).entryId()); + for (JsonNode step : steps) { + TrustBaseEntry candidate = entry(step.get("entry").asText()); + String outcome = step.get("outcome").asText(); + if (outcome.equals("appended")) { + assertEquals(TrustBaseAppendOutcome.APPENDED, history.append(candidate), name); + } else if (outcome.equals("noop")) { + assertEquals(TrustBaseAppendOutcome.ALREADY_HELD, history.append(candidate), name); + } else { + assertThrows(OUTCOME_ERRORS.get(outcome), () -> history.append(candidate), name); + } + } + List held = new ArrayList<>(); + for (TrustBaseEntry e : history.getEntries()) { + held.add(HexConverter.encode(e.entryId())); + } + List expected = new ArrayList<>(); + JsonNode finalIds = vector.get("finalEntryIds"); + if (finalIds != null && !finalIds.isNull()) { + finalIds.forEach(id -> expected.add(id.asText())); + } + assertEquals(expected, held, name); + seen++; + } + assertEquals(11, seen); + } + + @Test + void everyWeightedQuorumVectorHasTheSharedVerdict() { + int seen = 0; + for (JsonNode vector : VECTORS.get("weightedQuorum")) { + String name = vector.get("name").asText(); + TrustBaseEntry committee = named(vector.get("committee").asText()); + TrustBaseEntry successor = entry(vector.get("entry").asText()); + Map signatures = successor.getSignatures(); + List signers = new ArrayList<>(signatures.keySet()); + List expectedSigners = new ArrayList<>(); + vector.get("signers").forEach(s -> expectedSigners.add(s.asText())); + assertEquals(expectedSigners, signers, name); + + long signed = 0; + for (Map.Entry signature : signatures.entrySet()) { + signed += committee.verifySignature(successor.sigBytes(), signature.getValue(), + signature.getKey()); + } + assertEquals(vector.get("signedWeight").asLong(), signed, name); + assertEquals(vector.get("threshold").asLong(), committee.getQuorumThreshold(), name); + + if (vector.get("valid").asBoolean()) { + committee.verifyQuorumSignatures(successor.sigBytes(), signatures); + } else { + assertThrows(TrustBaseSignatureException.class, + () -> committee.verifyQuorumSignatures(successor.sigBytes(), signatures), name); + } + seen++; + } + assertEquals(4, seen); + } + + @Test + void theSharedBundlesDecodeReEncodeAndInstallThroughAppend() { + int seen = 0; + for (JsonNode vector : VECTORS.get("bundles")) { + String name = vector.get("name").asText(); + byte[] bytes = HexConverter.decode(vector.get("hex").asText()); + TrustBaseBundle bundle = TrustBaseBundle.decode(bytes, LIMITS); + List ids = new ArrayList<>(); + for (TrustBaseEntry e : bundle.getEntries()) { + ids.add(HexConverter.encode(e.entryId())); + } + List expected = new ArrayList<>(); + vector.get("entryIds").forEach(id -> expected.add(id.asText())); + assertEquals(expected, ids, name); + assertArrayEquals(bytes, TrustBaseBundle.encode(bundle.getEntries()), name); + + TrustBaseHistory history = + TrustBaseHistory.fromBundle(bundle, bundle.getEntries().get(0).entryId()); + assertEquals(bundle.getEntries().size(), history.getEntries().size(), name); + assertArrayEquals(bytes, history.toBundle(), name); + seen++; + } + assertEquals(2, seen); + } +} diff --git a/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseTestChain.java b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseTestChain.java new file mode 100644 index 0000000..fed3c57 --- /dev/null +++ b/src/test/java/org/unicitylabs/sdk/api/bft/trustbase/TrustBaseTestChain.java @@ -0,0 +1,90 @@ +package org.unicitylabs.sdk.api.bft.trustbase; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.unicitylabs.sdk.crypto.hash.DataHash; +import org.unicitylabs.sdk.crypto.hash.DataHasher; +import org.unicitylabs.sdk.crypto.hash.HashAlgorithm; +import org.unicitylabs.sdk.crypto.secp256k1.SigningService; + +/** Builds signed synthetic trust-base chains with known test keys. Test keys only. */ +final class TrustBaseTestChain { + + /** A committee with known secrets. */ + static final class Committee { + + final Map secrets = new LinkedHashMap<>(); + final List members = new ArrayList<>(); + + /** Members "m0000".."m(n-1)" with the given weight each, keys from {@code salt}. */ + Committee(int count, long weight, int salt) { + for (int i = 0; i < count; i++) { + String id = String.format("m%04d", i); + byte[] secret = secret(salt, i); + secrets.put(id, secret); + members.add(new TrustBaseMember(id, new SigningService(secret).getPublicKey(), weight)); + } + } + + long totalWeight() { + long total = 0; + for (TrustBaseMember member : members) { + total += member.getWeight(); + } + return total; + } + + long threshold() { + return totalWeight() * 2 / 3 + 1; + } + } + + private TrustBaseTestChain() { + } + + static byte[] secret(int salt, int i) { + byte[] secret = new byte[32]; + secret[28] = (byte) salt; + secret[30] = (byte) ((i + 1) >> 8); + secret[31] = (byte) (i + 1); + return secret; + } + + static TrustBaseEntry genesis(int network, long epoch, long startRound, Committee committee) { + return new TrustBaseEntry(network, epoch, startRound, committee.members, committee.threshold(), + null, null, new byte[32], null); + } + + static byte[] sign(byte[] secret, byte[] data) { + DataHash hash = new DataHasher(HashAlgorithm.SHA256).update(data).digest(); + return new SigningService(secret).sign(hash).encode(); + } + + /** A successor of {@code previous} signed by the named members of {@code signing}. */ + static TrustBaseEntry successor(TrustBaseEntry previous, Committee signing, Committee next, + long startRound, Collection signers) { + return successor(previous, signing, next.members, next.threshold(), startRound, signers); + } + + static TrustBaseEntry successor(TrustBaseEntry previous, Committee signing, + List members, long threshold, long startRound, Collection signers) { + Map placeholder = Map.of("x", new byte[65]); + TrustBaseEntry unsigned = new TrustBaseEntry(previous.getNetworkId().getId(), + previous.getEpoch() + 1, startRound, members, threshold, null, null, previous.entryId(), + placeholder); + byte[] data = unsigned.sigBytes(); + Map signatures = new LinkedHashMap<>(); + for (String signer : signers) { + signatures.put(signer, sign(signing.secrets.get(signer), data)); + } + return new TrustBaseEntry(previous.getNetworkId().getId(), previous.getEpoch() + 1, startRound, + members, threshold, null, null, previous.entryId(), signatures); + } + + static List firstN(Committee committee, int n) { + return new ArrayList<>(committee.secrets.keySet()).subList(0, n); + } +}