├── .gitignore ├── .travis.yml ├── src ├── main │ └── java │ │ └── at │ │ └── archistar │ │ └── bft │ │ ├── exceptions │ │ └── InconsistentResultsException.java │ │ ├── messages │ │ ├── AbstractCommand.java │ │ ├── CommitCommand.java │ │ ├── AdvanceEraCommand.java │ │ ├── ClientFragmentCommand.java │ │ ├── PrepareCommand.java │ │ ├── IntraReplicaCommand.java │ │ ├── PreprepareCommand.java │ │ ├── ClientCommand.java │ │ ├── TransactionResult.java │ │ └── CheckpointMessage.java │ │ ├── helper │ │ └── DigestHelper.java │ │ ├── server │ │ ├── BftEngineCallbacks.java │ │ ├── BftEngine.java │ │ ├── CheckpointManager.java │ │ ├── TransactionManager.java │ │ └── Transaction.java │ │ └── client │ │ ├── ResultManager.java │ │ └── ClientResult.java └── test │ └── java │ └── at │ └── archistar │ └── bft │ ├── helper │ └── FakeCommand.java │ └── server │ ├── InitialMessagesTest.java │ └── PerfectRunTest.java ├── README.md ├── pom.xml ├── checkstyle.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk7 4 | - openjdk7 5 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/exceptions/InconsistentResultsException.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.exceptions; 2 | 3 | /** 4 | * this exception is thrown if the resutl of one replica does not match the 5 | * expected results (determined through the other replicas) 6 | * 7 | * @author andy 8 | */ 9 | public class InconsistentResultsException extends Exception { 10 | 11 | private static final long serialVersionUID = -259378201508105072L; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/AbstractCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * This is the abstract base command from which all exchagned commands will 7 | * inherit. Every received command must be related to a client thus the 8 | * mandatory clientCmdId. 9 | * 10 | * @author andy 11 | */ 12 | public abstract class AbstractCommand implements Serializable { 13 | 14 | private static final long serialVersionUID = -7606967793233370624L; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/CommitCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * Commit a command through-out all BFT state machines 5 | * 6 | * @author andy 7 | */ 8 | public class CommitCommand extends IntraReplicaCommand { 9 | 10 | private static final long serialVersionUID = 5922218111327104543L; 11 | 12 | public CommitCommand(int viewNr, int sequence, int replicaId) { 13 | super(replicaId, sequence, viewNr); 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return getSequence() + ": commit"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/AdvanceEraCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * this command is used if the whole BFT system (all connected BFT state 5 | * machines) should perform an era-change, ie. compare all already retrieved 6 | * transactions 7 | * 8 | * @author andy 9 | */ 10 | public class AdvanceEraCommand extends IntraReplicaCommand { 11 | 12 | private static final long serialVersionUID = 4254847418079542679L; 13 | 14 | private final int newEra; 15 | 16 | public AdvanceEraCommand(int sourceReplicaId, int sequenceId, int viewNr, int newEra) { 17 | super(sourceReplicaId, sequenceId, viewNr); 18 | this.newEra = newEra; 19 | } 20 | 21 | public int getNewEra() { 22 | return this.newEra; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/ClientFragmentCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * This command extends a normal ClientCommand with a client fragment id. This 5 | * id is used within algorithms to allow for finer versioning and/or concurrency 6 | * 7 | * @author andy 8 | */ 9 | public abstract class ClientFragmentCommand extends ClientCommand { 10 | 11 | private static final long serialVersionUID = -8569203487109177534L; 12 | 13 | private final String fragmentId; 14 | 15 | public ClientFragmentCommand(int clientId, int clientSequence, String fragmentid) { 16 | super(clientId, clientSequence); 17 | this.fragmentId = fragmentid; 18 | } 19 | 20 | public String getFragmentId() { 21 | return this.fragmentId; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/at/archistar/bft/helper/FakeCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.helper; 2 | 3 | import at.archistar.bft.messages.ClientFragmentCommand; 4 | 5 | /** 6 | * This command is used by a client to forward an update/write operation to the 7 | * replicas. 8 | * 9 | * @author andy 10 | */ 11 | public class FakeCommand extends ClientFragmentCommand { 12 | 13 | private static final long serialVersionUID = -6269916515655616482L; 14 | 15 | public FakeCommand(int clientId, int clientSequence, String fragmentId, byte[] data) { 16 | 17 | super(clientId, clientSequence, fragmentId); 18 | this.payload = data; 19 | } 20 | 21 | public byte[] getData() { 22 | return this.payload; 23 | } 24 | 25 | @Override 26 | public String toString() { 27 | return getClientSequence() + ": write"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/PrepareCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * With this command replicas are exchanging information about planed execution 5 | * commands. This implicitly orders incoming commands (a bit). 6 | * 7 | * @author andy 8 | */ 9 | public class PrepareCommand extends IntraReplicaCommand { 10 | 11 | /** 12 | * message digest, used to verify message 13 | */ 14 | private final String digest; 15 | 16 | public PrepareCommand(int viewNr, int sequence, int replicaId, String digest) { 17 | super(replicaId, sequence, viewNr); 18 | this.digest = digest; 19 | } 20 | 21 | private static final long serialVersionUID = 1L; 22 | 23 | @Override 24 | public String toString() { 25 | return getSequence() + ": prepare"; 26 | } 27 | 28 | public String getClientOperationId() { 29 | return this.digest; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/IntraReplicaCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * this is a command that was sent between replicas 5 | * 6 | * @author andy 7 | */ 8 | public class IntraReplicaCommand extends AbstractCommand { 9 | 10 | private static final long serialVersionUID = 7605418133233561434L; 11 | 12 | /** 13 | * which replica has sent the message 14 | */ 15 | private final int sourceReplicaId; 16 | 17 | /** 18 | * what's the sequence id (should be the sequence nr of the pre-prepare 19 | */ 20 | private final int sequenceId; 21 | 22 | /** 23 | * in which view are we in 24 | */ 25 | private final int viewNr; 26 | 27 | public IntraReplicaCommand(int sourceReplicaId, int sequenceId, int viewNr) { 28 | this.sourceReplicaId = sourceReplicaId; 29 | this.sequenceId = sequenceId; 30 | this.viewNr = viewNr; 31 | } 32 | 33 | public int getViewNr() { 34 | return this.viewNr; 35 | } 36 | 37 | public int getSequence() { 38 | return this.sequenceId; 39 | } 40 | 41 | public int getSourceReplicaId() { 42 | return this.sourceReplicaId; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/PreprepareCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | /** 4 | * This command is utilized by the primary (currently always replica 0) to 5 | * forward a generated sequence number to all replicas. 6 | * 7 | * @author andy 8 | */ 9 | public class PreprepareCommand extends IntraReplicaCommand { 10 | 11 | private static final long serialVersionUID = 5708527225627396654L; 12 | 13 | private final int priorSequence; 14 | 15 | private final String clientOperationId; 16 | 17 | /** 18 | * TODO: this should be a hash over 19 | */ 20 | @SuppressWarnings("unused") 21 | private int cmdIdentifier; 22 | 23 | public PreprepareCommand(int viewNr, int sequence, int replicaId, String clientOperationId, int priorSequence) { 24 | super(replicaId, sequence, viewNr); 25 | 26 | this.priorSequence = priorSequence; 27 | this.clientOperationId = clientOperationId; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return getSequence() + "/" + clientOperationId + ": preprepare"; 33 | } 34 | 35 | public int getPriorSequence() { 36 | return this.priorSequence; 37 | } 38 | 39 | public String getClientOperationId() { 40 | return this.clientOperationId; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/ClientCommand.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | import at.archistar.bft.helper.DigestHelper; 4 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 5 | 6 | /** 7 | * this is a command from the client to a replica 8 | * 9 | * @author andy 10 | */ 11 | public abstract class ClientCommand extends AbstractCommand { 12 | 13 | private static final long serialVersionUID = -1195268975334641339L; 14 | 15 | private final int clientId; 16 | 17 | private final int clientSequence; 18 | 19 | protected byte[] payload = null; 20 | 21 | String operationId = null; 22 | 23 | public ClientCommand(int clientId, int clientSequence) { 24 | super(); 25 | 26 | this.clientId = clientId; 27 | this.clientSequence = clientSequence; 28 | } 29 | 30 | public int getClientId() { 31 | return this.clientId; 32 | } 33 | 34 | public int getClientSequence() { 35 | return this.clientSequence; 36 | } 37 | 38 | public String getClientOperationId() { 39 | 40 | if (this.operationId != null) { 41 | return this.operationId; 42 | } 43 | 44 | return this.operationId = DigestHelper.getClientOperationId(this.clientId, this.clientSequence); 45 | } 46 | 47 | @SuppressFBWarnings("EI_EXPOSE_REP") 48 | public byte[] getPayload() { 49 | return payload; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/helper/DigestHelper.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.helper; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | import javax.xml.bind.annotation.adapters.HexBinaryAdapter; 7 | 8 | /** 9 | * this is a simple singleton helper class for hash creation 10 | * 11 | * @author andy 12 | */ 13 | public class DigestHelper { 14 | 15 | private static MessageDigest md = null; 16 | 17 | private static synchronized void createMd() { 18 | if (md == null) { 19 | try { 20 | md = MessageDigest.getInstance("SHA-256"); 21 | } catch (NoSuchAlgorithmException e) { 22 | e.printStackTrace(); 23 | assert (false); 24 | } 25 | } 26 | } 27 | 28 | public static synchronized String createResultHash(int sequence, byte[] data) { 29 | 30 | createMd(); 31 | 32 | md.update(ByteBuffer.allocate(4).putInt(sequence).array()); 33 | if (data != null) { 34 | md.update(data); 35 | } 36 | 37 | /* store the hash */ 38 | return (new HexBinaryAdapter()).marshal(md.digest()); 39 | } 40 | 41 | public static synchronized String getClientOperationId(int clientId, int clientSequence) { 42 | 43 | createMd(); 44 | 45 | md.update(ByteBuffer.allocate(4).putInt(clientId).array()); 46 | md.update(ByteBuffer.allocate(4).putInt(clientSequence).array()); 47 | 48 | return (new HexBinaryAdapter()).marshal(md.digest()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/TransactionResult.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 4 | import java.util.Arrays; 5 | 6 | import javax.xml.bind.DatatypeConverter; 7 | 8 | /** 9 | * This is used by the replicas to signal back an operation's result to the 10 | * client. 11 | * 12 | * @author andy 13 | */ 14 | public class TransactionResult extends ClientCommand { 15 | 16 | private static final long serialVersionUID = 7045695496206304165L; 17 | 18 | private final int replicaId; 19 | 20 | public TransactionResult(int clientId, int replicaId, int sequenceId, byte[] payload) { 21 | super(clientId, sequenceId); 22 | if (payload != null) { 23 | this.payload = payload.clone(); 24 | } else { 25 | this.payload = null; 26 | } 27 | this.replicaId = replicaId; 28 | } 29 | 30 | public TransactionResult(ClientCommand clientCmd, int serverid, byte[] payload) { 31 | this(clientCmd.getClientId(), serverid, clientCmd.getClientSequence(), payload); 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return getClientId() + "/" + getClientSequence(); 37 | } 38 | 39 | public int getReplicaId() { 40 | return this.replicaId; 41 | } 42 | 43 | public String humanizeResult() { 44 | return DatatypeConverter.printHexBinary(this.payload); 45 | } 46 | 47 | @Override 48 | @SuppressFBWarnings("EI_EXPOSE_REP") 49 | public byte[] getPayload() { 50 | return payload; 51 | } 52 | 53 | public boolean verifyContent(TransactionResult tx) { 54 | return Arrays.equals(this.payload, tx.getPayload()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/messages/CheckpointMessage.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.messages; 2 | 3 | import java.util.Map; 4 | import java.util.Map.Entry; 5 | 6 | /** 7 | * checkpoint message including all remote/local operations 8 | * 9 | * @author andy 10 | */ 11 | public class CheckpointMessage extends IntraReplicaCommand { 12 | 13 | private final int lastExecutedSequence; 14 | 15 | private final Map executedCommands; 16 | 17 | public CheckpointMessage(int sourceReplicaId, int sequenceId, int viewNr, 18 | int lastExecutedSequence, Map operations) { 19 | super(sourceReplicaId, sequenceId, viewNr); 20 | 21 | this.lastExecutedSequence = lastExecutedSequence; 22 | this.executedCommands = operations; 23 | } 24 | 25 | private static final long serialVersionUID = 1125162800001556097L; 26 | 27 | public Integer getLastExecutedSequence() { 28 | return this.lastExecutedSequence; 29 | } 30 | 31 | public Map getExecutedCommands() { 32 | return this.executedCommands; 33 | } 34 | 35 | public boolean compatibleWith(CheckpointMessage other) { 36 | if (this.lastExecutedSequence == other.getLastExecutedSequence()) { 37 | if (other.getExecutedCommands().size() == this.executedCommands.size()) { 38 | for (Entry e : other.getExecutedCommands().entrySet()) { 39 | if (!e.getValue().equalsIgnoreCase(this.executedCommands.get(e.getKey()))) { 40 | return false; 41 | } 42 | } 43 | } else { 44 | return false; 45 | } 46 | return true; 47 | } else { 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/server/BftEngineCallbacks.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import at.archistar.bft.messages.AbstractCommand; 4 | import at.archistar.bft.messages.CheckpointMessage; 5 | import at.archistar.bft.messages.ClientCommand; 6 | import at.archistar.bft.messages.IntraReplicaCommand; 7 | import at.archistar.bft.messages.TransactionResult; 8 | 9 | /** 10 | * these are all callbacks that the server (that instantiates a BFT engine 11 | * should supply 12 | * 13 | * @author andy 14 | */ 15 | public interface BftEngineCallbacks { 16 | 17 | /** 18 | * notify server that an invalid (or unknown) command was received. This 19 | * might signify an malicous attacker or network problems (or more likely 20 | * an implementation error) 21 | * 22 | * @param msg the received message 23 | */ 24 | void invalidMessageReceived(AbstractCommand msg); 25 | 26 | /** 27 | * this signals that the state machine believes that one or more replicas 28 | * have become corrupted 29 | */ 30 | void replicasMightBeMalicous(); 31 | 32 | /** 33 | * send a message to all replicas 34 | * 35 | * @param cmd the to be sent message 36 | */ 37 | void sendToReplicas(IntraReplicaCommand cmd); 38 | 39 | /** 40 | * a client command should be executed by the server 41 | * @param cmd the to be executed client command 42 | * @return the result of the client command 43 | */ 44 | byte[] executeClientCommand(ClientCommand cmd); 45 | 46 | /** 47 | * the state machine received a checkpoint message that wasn't fitting 48 | * @param msg the weird checkpoint message 49 | */ 50 | void invalidCheckpointMessage(CheckpointMessage msg); 51 | 52 | /** 53 | * send an result back to a client 54 | * 55 | * @param transactionResult the to-be-sent result 56 | */ 57 | void answerClient(TransactionResult transactionResult); 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/client/ResultManager.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.client; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.concurrent.locks.Lock; 6 | import java.util.concurrent.locks.ReentrantLock; 7 | 8 | import at.archistar.bft.exceptions.InconsistentResultsException; 9 | import at.archistar.bft.messages.TransactionResult; 10 | 11 | /** 12 | * this is a manager class that collects and manages all ClientResults that 13 | * were retrieved by the replicas 14 | * 15 | * @author andy 16 | */ 17 | public class ResultManager { 18 | 19 | private final Map results; 20 | 21 | private final Lock lock = new ReentrantLock(); 22 | 23 | public ResultManager() { 24 | this.results = new HashMap<>(); 25 | } 26 | 27 | /** 28 | * Add a new client operation (for which we need to wait) 29 | * 30 | * @param f faulty replica count 31 | * @param clientId our client id 32 | * @param clientSequence our operations sequence id 33 | * @return a ClientResult object on which can be waited upon 34 | */ 35 | public ClientResult addClientOperation(int f, int clientId, int clientSequence) { 36 | 37 | ClientResult result = new ClientResult(f, clientId, clientSequence); 38 | lock.lock(); 39 | try { 40 | this.results.put(clientSequence, result); 41 | } finally { 42 | lock.unlock(); 43 | } 44 | return result; 45 | } 46 | 47 | public void addClientResponse(int clientId, int clientSequence, TransactionResult tx) throws InconsistentResultsException { 48 | 49 | lock.lock(); 50 | try { 51 | ClientResult result = this.results.get(clientSequence); 52 | 53 | if (result != null) { 54 | result.addResult(clientId, clientSequence, tx); 55 | } else { 56 | assert (false); 57 | } 58 | } finally { 59 | lock.unlock(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/at/archistar/bft/server/InitialMessagesTest.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.mockito.Mockito.*; 6 | 7 | import at.archistar.bft.helper.FakeCommand; 8 | import at.archistar.bft.messages.ClientCommand; 9 | import at.archistar.bft.messages.IntraReplicaCommand; 10 | import at.archistar.bft.messages.PreprepareCommand; 11 | 12 | public class InitialMessagesTest { 13 | 14 | @Test 15 | public void primarySendsPrepareAfterReceivingClientMessage() { 16 | 17 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 18 | BftEngine primary = spy(new BftEngine(1, 1, 1, callbacks)); 19 | 20 | /* stub: make sure that BftEngine is primary */ 21 | when(primary.isPrimary()).thenReturn(true); 22 | 23 | int clientId = 1; 24 | int clientSequence = 1; 25 | String fragmentId = "fragment-id-1"; 26 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 27 | 28 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 29 | primary.processClientCommand(cmd); 30 | 31 | /* If message was called, expect that a new PreprepareCommand is sent to all other replicas */ 32 | verify(callbacks).sendToReplicas(isA(PreprepareCommand.class)); 33 | } 34 | 35 | @Test 36 | public void NonPrimaryDoesntSendPreprareAfterReceivingClientMessage() { 37 | 38 | /* this throws an exception if any callback is called */ 39 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 40 | 41 | BftEngine primary = spy(new BftEngine(1, 1, callbacks)); 42 | 43 | /* stub: make sure that BftEngine is not primary */ 44 | when(primary.isPrimary()).thenReturn(false); 45 | 46 | int clientId = 1; 47 | int clientSequence = 1; 48 | String fragmentId = "fragment-id-1"; 49 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 50 | 51 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 52 | primary.processClientCommand(cmd); 53 | 54 | verify(callbacks, never()).sendToReplicas(any(IntraReplicaCommand.class)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/client/ClientResult.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.client; 2 | 3 | import java.util.HashMap; 4 | import java.util.concurrent.locks.Condition; 5 | import java.util.concurrent.locks.Lock; 6 | import java.util.concurrent.locks.ReentrantLock; 7 | 8 | import at.archistar.bft.exceptions.InconsistentResultsException; 9 | import at.archistar.bft.messages.TransactionResult; 10 | 11 | /** 12 | * Helper class used to synchronously wait for client operation finish. 13 | * 14 | * @author andy 15 | */ 16 | public class ClientResult { 17 | 18 | private final Lock lock = new ReentrantLock(); 19 | 20 | private final Condition condition = lock.newCondition(); 21 | 22 | /** 23 | * the configured faulty replica amount 24 | */ 25 | private final int f; 26 | 27 | /** 28 | * our client id, used for checks 29 | */ 30 | private final int clientId; 31 | 32 | /** 33 | * our client (operation) sequence, used for checks 34 | */ 35 | private final int clientSequence; 36 | 37 | /** 38 | * map with all retrieved results 39 | */ 40 | private final HashMap results = new HashMap<>(); 41 | 42 | /** 43 | * note: always returns a locked ClientResult 44 | */ 45 | public ClientResult(int f, int clientId, int clientSequence) { 46 | this.f = f; 47 | this.clientId = clientId; 48 | this.clientSequence = clientSequence; 49 | 50 | lock.lock(); 51 | } 52 | 53 | /** 54 | * adds a received replica answer 55 | * 56 | * @param clientId for which client? 57 | * @param clientSequence for which sequence (== operation)? 58 | * @param tx the result 59 | * @return true if enough results for output determination were received 60 | * @throws InconsistentResultsException is thrown if there seems to be a 61 | * faulty replica 62 | */ 63 | public boolean addResult(int clientId, int clientSequence, TransactionResult tx) throws InconsistentResultsException { 64 | 65 | lock.lock(); 66 | boolean result = false; 67 | 68 | try { 69 | /* consistency checks */ 70 | if (this.clientId != clientId || this.clientSequence != clientSequence) { 71 | throw new InconsistentResultsException(); 72 | } 73 | 74 | results.put(tx.getReplicaId(), tx); 75 | 76 | /* NOTE: this condition is highly dependent upon the used secret-sharing mechanism */ 77 | if (results.size() >= (2 * f + 1)) { 78 | condition.signal(); 79 | result = true; 80 | } 81 | } finally { 82 | lock.unlock(); 83 | } 84 | return result; 85 | } 86 | 87 | /** 88 | * note: expects ClientResult to be locked 89 | */ 90 | public void waitForEnoughAnswers() { 91 | while (results.size() < (f + 1)) { 92 | try { 93 | condition.await(); 94 | lock.unlock(); 95 | } catch (InterruptedException e) { 96 | assert (false); 97 | e.printStackTrace(); 98 | } 99 | } 100 | } 101 | 102 | public boolean containsDataForServer(int bftId) { 103 | return this.results.containsKey(bftId); 104 | } 105 | 106 | public byte[] getDataForServer(int bftId) { 107 | return this.results.get(bftId).getPayload(); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Note: we're currently focusing our development effort on a new generation of the software which can also be [found on gitlab](http://github.com/Archistar/archistar-akka) 2 | 3 | archistar-bft [![Build Status](https://travis-ci.org/Archistar/archistar-bft.png?branch=master)](https://travis-ci.org/Archistar/archistar-bft) 4 | ============= 5 | 6 | archistar-bft is an Java Open-Source library. It was developed for and within the [Archistar-core](https://github.com/Archistar/archistar-core) project, in 2014 the BFT algorithm's state engine was extracted into a library of its own. The reasoning behind extracting the library was to create a platform- and transport-independent BFT engine which can be reused within other projects. This allows for a very clear and compact code base (currently ~800LOC BFT code and 200LOC test cases). 7 | 8 | For example [Archistar](https://github.com/Archistar/archistar-core) combines the BFT state-machine with a [netty.io http transport](http://netty.io). We hope that other projects can reuse this code and/or extend it. 9 | 10 | As the code handles an abstract BFT state-machine test-cases can easily be written without the need of a network simulation software. The test-cases themself should be meaningful enough to get an better overview of BFT. 11 | 12 | Current ongoing research is mostly in the fault-tolerance area. The view-change code is lacking at best, state-transfer call-backs need to be implemented. Help is always welcome. 13 | 14 | Byzantine Fault Tolerance (BFT) Algorithms 15 | ------------------------------------------ 16 | 17 | Byzantine Fault Tolerance's objective is to find consensus within a distributed system in which every participating client or server can fail. In addition to "normal" stop-faults (faulty components stop communicating or signal an error) byzantine-fault-tolerant systems can deal with arbitrary errors, i.e. components can maliciously produce faulty outputs or corrupt their internal state. 18 | 19 | Initially this subject was breached by [Lamport, Shostak and Pease in 1982](http://research.microsoft.com/en-us/um/people/lamport/pubs/byz.pdf), but the proposed protocols were too expensive for general use. In 1999 Castro and Liskov's [Practical Byzantine Fault Tolerance](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.127.6130) kindled new research into BFT algorithms. Protocols like [Zyzzyva](http://dl.acm.org/citation.cfm?id=1294267) further improved good-case performance, but [Clement, Wong, Alvisi, Dahlin](https://www.cs.utexas.edu/~aclement/aardvark-tr.pdf) found those protocols susceptible to denial-of-service attacks and proposed Aardvark, a robust PBFT implementation with constant performance under pressure. Archistar uses an Aardvark-influenced BFT protocol with adoptions for secret-sharing algorithm integration. 20 | 21 | BFT algorithms impose restrictions upon the minimal server count. Algorithms without special hardware requirements typically need at lease 3f+1 to 5f+1 servers for handling f faulty servers. In addition servers (also called replicas in BFT terminology) contain active logic. They are able to perform cryptographic algorithms, manage multiple collections of operation states as well as communicate with each other. 22 | 23 | 24 | Differences to other solutions 25 | ------------------------------ 26 | 27 | In PBFT a client initiates an operation by sending the operation to each of the 3f+1 replicas. For our storage use-case this would mandate that an encrypted copy of the whole user dataset would be sent to each server -- thus beating privacy. Within the Archistar BFT protocol the client splits up data into 3f+1 encrypted fragments, each server only receives one of the fragments. The used secret-sharing algorithm ensures that a single replica is not able to reconstruct the plaintext. 28 | 29 | One important non-functional requirement of Archistar is a ``hackable'' code-base. As we embarked on testing different algorithms and protocols lean and agile source code was paramount. We believe in Abstract's and Aardvark's commitment to software engineering. 30 | 31 | Citing Archistar 32 | ---------------------- 33 | 34 | If you find Archistar useful for your work or if you use Archistar in a project, paper, website, etc., 35 | please cite the software as 36 | 37 | T. Lorünser, A. Happe, D. Slamanig (2014). “ARCHISTAR – A framework for secure distributed storage”. GNU General Public License. http://ARCHISTAR.at 38 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/server/BftEngine.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import at.archistar.bft.messages.AbstractCommand; 7 | import at.archistar.bft.messages.AdvanceEraCommand; 8 | import at.archistar.bft.messages.CheckpointMessage; 9 | import at.archistar.bft.messages.ClientCommand; 10 | import at.archistar.bft.messages.IntraReplicaCommand; 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | /** 15 | * this class encapsulates a whole BFT engine (as would be seen within one 16 | * replica). The whole BFT system consists of multiple distributed BFt engines 17 | * 18 | * @author andy 19 | */ 20 | public class BftEngine { 21 | 22 | private final BftEngineCallbacks callbacks; 23 | 24 | private final int f; 25 | 26 | private final int replicaId; 27 | 28 | private final CheckpointManager checkpoints; 29 | 30 | private final Logger logger = LoggerFactory.getLogger(BftEngine.class); 31 | 32 | private TransactionManager currentEra; 33 | 34 | private final Set oldEras = new HashSet<>(); 35 | 36 | public BftEngine(int replicaId, int viewNr, int f, BftEngineCallbacks callbacks) { 37 | this.callbacks = callbacks; 38 | this.f = f; 39 | this.replicaId = replicaId; 40 | this.checkpoints = new CheckpointManager(replicaId, callbacks, f); 41 | this.currentEra = new TransactionManager(replicaId, viewNr, f, callbacks, checkpoints); 42 | } 43 | 44 | 45 | public BftEngine(int replicaId, int f, BftEngineCallbacks callbacks) { 46 | this(replicaId, 0, f, callbacks); 47 | } 48 | 49 | public void processClientCommand(ClientCommand cmd) { 50 | Transaction t = this.currentEra.getTransaction(cmd); 51 | handleMessage(t, cmd); 52 | t.unlock(); 53 | this.currentEra.cleanupTransactions(t); 54 | } 55 | 56 | public void processIntraReplicaCommand(IntraReplicaCommand cmd) { 57 | if (!checkEraOfMessage((IntraReplicaCommand) cmd)) { 58 | logger.warn("message from old era detected"); 59 | } else { 60 | if (cmd instanceof CheckpointMessage) { 61 | addCheckpointMessage((CheckpointMessage) cmd); 62 | } else if (cmd instanceof AdvanceEraCommand) { 63 | newEra(((AdvanceEraCommand) cmd).getNewEra()); 64 | } else { 65 | /* this locks t */ 66 | Transaction t = this.currentEra.getTransaction(cmd); 67 | handleMessage(t, cmd); 68 | t.unlock(); 69 | this.currentEra.cleanupTransactions(t); 70 | } 71 | } 72 | } 73 | 74 | private boolean checkEraOfMessage(IntraReplicaCommand cmd) { 75 | return cmd.getViewNr() >= this.currentEra.getViewNr(); 76 | } 77 | 78 | public boolean isPrimary() { 79 | return this.replicaId == (this.currentEra.getViewNr() % (3*f + 1)); 80 | } 81 | 82 | private void newEra(int newEra) { 83 | /* backup old era */ 84 | this.oldEras.add(currentEra); 85 | 86 | /* create a new era */ 87 | currentEra = currentEra.createNewEra(newEra); 88 | } 89 | 90 | /** mostly to allow for stubbing */ 91 | TransactionManager getCurrentEra() { 92 | return this.currentEra; 93 | } 94 | 95 | private void addCheckpointMessage(CheckpointMessage msg) { 96 | this.checkpoints.addCheckpointMessage(msg); 97 | } 98 | 99 | /** 100 | * this outputs the collection count if it is over a treshold. This 101 | * typically identifies problems with the locking (or thread scheduling) 102 | * code 103 | */ 104 | public void checkCollections() { 105 | this.currentEra.checkCollections(); 106 | } 107 | 108 | public void tryAdvanceEra() { 109 | int viewNr = this.currentEra.getViewNr(); 110 | AdvanceEraCommand cmd = new AdvanceEraCommand(replicaId, -1, viewNr, viewNr + 1); 111 | this.callbacks.sendToReplicas(cmd); 112 | newEra(viewNr + 1); 113 | } 114 | 115 | private void handleMessage(Transaction t, AbstractCommand msg) { 116 | 117 | t.tryAdvanceToPreprepared(isPrimary()); 118 | t.tryAdvanceToPrepared(this.currentEra.getLastCommited()); 119 | if (t.tryAdvanceToCommited()) { 120 | /* check if we should send a CHECKPOINT message */ 121 | checkpoints.addTransaction(t, t.getResult(), this.currentEra.getViewNr()); 122 | this.currentEra.newCommited(t.getSequenceNr()); 123 | } 124 | t.tryMarkDelete(); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/server/CheckpointManager.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import java.util.HashSet; 4 | import java.util.Iterator; 5 | import java.util.Map.Entry; 6 | import java.util.Set; 7 | import java.util.SortedMap; 8 | import java.util.TreeMap; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import at.archistar.bft.helper.DigestHelper; 14 | import at.archistar.bft.messages.CheckpointMessage; 15 | 16 | /** 17 | * an instance of this class should handle all periodic checkpoint message 18 | * activity. It will get notified about every completed transaction 19 | * 20 | * @author andy 21 | */ 22 | public class CheckpointManager { 23 | 24 | private final Logger logger = LoggerFactory.getLogger(CheckpointManager.class); 25 | 26 | private final int serverId; 27 | 28 | private final int f; 29 | 30 | private int lowWaterMark = -1; 31 | 32 | /** 33 | * this stores operation's results -- will be used for check-pointing 34 | */ 35 | private SortedMap collResults; 36 | 37 | private final SortedMap> unstableCheckpoints; 38 | 39 | private static final int PERIOD_TIME = 128; 40 | 41 | private final BftEngineCallbacks callbacks; 42 | 43 | public CheckpointManager(int serverId, BftEngineCallbacks callbacks, int f) { 44 | this.serverId = serverId; 45 | this.collResults = new TreeMap<>(); 46 | this.unstableCheckpoints = new TreeMap<>(); 47 | this.f = f; 48 | this.callbacks = callbacks; 49 | } 50 | 51 | public synchronized void addCheckpointMessage(CheckpointMessage msg) { 52 | if (msg.getLastExecutedSequence() > lowWaterMark) { 53 | addCheckpointMessageToLog(msg); 54 | } else { 55 | /* this was already committed, discard message */ 56 | // TODO: should we do some notification of cleanups now? 57 | } 58 | } 59 | 60 | private void addCheckpointMessageToLog(CheckpointMessage msg) { 61 | 62 | int sequence = msg.getLastExecutedSequence(); 63 | Set currentMessages; 64 | 65 | if (unstableCheckpoints.containsKey(sequence)) { 66 | currentMessages = unstableCheckpoints.get(sequence); 67 | } else { 68 | currentMessages = new HashSet<>(); 69 | } 70 | 71 | /* check if new checkpoint message fits the existing ones */ 72 | for (CheckpointMessage old : currentMessages) { 73 | if (!old.compatibleWith(msg)) { 74 | callbacks.invalidCheckpointMessage(msg); 75 | } 76 | } 77 | 78 | currentMessages.add(msg); 79 | unstableCheckpoints.put(sequence, currentMessages); 80 | 81 | if (unstableCheckpoints.size() >= 10) { 82 | logger.warn("server {}: unstableCheckpoint count: {}", serverId, unstableCheckpoints.size()); 83 | } 84 | 85 | /** 86 | * TODO: what is the highest-unstable logic doing? It looks weird, can 87 | * we remove it? 88 | */ 89 | int highestUnstable = -1; 90 | Iterator>> it = unstableCheckpoints.entrySet().iterator(); 91 | while (it.hasNext()) { 92 | Entry> e = it.next(); 93 | if (e.getValue().size() >= (2 * f + 1)) { 94 | /* check if this is the youngest checkpoint in there */ 95 | if (highestUnstable == -1 || highestUnstable <= e.getKey()) { 96 | lowWaterMark = e.getKey(); 97 | it.remove(); 98 | } else { 99 | logger.warn("highest unstable {} < new checkpoint {}", highestUnstable, e.getKey()); 100 | } 101 | } else { 102 | highestUnstable = e.getKey(); 103 | } 104 | } 105 | } 106 | 107 | public synchronized void addTransaction(Transaction t, byte[] result, int viewNr) { 108 | this.collResults.put(t.getSequenceNr(), DigestHelper.createResultHash(t.getSequenceNr(), result)); 109 | 110 | if (t.getSequenceNr() % PERIOD_TIME == 0) { 111 | sendCheckpointMessage(viewNr, t.getSequenceNr()); 112 | } 113 | } 114 | 115 | private void sendCheckpointMessage(int viewNr, int sequence) { 116 | CheckpointMessage msg = new CheckpointMessage(serverId, -10, viewNr, sequence, collResults); 117 | collResults = new TreeMap<>(); 118 | 119 | addCheckpointMessageToLog(msg); 120 | 121 | /* send CHECKPOINT message */ 122 | callbacks.sendToReplicas(msg); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | at.archistar 5 | archistar-bft 6 | jar 7 | 0.1-wip 8 | archistar-bft 9 | http://maven.apache.org 10 | 11 | 12 | internal 13 | http://sqt.ait.ac.at/archistar/repository 14 | 15 | 16 | jboss 17 | http://repository.jboss.org/nexus/content/groups/public/ 18 | 19 | 20 | 21 | UTF-8 22 | 23 | 24 | 25 | 26 | junit 27 | junit 28 | 4.11 29 | test 30 | 31 | 32 | 33 | org.mockito 34 | mockito-all 35 | 1.8.4 36 | 37 | 38 | 39 | org.easytesting 40 | fest-assert-core 41 | 2.0M10 42 | 43 | 44 | 45 | org.slf4j 46 | slf4j-simple 47 | 1.7.5 48 | 49 | 50 | org.slf4j 51 | slf4j-api 52 | 1.7.5 53 | 54 | 55 | 56 | com.google.code.findbugs 57 | annotations 58 | 3.0.0 59 | 60 | 61 | 62 | 63 | 64 | org.apache.maven.plugins 65 | maven-checkstyle-plugin 66 | 2.12.1 67 | 68 | 69 | validate 70 | validate 71 | 72 | checkstyle.xml 73 | UTF-8 74 | true 75 | true 76 | false 77 | 78 | 79 | check 80 | 81 | 82 | 83 | 84 | 85 | org.codehaus.mojo 86 | findbugs-maven-plugin 87 | 3.0.0 88 | 89 | Max 90 | Low 91 | true 92 | ${project.build.directory}/findbugs 93 | 94 | 95 | 96 | analyze-compile 97 | compile 98 | 99 | check 100 | 101 | 102 | 103 | 104 | 105 | org.apache.maven.plugins 106 | maven-compiler-plugin 107 | 2.0.2 108 | 109 | 1.7 110 | 1.7 111 | 112 | 113 | 114 | org.apache.maven.plugins 115 | maven-surefire-plugin 116 | 2.16 117 | 118 | 119 | 120 | 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-javadoc-plugin 125 | 2.9 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-dependency-plugin 130 | 2.8 131 | 132 | 133 | 134 | 135 | Austrian Institute of Technology 136 | http://www.ait.ac.at 137 | 138 | bla bla bla 139 | 140 | -------------------------------------------------------------------------------- /src/test/java/at/archistar/bft/server/PerfectRunTest.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import org.junit.Test; 4 | import org.mockito.ArgumentCaptor; 5 | 6 | import static org.fest.assertions.api.Assertions.*; 7 | import static org.mockito.Mockito.*; 8 | 9 | import at.archistar.bft.helper.FakeCommand; 10 | import at.archistar.bft.messages.ClientCommand; 11 | import at.archistar.bft.messages.CommitCommand; 12 | import at.archistar.bft.messages.PrepareCommand; 13 | import at.archistar.bft.messages.PreprepareCommand; 14 | import at.archistar.bft.messages.TransactionResult; 15 | import at.archistar.bft.server.BftEngine; 16 | import at.archistar.bft.server.BftEngineCallbacks; 17 | 18 | public class PerfectRunTest { 19 | 20 | @Test 21 | public void testPrimaryWithThreeReplicas() { 22 | 23 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 24 | BftEngine primary = spy(new BftEngine(0, 1, callbacks)); 25 | 26 | /* stub: make sure that BftEngine is primary */ 27 | when(primary.isPrimary()).thenReturn(true); 28 | assertThat(primary.isPrimary()).isEqualTo(true); 29 | 30 | int clientId = 1; 31 | int clientSequence = 1; 32 | int viewNr = 0; 33 | String fragmentId = "fragment-id-1"; 34 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 35 | 36 | /* client sends command to primary */ 37 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 38 | primary.processClientCommand(cmd); 39 | 40 | /* capture outgoing preprepare command */ 41 | ArgumentCaptor ppCommand = ArgumentCaptor.forClass(PreprepareCommand.class); 42 | verify(callbacks, times(1)).sendToReplicas(ppCommand.capture()); 43 | String digest = ppCommand.getValue().getClientOperationId(); 44 | int sequence = ppCommand.getValue().getSequence(); 45 | 46 | /* primary receives prepare commands */ 47 | primary.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 1, digest)); 48 | primary.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 2, digest)); 49 | primary.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 3, digest)); 50 | verify(callbacks, times(1)).sendToReplicas(isA(CommitCommand.class)); 51 | 52 | /* primary receives commit messages */ 53 | primary.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 1)); 54 | primary.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 2)); 55 | primary.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 3)); 56 | 57 | /* primary executes operation */ 58 | verify(callbacks, times(1)).executeClientCommand(cmd); 59 | verify(callbacks, times(1)).answerClient(isA(TransactionResult.class)); 60 | } 61 | 62 | @Test 63 | public void primaryWithTwoReplicas() { 64 | 65 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 66 | BftEngine primary = spy(new BftEngine(0, 1, callbacks)); 67 | 68 | /* stub: make sure that BftEngine is primary */ 69 | when(primary.isPrimary()).thenReturn(true); 70 | assertThat(primary.isPrimary()).isEqualTo(true); 71 | 72 | int clientId = 1; 73 | int clientSequence = 1; 74 | int viewNr = 0; 75 | String fragmentId = "fragment-id-1"; 76 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 77 | 78 | /* client sends command to primary */ 79 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 80 | primary.processClientCommand(cmd); 81 | 82 | /* capture outgoing preprepare command */ 83 | ArgumentCaptor ppCommand = ArgumentCaptor.forClass(PreprepareCommand.class); 84 | verify(callbacks, times(1)).sendToReplicas(ppCommand.capture()); 85 | String digest = ppCommand.getValue().getClientOperationId(); 86 | int sequence = ppCommand.getValue().getSequence(); 87 | 88 | /* primary receives prepare commands */ 89 | primary.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 1, digest)); 90 | primary.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 2, digest)); 91 | verify(callbacks, times(1)).sendToReplicas(isA(CommitCommand.class)); 92 | 93 | /* primary receives commit messages */ 94 | primary.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 1)); 95 | primary.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 3)); 96 | 97 | /* primary executes operation */ 98 | verify(callbacks, times(1)).executeClientCommand(cmd); 99 | verify(callbacks, times(1)).answerClient(isA(TransactionResult.class)); 100 | } 101 | 102 | @Test 103 | public void testReplicaWithTwoReplicasAndPrimary() { 104 | 105 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 106 | BftEngine replica = spy(new BftEngine(1, 1, callbacks)); 107 | 108 | /* stub: make sure that BftEngine is primary */ 109 | when(replica.isPrimary()).thenReturn(false); 110 | assertThat(replica.isPrimary()).isEqualTo(false); 111 | 112 | int clientId = 1; 113 | int clientSequence = 1; 114 | int viewNr = 0; 115 | String fragmentId = "fragment-id-1"; 116 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 117 | 118 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 119 | 120 | /* client sends command to primary */ 121 | replica.processClientCommand(cmd); 122 | 123 | int sequence = -1; 124 | int priorSequence = -2; 125 | String digest = cmd.getClientOperationId(); 126 | 127 | replica.processIntraReplicaCommand(new PreprepareCommand(viewNr, sequence, 0, digest, priorSequence)); 128 | verify(callbacks, times(1)).sendToReplicas(isA(PrepareCommand.class)); 129 | 130 | /* primary receives prepare commands */ 131 | replica.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 0, digest)); 132 | replica.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 2, digest)); 133 | replica.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 3, digest)); 134 | verify(callbacks, times(1)).sendToReplicas(isA(CommitCommand.class)); 135 | 136 | /* primary receives commit messages */ 137 | replica.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 0)); 138 | replica.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 2)); 139 | replica.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 3)); 140 | 141 | /* primary executes operation */ 142 | verify(callbacks, times(1)).executeClientCommand(cmd); 143 | verify(callbacks, times(1)).answerClient(isA(TransactionResult.class)); 144 | } 145 | 146 | @Test 147 | public void testReplicaWithOneReplicaAndPrimary() { 148 | 149 | BftEngineCallbacks callbacks = mock(BftEngineCallbacks.class); 150 | BftEngine replica = spy(new BftEngine(1, 1, callbacks)); 151 | 152 | /* stub: make sure that BftEngine is primary */ 153 | when(replica.isPrimary()).thenReturn(false); 154 | assertThat(replica.isPrimary()).isEqualTo(false); 155 | 156 | int clientId = 1; 157 | int clientSequence = 1; 158 | int viewNr = 0; 159 | String fragmentId = "fragment-id-1"; 160 | byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 161 | 162 | ClientCommand cmd = new FakeCommand(clientId, clientSequence, fragmentId, data); 163 | 164 | /* client sends command to primary */ 165 | replica.processClientCommand(cmd); 166 | 167 | int sequence = -1; 168 | int priorSequence = -2; 169 | String digest = cmd.getClientOperationId(); 170 | 171 | replica.processIntraReplicaCommand(new PreprepareCommand(viewNr, sequence, 0, digest, priorSequence)); 172 | verify(callbacks, times(1)).sendToReplicas(isA(PrepareCommand.class)); 173 | 174 | /* primary receives prepare commands */ 175 | replica.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 0, digest)); 176 | replica.processIntraReplicaCommand(new PrepareCommand(viewNr, sequence, 3, digest)); 177 | verify(callbacks, times(1)).sendToReplicas(isA(CommitCommand.class)); 178 | 179 | /* primary receives commit messages */ 180 | replica.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 0)); 181 | replica.processIntraReplicaCommand(new CommitCommand(viewNr, sequence, 3)); 182 | 183 | /* primary executes operation */ 184 | verify(callbacks, times(1)).executeClientCommand(cmd); 185 | verify(callbacks, times(1)).answerClient(isA(TransactionResult.class)); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 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 | 59 | 60 | 61 | 62 | 63 | 65 | 68 | 69 | 70 | 71 | 72 | 73 | 75 | 76 | 77 | 78 | 79 | 80 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 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 | 125 | 126 | 127 | 128 | 129 | 131 | 132 | 133 | 134 | 135 | 137 | 138 | 139 | 140 | 141 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 175 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 204 | 205 | 206 | 207 | 208 | 209 | 214 | 215 | 216 | 221 | 222 | 223 | 224 | 229 | 230 | 231 | 235 | 236 | 237 | 238 | 239 | 240 | 243 | 244 | 245 | 246 | 247 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 268 | 269 | 270 | 271 | 272 | 273 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/server/TransactionManager.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import at.archistar.bft.exceptions.InconsistentResultsException; 4 | import at.archistar.bft.messages.AbstractCommand; 5 | import at.archistar.bft.messages.ClientFragmentCommand; 6 | import at.archistar.bft.messages.CommitCommand; 7 | import at.archistar.bft.messages.PrepareCommand; 8 | import at.archistar.bft.messages.PreprepareCommand; 9 | import java.util.Iterator; 10 | import java.util.SortedMap; 11 | import java.util.TreeMap; 12 | import java.util.concurrent.locks.ReentrantLock; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | /** 17 | * 18 | * TODO: can't we move some of the area stuff in here? A TransactionManager copy 19 | * should be the same as an era? 20 | * 21 | * @author andy 22 | */ 23 | public class TransactionManager { 24 | 25 | /** 26 | * (client-side operation id) -> transaction mapping 27 | */ 28 | private final SortedMap collClientId; 29 | 30 | /** 31 | * (internal id aka. sequence) -> transaction mapping 32 | */ 33 | private final SortedMap collSequence; 34 | 35 | private final ReentrantLock lockCollections = new ReentrantLock(); 36 | 37 | private final int replicaId; 38 | 39 | private int maxSequence = 0; 40 | 41 | private int lastCommited = -1; 42 | 43 | private final int viewNr; 44 | 45 | private final Logger logger = LoggerFactory.getLogger(TransactionManager.class); 46 | 47 | private final int f; 48 | 49 | private final BftEngineCallbacks callbacks; 50 | 51 | private final CheckpointManager checkpoints; 52 | 53 | public TransactionManager(int replicaId, int viewNr, int f, BftEngineCallbacks callbacks, CheckpointManager checkpoints) { 54 | this.collClientId = new TreeMap<>(); 55 | this.collSequence = new TreeMap<>(); 56 | this.replicaId = replicaId; 57 | this.f = f; 58 | this.callbacks = callbacks; 59 | this.checkpoints = checkpoints; 60 | this.viewNr = viewNr; 61 | } 62 | 63 | public TransactionManager(int replicaId, int f, BftEngineCallbacks callbacks, CheckpointManager checkpoints) { 64 | this(replicaId, 0, f, callbacks, checkpoints); 65 | } 66 | 67 | private Transaction handleClientFragmentCommand(ClientFragmentCommand c) { 68 | String clientOperationId = c.getClientOperationId(); 69 | Transaction result; 70 | 71 | if (collClientId.containsKey(clientOperationId)) { 72 | /* there was already a preprepare request */ 73 | result = collClientId.get(clientOperationId); 74 | } else { 75 | /* first request */ 76 | result = new Transaction(c, replicaId, f, this.callbacks); 77 | collClientId.put(c.getClientOperationId(), result); 78 | } 79 | 80 | result.addClientCommand(c); 81 | 82 | if (isPrimary()) { 83 | result.setDataFromPreprepareCommand(maxSequence++, getPriorSequenceNumber(c.getFragmentId())); 84 | collSequence.put(result.getSequenceNr(), result); 85 | PreprepareCommand seq = result.createPreprepareCommand(); 86 | callbacks.sendToReplicas(seq); 87 | } 88 | return result; 89 | } 90 | 91 | private Transaction handlePreprepareCommand(PreprepareCommand c) { 92 | String clientOperationId = c.getClientOperationId(); 93 | Transaction result; 94 | int sequence = c.getSequence(); 95 | 96 | boolean knownFromClientOpId = collClientId.containsKey(clientOperationId); 97 | boolean knownFromSequence = collSequence.containsKey(sequence); 98 | 99 | if (knownFromClientOpId && knownFromSequence) { 100 | result = collClientId.get(clientOperationId); 101 | result.merge(collSequence.get(sequence)); 102 | } else if (knownFromClientOpId && !knownFromSequence) { 103 | result = collClientId.get(clientOperationId); 104 | result.setDataFromPreprepareCommand(sequence, c.getPriorSequence()); 105 | } else if (!knownFromClientOpId && knownFromSequence) { 106 | result = collSequence.get(sequence); 107 | result.setClientOperationId(clientOperationId); 108 | } else { 109 | /* initial network package */ 110 | result = new Transaction(c, replicaId, f, this.callbacks); 111 | } 112 | 113 | if (!isPrimary()) { 114 | result.setDataFromPreprepareCommand(sequence, c.getPriorSequence()); 115 | } 116 | 117 | /* after the prepare command the transaction should be known by both client-operation-id 118 | * as well as by the bft-internal sequence number */ 119 | result.setPrepreparedReceived(); 120 | collSequence.put(sequence, result); 121 | collClientId.put(clientOperationId, result); 122 | return result; 123 | } 124 | 125 | private Transaction handlePrepareCommand(PrepareCommand c) { 126 | Transaction result; 127 | int sequence = c.getSequence(); 128 | 129 | if (collSequence.containsKey(sequence)) { 130 | result = collSequence.get(sequence); 131 | } else { 132 | result = new Transaction(c, replicaId, f, this.callbacks); 133 | collSequence.put(sequence, result); 134 | } 135 | 136 | try { 137 | result.addPrepareCommand(c); 138 | } catch (InconsistentResultsException e) { 139 | callbacks.replicasMightBeMalicous(); 140 | } 141 | return result; 142 | } 143 | 144 | private Transaction handleCommitCommand(CommitCommand c) { 145 | Transaction result = collSequence.get(c.getSequence()); 146 | result.addCommitCommand(c); 147 | return result; 148 | } 149 | 150 | public Transaction getTransaction(AbstractCommand msg) { 151 | 152 | Transaction result = null; 153 | lockCollections.lock(); 154 | try { 155 | 156 | if (msg instanceof ClientFragmentCommand) { 157 | result = handleClientFragmentCommand((ClientFragmentCommand)msg); 158 | } else if (msg instanceof PreprepareCommand) { 159 | result = handlePreprepareCommand((PreprepareCommand)msg); 160 | } else if (msg instanceof PrepareCommand) { 161 | result = handlePrepareCommand((PrepareCommand)msg); 162 | } else if (msg instanceof CommitCommand) { 163 | result = handleCommitCommand((CommitCommand)msg); 164 | } else { 165 | callbacks.invalidMessageReceived(msg); 166 | } 167 | 168 | if (result != null) { 169 | result.lock(); 170 | } 171 | } finally { 172 | lockCollections.unlock(); 173 | } 174 | return result; 175 | } 176 | 177 | public void cleanupTransactions(Transaction mightDelete) { 178 | 179 | this.lockCollections.lock(); 180 | try { 181 | if (mightDelete.tryMarkDelete()) { 182 | mightDelete.lock(); 183 | collClientId.remove(mightDelete.getClientOperationId()); 184 | collSequence.remove(mightDelete.getSequenceNr()); 185 | /* free transaction */ 186 | mightDelete.unlock(); 187 | } 188 | 189 | /* search for preparable and commitable transactions */ 190 | Iterator it = collSequence.values().iterator(); 191 | while (it.hasNext()) { 192 | Transaction x = it.next(); 193 | 194 | x.lock(); 195 | 196 | if (x.tryAdvanceToPrepared(lastCommited)) { 197 | lastCommited = Math.max(lastCommited, x.getPriorSequenceNr()); 198 | 199 | if (x.tryAdvanceToCommited()) { 200 | /* check if we should send a CHECKPOINT message */ 201 | checkpoints.addTransaction(x, x.getResult(), viewNr); 202 | 203 | newCommited(x.getSequenceNr()); 204 | } 205 | 206 | if (x.tryMarkDelete()) { 207 | collClientId.remove(x.getClientOperationId()); 208 | it.remove(); 209 | } 210 | } 211 | x.unlock(); 212 | } 213 | } finally { 214 | this.lockCollections.unlock(); 215 | } 216 | } 217 | 218 | private int getPriorSequenceNumber(String fragmentId) { 219 | int priorSequence = -2; 220 | 221 | /* TODO: there could be sequence commands without fragment (bad timing...) */ 222 | for (Transaction x : this.collSequence.values()) { 223 | if (fragmentId.equals(x.getFragmentId()) || x.getFragmentId() == null) { 224 | priorSequence = Math.max(priorSequence, x.getSequenceNr()); 225 | } 226 | } 227 | 228 | return priorSequence; 229 | } 230 | 231 | public void checkCollections() { 232 | lockCollections.lock(); 233 | try { 234 | if (collClientId.size() >= 100 || collSequence.size() >= 100) { 235 | logger.info("server: {} collClient: {} collSequence: {}", this.replicaId, collClientId.size(), collSequence.size()); 236 | } 237 | } finally { 238 | lockCollections.unlock(); 239 | } 240 | } 241 | 242 | public TransactionManager createNewEra(int era) { 243 | lockCollections.lock(); 244 | 245 | TransactionManager newEra; 246 | try { 247 | newEra = new TransactionManager(replicaId, era, f, callbacks, checkpoints); 248 | 249 | if (this.viewNr <= era) { 250 | logger.warn("already in era {}", era); 251 | } else { 252 | 253 | /* remove all non-client transactions and reset all client-ones */ 254 | for (Transaction t : collSequence.values()) { 255 | newEra.addTransaction(t); 256 | } 257 | } 258 | } finally { 259 | lockCollections.unlock(); 260 | } 261 | 262 | return newEra; 263 | } 264 | 265 | public int getLastCommited() { 266 | return this.lastCommited; 267 | } 268 | 269 | public int getViewNr() { 270 | return this.viewNr; 271 | } 272 | 273 | boolean isPrimary() { 274 | return this.replicaId == (viewNr % (3*f + 1)); 275 | } 276 | 277 | void newCommited(int sequenceNr) { 278 | this.lastCommited = Math.max(sequenceNr, this.lastCommited); 279 | } 280 | 281 | void addTransaction(Transaction t) { 282 | 283 | if (t.hasClientInteraction()) { 284 | 285 | Transaction newT = new Transaction(t.getClientCommand(), replicaId, f, callbacks); 286 | 287 | this.collClientId.put(newT.getClientOperationId(), newT); 288 | this.collSequence.put(newT.getSequenceNr(), newT); 289 | 290 | if (isPrimary()) { 291 | this.callbacks.sendToReplicas(newT.createPreprepareCommand()); 292 | 293 | /* generates pre-prepare commands and sets state to prepared */ 294 | newT.tryAdvanceToPreprepared(true); 295 | } 296 | } else { 297 | /* TODO: create copies of t */ 298 | 299 | /* means that it will be added */ 300 | this.collClientId.put(t.getClientOperationId(), t); 301 | this.collSequence.put(t.getSequenceNr(), t); 302 | } 303 | } 304 | } 305 | -------------------------------------------------------------------------------- /src/main/java/at/archistar/bft/server/Transaction.java: -------------------------------------------------------------------------------- 1 | package at.archistar.bft.server; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import at.archistar.bft.exceptions.InconsistentResultsException; 11 | import at.archistar.bft.messages.AbstractCommand; 12 | import at.archistar.bft.messages.ClientCommand; 13 | import at.archistar.bft.messages.ClientFragmentCommand; 14 | import at.archistar.bft.messages.CommitCommand; 15 | import at.archistar.bft.messages.PrepareCommand; 16 | import at.archistar.bft.messages.PreprepareCommand; 17 | import at.archistar.bft.messages.TransactionResult; 18 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 19 | import java.util.Arrays; 20 | import java.util.Objects; 21 | 22 | /** 23 | * This is used to store transaction information for an operation. It contains a 24 | * simple state model (INCOMING -> PRECOMMITED, COMMITED, JOURNAL) that actually 25 | * mirrors the collection that the transaction is currently in. 26 | * 27 | * TODO: investigate if there's some memory structure that would allow to store 28 | * all transactions within one 'tree' 29 | * 30 | * @author andy 31 | */ 32 | public class Transaction implements Comparable { 33 | 34 | /** those are the possible states a transaction could be in */ 35 | public enum State { 36 | INCOMING, PREPREPARED, PREPARED, COMMITED 37 | }; 38 | 39 | private State state = State.INCOMING; 40 | 41 | /** 42 | * all exchanged precommit commands, should be replicaCount 43 | */ 44 | private Set preparedCmds = new HashSet<>(); 45 | 46 | private Set commitedCmds = new HashSet<>(); 47 | 48 | /** 49 | * the expected error model 50 | */ 51 | private int f = 1; 52 | 53 | private final Logger logger = LoggerFactory.getLogger(Transaction.class); 54 | 55 | /** 56 | * fragment id 57 | */ 58 | private String fragmentid; 59 | 60 | /** 61 | * my sequence number (from primary) 62 | */ 63 | private int sequenceNr; 64 | 65 | /** 66 | * sequence number of previous operation (from primary) 67 | */ 68 | private int priorSequenceNr; 69 | 70 | private String clientOperationId; 71 | 72 | private final ReentrantLock lock = new ReentrantLock(); 73 | 74 | private boolean executed = false; 75 | 76 | private boolean primaryReceived = false; 77 | 78 | private final int replica; 79 | 80 | private ClientCommand clientCmd = null; 81 | 82 | private byte[] result = null; 83 | 84 | private BftEngineCallbacks callbacks = null; 85 | 86 | /** 87 | * output a more readable id for debug output 88 | */ 89 | public String readableId() { 90 | 91 | if (clientCmd == null) { 92 | return "" + this.replica + "/" + this.sequenceNr + "/?/?"; 93 | } else { 94 | return "" + this.replica + "/" + this.sequenceNr + "/" + this.clientCmd.getClientId() + "/" + this.clientCmd.getClientSequence(); 95 | } 96 | } 97 | 98 | public Transaction(AbstractCommand cmd, int replicaId, int f, BftEngineCallbacks callbacks) { 99 | 100 | /* default stuff, valid for all commands */ 101 | this.f = f; 102 | this.replica = replicaId; 103 | this.callbacks = callbacks; 104 | 105 | /* if there's a fragment-id, record it */ 106 | if (cmd instanceof ClientFragmentCommand) { 107 | this.fragmentid = ((ClientFragmentCommand) cmd).getFragmentId(); 108 | } else { 109 | this.fragmentid = null; 110 | } 111 | 112 | if (cmd instanceof PreprepareCommand) { 113 | PreprepareCommand c = (PreprepareCommand) cmd; 114 | this.clientOperationId = c.getClientOperationId(); 115 | this.primaryReceived = true; 116 | this.priorSequenceNr = c.getPriorSequence(); 117 | this.sequenceNr = c.getSequence(); 118 | } else if (cmd instanceof PrepareCommand) { 119 | PrepareCommand c = (PrepareCommand) cmd; 120 | this.clientOperationId = c.getClientOperationId(); 121 | this.priorSequenceNr = -1; 122 | this.sequenceNr = c.getSequence(); 123 | } else if (cmd instanceof ClientCommand) { 124 | this.clientCmd = (ClientCommand) cmd; 125 | this.clientOperationId = this.clientCmd.getClientOperationId(); 126 | } else { 127 | assert (false); 128 | } 129 | } 130 | 131 | private boolean canAdvanceToPreprepared() { 132 | return state == State.INCOMING && clientCmd != null && primaryReceived; 133 | } 134 | 135 | AbstractCommand getClientCommand() { 136 | return this.clientCmd; 137 | } 138 | 139 | private boolean canAdvanceToPrepared(int lastCommited) { 140 | 141 | logger.debug("{}: {} - {} - {}", readableId(), state, preparedCmds.size(), priorSequenceNr == -1 || priorSequenceNr <= lastCommited); 142 | 143 | if (state == State.PREPREPARED && preparedCmds.size() >= 2 * f) { 144 | if (priorSequenceNr == -1 || priorSequenceNr <= lastCommited) { 145 | return true; 146 | } 147 | } 148 | return false; 149 | } 150 | 151 | private boolean canAdvanceToCommited() { 152 | logger.debug("{}: {} - {}/{} - {}/{} - {}", readableId(), state, preparedCmds.size(), commitedCmds.size(), clientCmd != null, primaryReceived, priorSequenceNr); 153 | return state == State.PREPARED && commitedCmds.size() >= (2 * f + 1) && !executed; 154 | } 155 | 156 | public void outputState() { 157 | logger.warn("{}: {} - {}/{} - {}/{} - {}", readableId(), state, preparedCmds.size(), commitedCmds.size(), clientCmd != null, primaryReceived, priorSequenceNr); 158 | } 159 | 160 | /** 161 | * execute operation and return result 162 | */ 163 | private byte[] execute() { 164 | 165 | assert (state == State.PREPARED); 166 | state = State.COMMITED; 167 | 168 | this.executed = true; 169 | return callbacks.executeClientCommand(clientCmd); 170 | } 171 | 172 | public String getFragmentId() { 173 | return this.fragmentid; 174 | } 175 | 176 | public int getSequenceNr() { 177 | return this.sequenceNr; 178 | } 179 | 180 | public int getPriorSequenceNr() { 181 | return this.priorSequenceNr; 182 | } 183 | 184 | public void lock() { 185 | this.lock.lock(); 186 | } 187 | 188 | public void unlock() { 189 | this.lock.unlock(); 190 | } 191 | 192 | public void setDataFromPreprepareCommand(int sequence, int priorSequence) { 193 | this.priorSequenceNr = priorSequence; 194 | this.sequenceNr = sequence; 195 | } 196 | 197 | public PreprepareCommand createPreprepareCommand() { 198 | PreprepareCommand seq = new PreprepareCommand(0, sequenceNr, replica, clientOperationId, priorSequenceNr); 199 | if (this.state == State.INCOMING) { 200 | this.state = State.PREPREPARED; 201 | } else { 202 | assert (false); 203 | } 204 | this.primaryReceived = true; 205 | return seq; 206 | } 207 | 208 | @Override 209 | public int compareTo(Transaction o) { 210 | return sequenceNr - o.getSequenceNr(); 211 | } 212 | 213 | @Override 214 | public boolean equals(Object o) { 215 | if (o instanceof Transaction) { 216 | /* TODO: should we compare the transactions too? */ 217 | return ((Transaction)o).sequenceNr == this.sequenceNr; 218 | } else { 219 | return false; 220 | } 221 | } 222 | 223 | @Override 224 | public int hashCode() { 225 | int hash = 7; 226 | hash = 37 * hash + Objects.hashCode(this.state); 227 | hash = 37 * hash + Objects.hashCode(this.preparedCmds); 228 | hash = 37 * hash + Objects.hashCode(this.commitedCmds); 229 | hash = 37 * hash + this.f; 230 | hash = 37 * hash + Objects.hashCode(this.fragmentid); 231 | hash = 37 * hash + this.sequenceNr; 232 | hash = 37 * hash + this.priorSequenceNr; 233 | hash = 37 * hash + Objects.hashCode(this.clientOperationId); 234 | hash = 37 * hash + (this.executed ? 1 : 0); 235 | hash = 37 * hash + (this.primaryReceived ? 1 : 0); 236 | hash = 37 * hash + this.replica; 237 | hash = 37 * hash + Objects.hashCode(this.clientCmd); 238 | hash = 37 * hash + Arrays.hashCode(this.result); 239 | return hash; 240 | } 241 | 242 | public boolean tryMarkDelete() { 243 | if (state == State.COMMITED && commitedCmds.size() == (3 * f + 1)) { 244 | logger.debug("{} advance commited -> to-delete", readableId()); 245 | return true; 246 | } else { 247 | return false; 248 | } 249 | } 250 | 251 | public void setPrepreparedReceived() { 252 | this.primaryReceived = true; 253 | } 254 | 255 | public void addPrepareCommand(PrepareCommand c) throws InconsistentResultsException { 256 | /* verify that the digest matches */ 257 | if (this.preparedCmds.size() > 0) { 258 | for (PrepareCommand i : preparedCmds) { 259 | if (!c.getClientOperationId().equalsIgnoreCase(i.getClientOperationId())) { 260 | throw new InconsistentResultsException(); 261 | } 262 | } 263 | } 264 | 265 | this.preparedCmds.add(c); 266 | } 267 | 268 | public void addCommitCommand(CommitCommand cmd) { 269 | this.commitedCmds.add(cmd); 270 | } 271 | 272 | public void addClientCommand(ClientCommand cmd) { 273 | this.clientCmd = cmd; 274 | if (cmd instanceof ClientFragmentCommand) { 275 | this.fragmentid = ((ClientFragmentCommand) cmd).getFragmentId(); 276 | } 277 | } 278 | 279 | public Set getPreparedCommands() { 280 | return this.preparedCmds; 281 | } 282 | 283 | public Set getCommitedCommands() { 284 | return this.commitedCmds; 285 | } 286 | 287 | public void setClientOperationId(String clientOperationId) { 288 | this.clientOperationId = clientOperationId; 289 | } 290 | 291 | public String getClientOperationId() { 292 | return this.clientOperationId; 293 | } 294 | 295 | public void tryAdvanceToPreprepared(boolean primary) { 296 | if (canAdvanceToPreprepared()) { 297 | logger.debug("{} advance incoming -> (pre-)prepared", readableId()); 298 | 299 | assert (this.state == State.INCOMING); 300 | if (primary) { 301 | /* primary can directly jump to prepared */ 302 | this.state = State.PREPARED; 303 | } else { 304 | PrepareCommand cmd = new PrepareCommand(0, sequenceNr, replica, clientOperationId); 305 | this.preparedCmds.add(cmd); 306 | this.state = State.PREPREPARED; 307 | callbacks.sendToReplicas(cmd); 308 | } 309 | } 310 | } 311 | 312 | public boolean tryAdvanceToPrepared(int lastCommited) { 313 | if (canAdvanceToPrepared(lastCommited)) { 314 | logger.debug("{} advance prepared -> precommited", replica, readableId()); 315 | 316 | CommitCommand cmd = new CommitCommand(0, sequenceNr, replica); 317 | this.commitedCmds.add(cmd); 318 | 319 | assert (this.state == State.PREPREPARED); 320 | this.state = State.PREPARED; 321 | 322 | callbacks.sendToReplicas(cmd); 323 | return true; 324 | } else { 325 | return false; 326 | } 327 | } 328 | 329 | public boolean tryAdvanceToCommited() { 330 | if (canAdvanceToCommited()) { 331 | logger.debug("{} advance precommited -> commited", readableId()); 332 | result = execute(); 333 | this.callbacks.answerClient(new TransactionResult(this.clientCmd, this.replica, result)); 334 | return true; 335 | } else { 336 | return false; 337 | } 338 | } 339 | 340 | @SuppressFBWarnings("EI_EXPOSE_REP") 341 | public byte[] getResult() { 342 | return this.result; 343 | } 344 | 345 | public boolean hasClientInteraction() { 346 | return clientCmd != null; 347 | } 348 | 349 | public void reset() { 350 | this.state = State.INCOMING; 351 | this.preparedCmds.clear(); 352 | this.commitedCmds.clear(); 353 | this.primaryReceived = false; 354 | } 355 | 356 | public void merge(Transaction tmp) { 357 | tmp.lock(); 358 | setDataFromPreprepareCommand(tmp.getSequenceNr(), tmp.getPriorSequenceNr()); 359 | preparedCmds = tmp.getPreparedCommands(); 360 | commitedCmds = tmp.getCommitedCommands(); 361 | tmp.unlock(); 362 | } 363 | } 364 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | {signature of Ty Coon}, 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | --------------------------------------------------------------------------------