diff --git a/.gitignore b/.gitignore index a1c2a23..2fef4bb 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,7 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +.idea/ + +target/ \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..80e76da --- /dev/null +++ b/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + blockchains.iaas.uni.stuttgart.de + blockchain-access-layer-api + 1.0.1-SNAPSHOT + + + 8 + 8 + 0.10 + 1.7.25 + UTF-8 + + + + + org.pf4j + pf4j + 3.6.0 + + + com.github.arteam + simple-json-rpc-server + ${jsonrpc.version} + + + org.slf4j + slf4j-api + + + com.google.guava + guava + + + + + com.github.arteam + simple-json-rpc-client + ${jsonrpc.version} + + + org.slf4j + slf4j-api + + + + + org.projectlombok + lombok + 1.18.8 + provided + + + com.google.guava + guava + 26.0-android + + + + javax.json + javax.json-api + 1.1.4 + + + io.reactivex.rxjava2 + rxjava + 2.2.21 + + + \ No newline at end of file diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/IAdapterExtenstion.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/IAdapterExtenstion.java new file mode 100644 index 0000000..faf9df4 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/IAdapterExtenstion.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * Copyright (c) 2022 Institute for the Architecture of Application System - University of Stuttgart + * Author: Akshay Patel + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api; + +import blockchains.iaas.uni.stuttgart.de.api.interfaces.BlockchainAdapter; +import org.pf4j.ExtensionPoint; + +import java.util.Map; + +public interface IAdapterExtenstion extends ExtensionPoint { + BlockchainAdapter getAdapter(Map parameters); + + String getBlockChainId(); +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/connectionprofiles/AbstractConnectionProfile.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/connectionprofiles/AbstractConnectionProfile.java new file mode 100644 index 0000000..f840084 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/connectionprofiles/AbstractConnectionProfile.java @@ -0,0 +1,59 @@ +/******************************************************************************** + * Copyright (c) 2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.connectionprofiles; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import java.util.Properties; + +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME) +public abstract class AbstractConnectionProfile { + private static final String PREFIX = "common."; + private static final String ADVERSARY_VOTING_RATIO = PREFIX + "adversaryVotingRatio"; + private double adversaryVotingRatio; + + public double getAdversaryVotingRatio() { + return adversaryVotingRatio; + } + + public void setAdversaryVotingRatio(double adversaryVotingRatio) { + if (adversaryVotingRatio < 0 || adversaryVotingRatio > 1.0) { + throw new IllegalArgumentException("Voting power of adversary should be between 0.0 and 1.0, but (" + + adversaryVotingRatio + ") is passed!"); + } + + this.adversaryVotingRatio = adversaryVotingRatio; + } + + public Properties getAsProperties() { + Properties result = new Properties(); + result.put(ADVERSARY_VOTING_RATIO, String.valueOf(adversaryVotingRatio)); + + return result; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AbstractConnectionProfile that = (AbstractConnectionProfile) o; + return this.getAsProperties().equals(that.getAsProperties()); + } + + @Override + public int hashCode() { + return this.getAsProperties().hashCode(); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BalException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BalException.java new file mode 100644 index 0000000..50be7d4 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BalException.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +public abstract class BalException extends RuntimeException { + + public BalException() { + } + + public BalException(String message) { + super(message); + } + + public BalException(String message, Throwable cause) { + super(message, cause); + } + + public BalException(Throwable cause) { + super(cause); + } + + public abstract int getCode(); +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainIdNotFoundException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainIdNotFoundException.java new file mode 100644 index 0000000..fbe99d7 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainIdNotFoundException.java @@ -0,0 +1,31 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.NotFound, message = "The specified blockchain-id cannot be found") +public class BlockchainIdNotFoundException extends BalException { + + public BlockchainIdNotFoundException() { + super(); + } + + public BlockchainIdNotFoundException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.NotFound; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainNodeUnreachableException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainNodeUnreachableException.java new file mode 100644 index 0000000..7579ec3 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/BlockchainNodeUnreachableException.java @@ -0,0 +1,30 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.ConnectionException, message = "The blockchain node cannot be reached.") +public class BlockchainNodeUnreachableException extends BalException { + + public BlockchainNodeUnreachableException() { + } + + public BlockchainNodeUnreachableException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.ConnectionException; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ExceptionCode.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ExceptionCode.java new file mode 100644 index 0000000..27381a7 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ExceptionCode.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +public class ExceptionCode { + public static final int UnknownError = 0; + + /** + * The blockchain instance, smart contract, event or function are not found + */ + public static final int NotFound = -32000; + /** + * Input parameter types, names, or order mismatch the designated function or event. + * This also indicates inability to map a parameter's abstract type to a native type. + */ + public static final int InvalidParameters = -32001; + /** + * Client certificate is missing + */ + public static final int MissingCertificate = -32002; + /** + * The client application is not authorized to perform the requested task. + * Gateway-side authorization. + */ + public static final int NotAuthorized = -32003; + /** + * The specified blockchain instance does not support the requested operation. + */ + public static final int NotSupported = -32004; + /** + * Connection to the underlying blockchain node is not possible. + */ + public static final int ConnectionException = -32005; + /** + * The transaction associated with an function invocation is invalidated after it was mined. + */ + public static final int TransactionInvalidatedException = -32006; + + /** + * A scip method parameter has an invalid value + */ + public static final int InvalidScipParam = -32007; + + /** + * A general error occurred when trying to invoke a smart contract function + * This error is used when the specific cause of the error cannot be deteremined. + */ + public static final int InvocationError = -32100; + /** + * The smart contract function threw an exception + */ + public static final int ExecutionError = -32101; + /** + * Not enough funds to invoke the state-changing smart contract funciton. + */ + public static final int InsufficientFunds = -32102; + /** + * The BAL instance is not authorized to performed the requested operation on the underlying blockchain. + */ + public static final int BalNotAuthorized = -32103; + + /** + * Timeout is reached before fulfilling the desired degree of confidence. + * This is an asynchronous error. + */ + public static final int Timeout = -32201; +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidScipParameterException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidScipParameterException.java new file mode 100644 index 0000000..87b53a0 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidScipParameterException.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.InvalidScipParam, message = "A scip method parameter has an invalid value.") +public class InvalidScipParameterException extends BalException { + @Override + public int getCode() { + return ExceptionCode.InvalidScipParam; + } + + public InvalidScipParameterException() { + } + + public InvalidScipParameterException(String message) { + super(message); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidTransactionException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidTransactionException.java new file mode 100644 index 0000000..86ac8a6 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvalidTransactionException.java @@ -0,0 +1,30 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.InvocationError, message = "An error occurred while trying to invoke the smart contract function.") +public class InvalidTransactionException extends BalException { + + public InvalidTransactionException() { + } + + public InvalidTransactionException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.InvocationError; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvokeSmartContractFunctionFailure.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvokeSmartContractFunctionFailure.java new file mode 100644 index 0000000..3d3a059 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/InvokeSmartContractFunctionFailure.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.ExecutionError, message = "The execution of the smart contract function resulted in an error.") +public class InvokeSmartContractFunctionFailure extends BalException { + public InvokeSmartContractFunctionFailure() { + } + + public InvokeSmartContractFunctionFailure(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.ExecutionError; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ManualUnsubscriptionException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ManualUnsubscriptionException.java new file mode 100644 index 0000000..5f83b12 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ManualUnsubscriptionException.java @@ -0,0 +1,22 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +public class ManualUnsubscriptionException extends RuntimeException { + public ManualUnsubscriptionException() { + super(); + } + + public ManualUnsubscriptionException(String message) { + super(message); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/NotSupportedException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/NotSupportedException.java new file mode 100644 index 0000000..5441590 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/NotSupportedException.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.NotSupported, message = "The requested operation is not supported by the underlying blockchain instance.") +public class NotSupportedException extends BalException { + public NotSupportedException() { + } + + public NotSupportedException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.NotSupported; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ParameterException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ParameterException.java new file mode 100644 index 0000000..9ba3bd3 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/ParameterException.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.InvalidParameters, message = "The passed function/event parameter names, order, or types are invalid.") +public class ParameterException extends BalException { + public ParameterException() { + } + + public ParameterException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.InvalidParameters; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/SmartContractNotFoundException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/SmartContractNotFoundException.java new file mode 100644 index 0000000..2825e54 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/SmartContractNotFoundException.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.NotFound, message = "The specified smart contract is not found.") +public class SmartContractNotFoundException extends BalException { + public SmartContractNotFoundException() { + } + + public SmartContractNotFoundException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.NotFound; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TimeoutException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TimeoutException.java new file mode 100644 index 0000000..edf8b5d --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TimeoutException.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; +import lombok.Getter; +import lombok.Setter; + +@JsonRpcError(code = ExceptionCode.Timeout, message = "Timeout was reached before the desired DoC was fulfilled.") +@Setter +@Getter +public class TimeoutException extends BalException { + private String transactionHash; + private double doc; + + public TimeoutException() { + } + + public TimeoutException(String message, String transactionHash, double doc) { + super(message); + this.transactionHash = transactionHash; + this.doc = doc; + } + + @Override + public int getCode() { + return ExceptionCode.Timeout; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TransactionNotFoundException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TransactionNotFoundException.java new file mode 100644 index 0000000..2029d4a --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/TransactionNotFoundException.java @@ -0,0 +1,30 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.TransactionInvalidatedException, message = "The transaction associated with an function invocation is invalidated after it was mined.") +public class TransactionNotFoundException extends BalException { + + public TransactionNotFoundException() { + } + + public TransactionNotFoundException(String message) { + super(message); + } + + @Override + public int getCode() { + return ExceptionCode.TransactionInvalidatedException; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/UnknownException.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/UnknownException.java new file mode 100644 index 0000000..6af5f6d --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/exceptions/UnknownException.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.exceptions; + +import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcError; + +@JsonRpcError(code = ExceptionCode.UnknownError, message = "Unknown server error occurred.") +public class UnknownException extends BalException { + @Override + public int getCode() { + return ExceptionCode.UnknownError; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/BlockchainAdapter.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/BlockchainAdapter.java new file mode 100644 index 0000000..4b43213 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/BlockchainAdapter.java @@ -0,0 +1,124 @@ +/******************************************************************************** + * Copyright (c) 2018-2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.interfaces; + +import blockchains.iaas.uni.stuttgart.de.api.exceptions.BalException; +import blockchains.iaas.uni.stuttgart.de.api.exceptions.InvalidTransactionException; +import blockchains.iaas.uni.stuttgart.de.api.exceptions.NotSupportedException; +import blockchains.iaas.uni.stuttgart.de.api.model.*; +import io.reactivex.Observable; + +import java.math.BigDecimal; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public interface BlockchainAdapter { + /** + * submits a transaction to the blockchain that transfers an amount of the native crypto-currency to some address. + * + * @param requiredConfidence the degree-of-confidence required to be achieved before sending a callback message to the invoker. + * @param receiverAddress the address of the receiver + * @param value the value to transfer measured in the most granular unit, e.g., wei, satoshi + * @return a completable future that emits a summary of the submitted transaction. + * The future should normally complete with a transaction of the state CONFIRMED if the desired number of block-confirmations were received, + * and with a transaction of the state NOT_FOUND if the transaction was committed to a block and then orphaned and invalidated. + * The future should exceptionally complete with an exception of type BlockchainNodeUnreachableException if the blockchain node is not reachable, + * and with an exception of type InvalidTransactionException if the transaction is initially invalid (e.g., malformed) + * @throws InvalidTransactionException if the submitted transaction causes an immediate validation error, e.g., + * insufficient funds, or incorrect receiverAddress (this seems to never be thrown) + */ + CompletableFuture submitTransaction(String receiverAddress, BigDecimal value, double requiredConfidence) throws InvalidTransactionException, NotSupportedException; + + /** + * receives transactions addressed to us (potentially from a specific sender) + * + * @param requiredConfidence the degree-of-confidence required to be achieved before sending a callback message to the invoker. + * @param senderId an optional address of the sender. If specified, only transactions from this sender are considered + * @return an observable that emits a summary of the received transaction whenever one is detected + */ + Observable receiveTransactions(String senderId, double requiredConfidence) throws NotSupportedException; + + /** + * ensures that a transaction receives enough block-confirmations + * + * @param requiredConfidence the degree-of-confidence required to be achieved before sending a callback message to the invoker. + * @param transactionId the hash of the transaction we want to monitor + * @return a completable future that emits the new state of the transaction (either COFIRMED in case the desired + * number of block-confirmations got received, or NOT_FOUND if the transaction got invalidated). + * The future should exceptionally complete with an exception of type BlockchainNodeUnreachableException if the blockchain node is not reachable + */ + CompletableFuture ensureTransactionState(String transactionId, double requiredConfidence) throws NotSupportedException; + + /** + * detects that the given transaction got orphaned + * + * @param transactionId the hash of the transaction we want to monitor + * @return a completable future that emits the new state of the transaction (PENDING meaning that it no longer has a + * block, i.e., it is orphaned) + * The future should exceptionally complete with an exception of type BlockchainNodeUnreachableException if the blockchain node is not reachable + */ + CompletableFuture detectOrphanedTransaction(String transactionId) throws NotSupportedException; + + /** + * invokes a smart contract function + * + * @param smartContractPath the path to the smart contract + * @param functionIdentifier the function name + * @param inputs the input parameters of the function to be invoked + * @param outputs the output parameters of the function to be invoked + * @param requiredConfidence the degree-of-confidence required to be achieved before sending a callback message to the invoker. + * @return a completable future that emits a new transaction object holding the result of the invocation. + * @throws NotSupportedException if the underlying blockchain system does not support smart contracts. + */ + CompletableFuture invokeSmartContract( + String smartContractPath, + String functionIdentifier, + List inputs, + List outputs, + double requiredConfidence + ) throws BalException; + + /** + * Monitors the occurrences of a given blockchain event. + * + * @param smartContractAddress the address of the smart contract that contains the event. + * @param eventIdentifier the name of the event to be monitored. + * @param outputParameters the list of output parameter names and types of the event to be monitored. + * @param degreeOfConfidence the degree of confidence required for the transactions triggering the events. + * @param filter C-style filter for the events that uses the output parameters. + * @return An observable that emits matching occurrences. + */ + Observable subscribeToEvent(String smartContractAddress, String eventIdentifier, + List outputParameters, + double degreeOfConfidence, + String filter) throws BalException; + + /** + * Queries previous occurrences of a given blockchain event + * + * @param smartContractAddress the address of the smart contract that contains the event. + * @param eventIdentifier the name of the event to be monitored. + * @param outputParameters the list of output parameter names and types of the event to be monitored. + * @param filter C-style filter for the events that uses the output parameters. + * @param timeFrame The timeFrame in which to consider event occurrences. + * @return A completable future containing a list of matching occurrences. + */ + CompletableFuture queryEvents(String smartContractAddress, String eventIdentifier, List outputParameters, + String filter, TimeFrame timeFrame) throws BalException; + /** + * Tests the connection settings with the underlying blockchain + * + * @return true if the connection is successful, an error message otherwise. + */ + String testConnection(); +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/FinalityConfidenceCalculator.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/FinalityConfidenceCalculator.java new file mode 100644 index 0000000..d3073d0 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/interfaces/FinalityConfidenceCalculator.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.interfaces; + +import blockchains.iaas.uni.stuttgart.de.api.model.LinearChainTransaction; + +/** + * Calculates the DoC of a transaction + */ +public interface FinalityConfidenceCalculator { + double getCurrentConfidence(LinearChainTransaction transaction); +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Block.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Block.java new file mode 100644 index 0000000..da70b14 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Block.java @@ -0,0 +1,60 @@ +package blockchains.iaas.uni.stuttgart.de.api.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.math.BigInteger; + +/******************************************************************************** + * Copyright (c) 2018 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +@XmlRootElement(name="Block") +@XmlAccessorType(XmlAccessType.NONE) +public class Block { + private BigInteger number; + private String hash; + + public Block(){ + + } + + public Block(BigInteger number, String hash) { + this.number = number; + this.hash = hash; + } + + public BigInteger getNumber() { + return number; + } + + public void setNumber(BigInteger number) { + this.number = number; + } + + @XmlElement(name="BlockNumber") + public long getNumberAsLong(){ + return this.number.longValue(); + } + + public void setNumberAsLong(long value){ + this.number = BigInteger.valueOf(value); + } + + @XmlElement(name="BlockHash") + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/LinearChainTransaction.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/LinearChainTransaction.java new file mode 100644 index 0000000..48ffc63 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/LinearChainTransaction.java @@ -0,0 +1,105 @@ +package blockchains.iaas.uni.stuttgart.de.api.model; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.math.BigInteger; +import java.util.List; + +/******************************************************************************** + * Copyright (c) 2018 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +@XmlRootElement(name="Transaction") +@XmlAccessorType(XmlAccessType.NONE) +public class LinearChainTransaction extends Transaction { + + @XmlElement(name="TransactionHash") + private String transactionHash; + + @XmlElement + private Block block; + + @XmlElement(name="From") + private String from; + + @XmlElement(name="To") + private String to; + + private BigInteger value; + + public LinearChainTransaction() { + super(); + } + + public LinearChainTransaction(String transactionHash, + Block block, + String from, String to, BigInteger value, TransactionState state, List returnValues) { + this.setReturnValues(returnValues); + this.setState(state); + this.transactionHash = transactionHash; + this.block = block; + this.from = from; + this.to = to; + this.value = value; + } + + public String getTransactionHash() { + return transactionHash; + } + + public void setTransactionHash(String transactionHash) { + this.transactionHash = transactionHash; + } + + public Block getBlock() { + return block; + } + + public void setBlock(Block block) { + this.block = block; + } + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public BigInteger getValue() { + return value; + } + + public void setValue(BigInteger value) { + this.value = value; + } + + @XmlElement(name="Value") + public String getValueAsString(){ + return value.toString(); + } + + public void setValueAsString(String value){ + this.value = new BigInteger(value); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Occurrence.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Occurrence.java new file mode 100644 index 0000000..49cce48 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Occurrence.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.model; + +import blockchains.iaas.uni.stuttgart.de.api.utils.TimeUtils; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; + +import java.time.LocalDateTime; +import java.util.List; + +@Builder +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class Occurrence { + List parameters; + String isoTimestamp; + + @JsonIgnore + public LocalDateTime getTimestampObject() { + return TimeUtils.getTimestampObject(isoTimestamp); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Parameter.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Parameter.java new file mode 100644 index 0000000..2e8d626 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Parameter.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.model; + +import lombok.*; + +@Setter +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Parameter { + private String name; + private String type; + private String value; +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/QueryResult.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/QueryResult.java new file mode 100644 index 0000000..1b1b067 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/QueryResult.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.model; + +import lombok.*; + +import java.util.List; + +@Builder +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class QueryResult { + private List occurrences; +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TimeFrame.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TimeFrame.java new file mode 100644 index 0000000..97a468c --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TimeFrame.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.model; + +import blockchains.iaas.uni.stuttgart.de.api.utils.TimeUtils; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; + +import java.time.LocalDateTime; + +@Builder +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class TimeFrame { + private String from; + private String to; + + @JsonIgnore + public LocalDateTime getFromLocalDateTime() { + return TimeUtils.getTimestampObject(from); + } + + @JsonIgnore + public LocalDateTime getToLocalDateTime() { + return TimeUtils.getTimestampObject(to); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Transaction.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Transaction.java new file mode 100644 index 0000000..aa7f1fe --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/Transaction.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.model; + +import lombok.Data; + +import javax.xml.bind.annotation.XmlElement; +import java.util.List; + +@Data +public class Transaction { + @XmlElement(name = "TransactionState") + private TransactionState state; + + @XmlElement(name = "ReturnValues") + private List returnValues; +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TransactionState.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TransactionState.java new file mode 100644 index 0000000..59f1615 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/model/TransactionState.java @@ -0,0 +1,25 @@ +/******************************************************************************** + * Copyright (c) 2019 Institute for the Architecture of Application System - + * University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "State") +public enum TransactionState { + UNKNOWN, + PENDING, + CONFIRMED, + NOT_FOUND, + INVALID, + // transactions which are only place holders for read-only function invocation result + RETURN_VALUE +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/BooleanExpressionEvaluator.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/BooleanExpressionEvaluator.java new file mode 100644 index 0000000..80ccb85 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/BooleanExpressionEvaluator.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import blockchains.iaas.uni.stuttgart.de.api.model.Parameter; +import com.google.common.base.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.util.List; + +public class BooleanExpressionEvaluator { + private static final Logger log = LoggerFactory.getLogger(BooleanExpressionEvaluator.class); + + public static boolean evaluate(String expression, List parameters) throws Exception { + if (Strings.isNullOrEmpty(expression)) { + return true; + } + + ScriptEngineManager mgr = new ScriptEngineManager(); + ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); + + for (Parameter param : parameters) { + jsEngine.put(param.getName(), JsonSchemaToJavaTypeMapper.map(param)); + } + + log.info("Executing in script environment..."); + + try { + Object result = jsEngine.eval(expression); + if (result instanceof Boolean) { + return (Boolean) result; + } else { + throw new RuntimeException(String.format("The expression evaluated to type: %s, but a boolean value was expected!", result.getClass().getName())); + } + } catch (ScriptException ex) { + log.error("Failed to execute boolean expression {}. Reason: {}.", expression, ex.getMessage()); + throw ex; + } + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/JsonSchemaToJavaTypeMapper.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/JsonSchemaToJavaTypeMapper.java new file mode 100644 index 0000000..af73c74 --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/JsonSchemaToJavaTypeMapper.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import blockchains.iaas.uni.stuttgart.de.api.exceptions.BalException; +import blockchains.iaas.uni.stuttgart.de.api.exceptions.ParameterException; +import blockchains.iaas.uni.stuttgart.de.api.model.Parameter; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.xml.bind.DatatypeConverter; +import java.io.ByteArrayInputStream; +import java.util.Arrays; + +public class JsonSchemaToJavaTypeMapper { + + public static Object map(Parameter parameter) throws BalException { + try { + JsonObject jsonObject = Json.createReader(new ByteArrayInputStream(parameter.getType().getBytes())).readObject(); + + return map(jsonObject, parameter.getValue()); + } catch (Exception e) { + if (!(e instanceof BalException)) + throw new ParameterException(e.getMessage()); + + throw (BalException) e; + } + } + + private static Object map(JsonObject jsonObject, String value) { + + String type = jsonObject.getString("type"); + + if (type.equals("boolean")) { + return Boolean.parseBoolean(value); + } + + if (type.equals("string")) { + if (jsonObject.containsKey("pattern") && jsonObject.getString("pattern").equals("^[a-fA-F0-9]{2}$")) { + byte[] bytes = DatatypeConverter.parseHexBinary(value); + + if (bytes.length == 1) { + return bytes[0]; + } + + throw new ParameterException("Invalid byte array: " + value); + } + + return value; + } + + if (type.equals("integer")) { + return Long.parseLong(value); + } + + if (type.equals("number")) { + return Double.parseDouble(value); + } + + if (type.equals("array")) { + return handleArrayType(jsonObject, value); + } + + throw new ParameterException("Unrecognized type!"); + } + + // todo this will not work with ethereum byte array types! + private static Object handleArrayType(JsonObject outerJsonObject, String value) { + if (outerJsonObject.containsKey("items")) { + // get the "items" schema, tuples are not yet supported! + JsonObject jsonObject = outerJsonObject.getJsonObject("items"); + + // not an empty array! + if (value.length() > 2) { + String[] values = value.substring(1, value.length() - 1).split(","); + + return Arrays.stream(values).map(current -> map(jsonObject, current)).toArray(); + } + } + + throw new ParameterException("Unrecognized array type!"); + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/MathUtils.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/MathUtils.java new file mode 100644 index 0000000..21cd3fd --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/MathUtils.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import com.google.common.math.BigIntegerMath; +import com.google.common.math.LongMath; + +import java.math.BigInteger; +import java.math.RoundingMode; + +public class MathUtils { + public static final double ACCEPTED_DOUBLE_ERROR = 0.000001; + public static long factorial(int n) { + return LongMath.factorial(n); + } + public static int log2(BigInteger n) throws ArithmeticException { + return BigIntegerMath.log2(n, RoundingMode.UNNECESSARY); + } + + public static int doubleCompare(double lhs, double rhs) { + if (Math.abs(lhs-rhs) < ACCEPTED_DOUBLE_ERROR) + return 0; + if(lhs-rhs > ACCEPTED_DOUBLE_ERROR) + return 1; + return -1; + } + + +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/PoWConfidenceCalculator.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/PoWConfidenceCalculator.java new file mode 100644 index 0000000..7af226e --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/PoWConfidenceCalculator.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import blockchains.iaas.uni.stuttgart.de.api.interfaces.FinalityConfidenceCalculator; +import blockchains.iaas.uni.stuttgart.de.api.model.LinearChainTransaction; + +public class PoWConfidenceCalculator implements FinalityConfidenceCalculator { + private long currentBlockchainHeight; + private double adversaryRatio; + + public double getAdversaryRatio() { + return adversaryRatio; + } + + public void setAdversaryRatio(double adversaryRatio) { + if (adversaryRatio >= 0.0 && adversaryRatio <= 1.0) { + this.adversaryRatio = adversaryRatio; + } else { + throw new IllegalArgumentException("Adversary ratio must be between 0.0 and 1.0!"); + } + } + + public long getCurrentBlockchainHeight() { + return currentBlockchainHeight; + } + + public void setCurrentBlockchainHeight(long currentBlockchainHeight) { + this.currentBlockchainHeight = currentBlockchainHeight; + } + + /** + * Uses the equation from the Bitcoin whitepaper to calculate the degree-of-confidence + * + * @param transaction the transaction to calculate the current confidence for. + * @return the current DoC measured between 0.0 and 1.0 + */ + @Override + public double getCurrentConfidence(LinearChainTransaction transaction) { + final long z = this.currentBlockchainHeight - transaction.getBlock().getNumberAsLong(); + return this.getConfidence(z); + } + + public long getEquivalentBlockDepth(double requiredConfidence) { + long z = 0; + double currentConfidence = 0.0; + + while (currentConfidence < requiredConfidence) { + currentConfidence = getConfidence(z); + ++z; + } + + return z; + } + + private double getConfidence(long z) { + final double q = this.adversaryRatio; + + if (z < 0.0) { + throw new RuntimeException("currentBlockchainHeight is smaller than the block height of the transaction!"); + } + + final double lambda = z * (q / (1 - q)); + double accumulator = 0.0; + double part1; + double part2; + + for (int k = 0; k < z; k++) { + part1 = (Math.pow(lambda, k) * Math.exp(-lambda)) / MathUtils.factorial(k); + part2 = 1 - Math.pow(q / (1 - q), z - k); + accumulator += part1 * part2; + } + + return accumulator; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/SmartContractPathParser.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/SmartContractPathParser.java new file mode 100644 index 0000000..922facf --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/SmartContractPathParser.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import lombok.Data; + +@Data +public class SmartContractPathParser { + private final String path; + private String[] smartContractPathSegments; + + private SmartContractPathParser(String path) { + this.path = path; + } + + private void parse() { + this.smartContractPathSegments = path.split("/"); + } + + public static SmartContractPathParser parse(String smartContractPath) { + final SmartContractPathParser result = new SmartContractPathParser(smartContractPath); + result.parse(); + + return result; + } +} diff --git a/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/TimeUtils.java b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/TimeUtils.java new file mode 100644 index 0000000..88bae7e --- /dev/null +++ b/src/main/java/blockchains/iaas/uni/stuttgart/de/api/utils/TimeUtils.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2019 Institute for the Architecture of Application System - University of Stuttgart + * Author: Ghareeb Falazi + * + * This program and the accompanying materials are made available under the + * terms the Apache Software License 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + *******************************************************************************/ + +package blockchains.iaas.uni.stuttgart.de.api.utils; + +import com.google.common.base.Strings; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class TimeUtils { + + public static LocalDateTime getTimestampObject(String isoTimestamp) { + if (!Strings.isNullOrEmpty(isoTimestamp)) { + return LocalDateTime.parse(isoTimestamp, DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + + return null; + } +}