Merge branch 'develop'

This commit is contained in:
GME 2018-11-17 18:30:16 +01:00
commit d127499a32
58 changed files with 1304 additions and 0 deletions

83
.gitignore vendored Normal file
View file

@ -0,0 +1,83 @@
# Created by https://www.gitignore.io/api/intellij
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
# End of https://www.gitignore.io/api/intellij

13
.idea/compiler.xml Normal file
View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="java-api" />
</profile>
</annotationProcessing>
</component>
</project>

6
.idea/encodings.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$" charset="UTF-8" />
</component>
</project>

14
.idea/misc.xml Normal file
View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

BIN
msp/org1/User-org1.context Normal file

Binary file not shown.

BIN
msp/org1/admin.context Normal file

Binary file not shown.

BIN
msp/toto/abdel.context Normal file

Binary file not shown.

74
pom.xml Normal file
View file

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.monnethic</groupId>
<artifactId>java-api</artifactId>
<version>0.1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<!-- HYPERLEDGER -->
<dependency>
<groupId>org.hyperledger.fabric-sdk-java</groupId>
<artifactId>fabric-sdk-java</artifactId>
<version>1.2.1</version>
</dependency>
<!-- ***** -->
<!-- SPRING FRAMEWORK -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- ***** -->
<!-- LOGGER AND TEST DEPENDENCIES -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- ***** -->
<!-- CRYPTO CONFIG -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
</dependency>
<!-- ***** -->
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,31 @@
package Application;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
import java.util.Collections;
@SpringBootApplication
public class App {
public static void main(String [ ] args){
SpringApplication app = new SpringApplication(App.class);
app.setDefaultProperties(Collections.singletonMap("server.port","8083"));
app.run(args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx){
return args -> {
System.out.println("Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}

View file

@ -0,0 +1,105 @@
package blockchain.client;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.hyperledger.fabric_ca.sdk.RegistrationRequest;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.util.Properties;
public class CAClientWrapper {
private static Logger logger = Logger.getLogger(CAClientWrapper.class);
private String caUrl;
private Properties properties;
private HFCAClient hfcaClient;
private UserContext adminContext;
public void setAdminContext(UserContext adminContext) { this.adminContext = adminContext; }
public UserContext getAdminContext(){ return adminContext; }
public HFCAClient getHfcaClient(){
return hfcaClient;
}
public CAClientWrapper(String caUrl, Properties properties) throws MalformedURLException, IllegalAccessException, InstantiationException, ClassNotFoundException, CryptoException, InvalidArgumentException, NoSuchMethodException, InvocationTargetException {
this.caUrl=caUrl;
this.properties=properties;
init();
}
private void init() throws MalformedURLException, IllegalAccessException, InstantiationException, ClassNotFoundException, CryptoException, InvalidArgumentException, NoSuchMethodException, InvocationTargetException {
BasicConfigurator.configure();
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
hfcaClient = HFCAClient.createNewInstance(caUrl, properties);
hfcaClient.setCryptoSuite(cryptoSuite);
}
public UserContext enrollAdmin(String username, String password, String affiliation) throws Exception{
BasicConfigurator.configure();
UserContext checkAdmin;
checkAdmin = Util.readUserContext(affiliation, username);
//SANITY CHECK
if(adminContext.getName().isEmpty()) throw new NullPointerException();
if(checkAdmin!=null){
logger.warn("Admin already enrolled, skip");
return checkAdmin;
}
logger.info("Try hfcaClient.enroll");
Enrollment enrollment = hfcaClient.enroll(username,password);
logger.info("Admin enrolled");
adminContext.setEnrollment(enrollment);
logger.info("Write admin in msp directory");
Util.writeUserContext(adminContext);
return adminContext;
}
//Method to register an User
public String registerUser(String username, String organization) throws Exception {
UserContext userContext = Util.readUserContext(organization, username);
if (userContext!=null){
logger.warn("User already registered");
return null;
}
RegistrationRequest rr = new RegistrationRequest(username,organization);
logger.info("registrar is : "+adminContext.getName());
String enrollementSecret = hfcaClient.register(rr,adminContext);
logger.info("User registered");
return enrollementSecret;
}
//Method to enroll an User
public UserContext enrollUser(UserContext userContext, String secret) throws Exception{
UserContext uContext = Util.readUserContext(userContext.getAffiliation(),userContext.getName());
if(uContext!=null){
logger.warn("User already enrolled");
return uContext;
}
Enrollment enrollment = hfcaClient.enroll(userContext.getName(),secret);
userContext.setEnrollment(enrollment);
Util.writeUserContext(userContext);
logger.info("User enrolled");
return userContext;
}
//Method to revoke an User
public void revokeUser(UserContext admin, Enrollment userEnrollement, String reason) throws Exception{
hfcaClient.revoke(admin,userEnrollement,reason);
}
}

View file

@ -0,0 +1,99 @@
package blockchain.client;
import blockchain.configuration.Config;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class ChannelClientWrapper {
private String name;
static private Channel channel;
private FabricClientWrapper fabricClientWrapper;
public String getName(){
return name;
}
public Channel getChannel(){
return channel;
}
public FabricClientWrapper getFabricClientWrapper(){
return fabricClientWrapper;
}
public ChannelClientWrapper(String name, Channel channel, FabricClientWrapper fabricClientWrapper){
this.name=name;
this.channel=channel;
this.fabricClientWrapper=fabricClientWrapper;
}
public Collection<ProposalResponse> queryByChainCode(String chaincodeName,String fuctionName, String[] args) throws InvalidArgumentException, ProposalException {
QueryByChaincodeRequest request = fabricClientWrapper.getClient().newQueryProposalRequest();
ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).build();
request.setChaincodeID(chaincodeID);
request.setFcn(fuctionName);
if(args != null){
request.setArgs(args);
}
Collection<ProposalResponse> response = channel.queryByChaincode(request);
return response;
}
//Method to init the channel for query
static public ChannelClientWrapper setupChannel(FabricClientWrapper fabricClientWrapper) throws InvalidArgumentException, TransactionException {
ChannelClientWrapper channelClientWrapper = fabricClientWrapper.createChannelClient(Config.CHANNEL_NAME);
channel = channelClientWrapper.getChannel();
Peer peer = fabricClientWrapper.getClient().newPeer(Config.ORG1_PEER_0,Config.ORG1_PEER_0_URL);
EventHub eventHub = fabricClientWrapper.getClient().newEventHub("eventhub01", "grpc://vps577432.ovh.net:8053");
Orderer orderer = fabricClientWrapper.getClient().newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
channel.addPeer(peer);
channel.addEventHub(eventHub);
channel.addOrderer(orderer);
channel.initialize();
return channelClientWrapper;
}
//Wrapper for channel.sendTransactionProposal
public Collection<ProposalResponse> sendTransactionProposal (TransactionProposalRequest transactionProposalRequest){
try{
return channel.sendTransactionProposal(transactionProposalRequest);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
//Wrapper for channel.sendTransaction
public BlockEvent.TransactionEvent sendTransaction(Collection<ProposalResponse> proposalResponses){
Logger logger = Logger.getLogger(ChannelClientWrapper.class);
BasicConfigurator.configure();
try{
List<ProposalResponse> invalid = proposalResponses.stream().filter(r -> r.isInvalid()).collect(Collectors.toList());
if (!invalid.isEmpty()) {
invalid.forEach(response -> {
logger.error(response.getMessage());
});
}
return channel.sendTransaction(proposalResponses).get();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}

View file

@ -0,0 +1,43 @@
package blockchain.client;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
public class FabricClientWrapper {
private HFClient client;
public HFClient getClient(){
return client;
}
public FabricClientWrapper(UserContext userContext) throws CryptoException, InvalidArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
client.setUserContext(userContext);
}
public ChannelClientWrapper createChannelClient(String name) throws InvalidArgumentException {
Channel channel = client.newChannel(name);
ChannelClientWrapper channelClientWrapper = new ChannelClientWrapper(name, channel, this);
return channelClientWrapper;
}
public Set<String> queryForChannels() throws InvalidArgumentException, IllegalArgumentException, ProposalException {
client.newChannel(Config.CHANNEL_NAME);
client.newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
//Peer peer = client.newPeer(Config.ORG_PEER,Config.ORG_PEER_URL);
Peer peer = client.newPeer(Config.ORG1_PEER_0,Config.ORG1_PEER_0_URL);
return client.queryChannels(peer);
}
}

View file

@ -0,0 +1,51 @@
package blockchain.configuration;
public class Config {
//ORGANIZATION
public static final String ORG1_MSP = "Org1MSP";
public static final String ORG1 = "org1";
//ADMIN
public static final String ADMIN = "admin";
public static final String ADMIN_PASSWORD = "adminpw";
//USER
public static final String UserPWD = "ZIidLJHQbLcC";
//CA
public static final String CA_ORG1_URL = "http://vps577432.ovh.net:7054";
//ORDERER
public static final String ORDERER_URL = "grpc://vps577432.ovh.net:7050";
public static final String ORDERER_NAME = "orderer.example.com";
//CHANNEL - CHAINCODE
public static final String CHANNEL_NAME = "mychannel";
public static final String CHAINCODE_NAME = "mycc";
//PEER 0
public static final String ORG1_PEER_0 = "peer0.org1.example.com";
public static final String ORG1_PEER_0_URL = "grpc://vps577432.ovh.net:8051";
//PEER 1
public static final String ORG_PEER = "peer1.org1.example.com";
public static final String ORG_PEER_URL = "grpc://vps592802.ovh.net:9051";
//EVENTHUB
public static final String ORG_PEER_EVENT_URL = "grpc://vps592802.ovh.net:9053";
//ADMIN FILE TEST
public static final String ADMIN_FILE_PATH = "msp/AdminFiles";
public static final String ADMIN_KEY_PATH = ADMIN_FILE_PATH+"/keystore";
public static final String ADMIN_CERT_PATH = ADMIN_FILE_PATH+"/admincerts";
}

View file

@ -0,0 +1,53 @@
package blockchain.query;
import blockchain.client.ChannelClientWrapper;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.hyperledger.fabric.sdk.ChaincodeResponse;
import org.hyperledger.fabric.sdk.ProposalResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class QueryWrapper {
public String getUserBalance(String userHashId){
String response = null;
try{
UserContext userContext = Util.readUserContext(Config.ORG1,"User-org1");
String chaincode = Config.CHAINCODE_NAME;
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(userContext);
ChannelClientWrapper channelClientWrapper = ChannelClientWrapper.setupChannel(fabricClientWrapper);
String[] args = {userHashId};
Collection<ProposalResponse> responseQuery = channelClientWrapper.queryByChainCode(chaincode,"query",args);
for(ProposalResponse pres : responseQuery){
ChaincodeResponse.Status status = pres.getStatus();
if(status.getStatus()!=200){
throw new Exception(pres.getMessage());
}
response = new String(pres.getChaincodeActionResponsePayload());
}
}catch (Exception e){
e.printStackTrace();
}
if(response==null) response = "Error";
return response;
}
public String getUser(String userHashId){
return "";
}
public List<String> getUserLastTransactions(String userHashId){
List<String> transactions = new ArrayList<>();
return transactions;
}
}

View file

@ -0,0 +1,41 @@
package blockchain.query;
import blockchain.client.ChannelClientWrapper;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.hyperledger.fabric.sdk.ChaincodeID;
import org.hyperledger.fabric.sdk.ProposalResponse;
import org.hyperledger.fabric.sdk.TransactionProposalRequest;
import java.util.Collection;
public class TransactionWrapper {
public String sendTransaction(String from, String to, String amount){
try{
UserContext userContext = Util.readUserContext(Config.ORG1,"User-org1");
String chaincode = Config.CHAINCODE_NAME;
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(userContext);
ChannelClientWrapper channelClientWrapper = ChannelClientWrapper.setupChannel(fabricClientWrapper);
TransactionProposalRequest tpr = fabricClientWrapper.getClient().newTransactionProposalRequest();
ChaincodeID cid = ChaincodeID.newBuilder().setName(Config.CHAINCODE_NAME).build();
tpr.setChaincodeID(cid);
tpr.setFcn("invoke");
tpr.setArgs(new String[]{from,to,amount});
Collection<ProposalResponse> responses = channelClientWrapper.sendTransactionProposal(tpr);
BlockEvent.TransactionEvent event = channelClientWrapper.sendTransaction(responses);
return event.getTransactionID();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}

View file

@ -0,0 +1,27 @@
package blockchain.user;
import org.hyperledger.fabric.sdk.Enrollment;
import java.io.Serializable;
import java.security.PrivateKey;
public class CAEnrollement implements Enrollment, Serializable {
private static final long serialVersionUID = 550416591376968096L;
private PrivateKey privateKey;
private String cert;
public CAEnrollement(PrivateKey pkey, String signedPem){
this.privateKey=pkey;
this.cert=signedPem;
}
@Override
public PrivateKey getKey() {
return privateKey;
}
@Override
public String getCert() {
return cert;
}
}

View file

@ -0,0 +1,72 @@
package blockchain.user;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.User;
import java.io.Serializable;
import java.util.Set;
public class UserContext implements User, Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected Set<String> roles;
protected String account;
protected String affiliation;
protected Enrollment enrollment;
protected String mspId;
public void setName(String name){
this.name=name;
}
public void setRoles(Set<String> roles){
this.roles=roles;
}
public void setAccount(String account) {
this.account = account;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public void setEnrollment(Enrollment enrollment) {
this.enrollment = enrollment;
}
public void setMspId(String mspId) {
this.mspId = mspId;
}
@Override
public String getName() {
return name;
}
@Override
public Set<String> getRoles() {
return roles;
}
@Override
public String getAccount() {
return account;
}
@Override
public String getAffiliation() {
return affiliation;
}
@Override
public Enrollment getEnrollment() {
return enrollment;
}
@Override
public String getMspId() {
return mspId;
}
}

View file

@ -0,0 +1,90 @@
package blockchain.utility;
import blockchain.user.UserContext;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import java.io.*;
//Class to Read and Write user / admin to msp directory
public class Util {
private static Logger logger = Logger.getLogger(Util.class);
public static void writeUserContext(UserContext userContext) {
BasicConfigurator.configure();
ObjectOutputStream out = null;
FileOutputStream fileOutputStream = null;
try {
logger.info("Write user "+userContext.getName()+" of "+userContext.getAffiliation());
String directoryPath = "msp/" + userContext.getAffiliation();
String filePath = directoryPath + "/" + userContext.getName() + ".context";
File directory = new File(directoryPath);
if (!directory.exists()){
logger.info("Create directory at path "+directoryPath);
directory.mkdirs();
}
File file = new File(filePath);
fileOutputStream = new FileOutputStream(file);
out = new ObjectOutputStream(fileOutputStream);
logger.info("Try write object for user "+userContext.getName());
out.writeObject(userContext);
} catch (IOException e) {
logger.error("1st IOException");
e.printStackTrace();
} finally {
try {
if (out != null){
logger.info("Close ObjectOutputStream");
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileOutputStream != null) {
logger.info("Close fileOutputStream");
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static UserContext readUserContext(String affiliation, String username) {
UserContext userContext = null;
FileInputStream fileStream = null;
ObjectInputStream in = null;
try {
String filePath = "msp/" + affiliation + "/" + username + ".context";
File file = new File(filePath);
if (file.exists()) {
fileStream = new FileInputStream(filePath);
in = new ObjectInputStream(fileStream);
userContext = (UserContext) in.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileStream != null)
fileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return userContext;
}
}
}

View file

@ -0,0 +1,12 @@
package restService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WelcomeController {
@RequestMapping("/")
public String index(){return "Welcome from Monnethic !";}
}

View file

@ -0,0 +1,42 @@
package blockchain.client;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import org.hyperledger.fabric.sdk.Enrollment;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
//Test to enroll Admin
public class TestEnrollAdmin {
@Test
public void TestAEnrollAdmin(){
String caUrl = Config.CA_ORG1_URL;
try {
CAClientWrapper caClientWrapper = new CAClientWrapper(caUrl,null);
UserContext adminContext = new UserContext();
adminContext.setName(Config.ADMIN);
adminContext.setAffiliation(Config.ORG1);
adminContext.setMspId(Config.ORG1_MSP);
caClientWrapper.setAdminContext(adminContext);
UserContext verifyUser = caClientWrapper.getAdminContext();
assertEquals(Config.ADMIN, verifyUser.getName());
assertEquals(Config.ORG1, verifyUser.getAffiliation());
assertEquals(Config.ORG1_MSP, verifyUser.getMspId());
//ENROLL AND WRITE ADMIN
adminContext = caClientWrapper.enrollAdmin(adminContext.getName(),Config.ADMIN_PASSWORD,adminContext.getAffiliation());
//Check Admin Enrollement
Enrollment enrollment = adminContext.getEnrollment();
System.out.println("admin cert : "+enrollment.getCert());
System.out.println("admin keys : "+enrollment.getKey());
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,37 @@
package blockchain.client;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.Logger;
import org.junit.Test;
//Test to register and enroll user
public class TestRegisterEnrollUser {
private static Logger logger = Logger.getLogger(TestRegisterEnrollUser.class);
//Success
@Test
public void RegisterEnrollUser(){
String caUrl = Config.CA_ORG1_URL;
try{
CAClientWrapper caClientWrapper = new CAClientWrapper(caUrl,null);
UserContext admin = Util.readUserContext(Config.ORG1,Config.ADMIN);
caClientWrapper.setAdminContext(admin);
UserContext userContext = new UserContext();
userContext.setName("User-org1");
userContext.setAffiliation(Config.ORG1);
userContext.setMspId(Config.ORG1_MSP);
String userSecret = caClientWrapper.registerUser(userContext.getName(),userContext.getAffiliation());
logger.info("uSecret : "+userSecret);
userContext = caClientWrapper.enrollUser(userContext,userSecret);
logger.info("userContext enrollement : "+userContext.getEnrollment());
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,75 @@
package blockchain.query;
import blockchain.client.ChannelClientWrapper;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
//Test for transaction
public class ChaincodeTransactionTest {
private static Logger logger = Logger.getLogger(ChaincodeTransactionTest.class);
@Test
public void TestATransaction(){
BasicConfigurator.configure();
//UserContext user = Util.readUserContext(Config.ORG1,"User-org1");
UserContext user = Util.readUserContext(Config.ORG1,Config.ADMIN);
try{
String chaincode = Config.CHAINCODE_NAME;
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(user);
ChannelClientWrapper channelClientWrapper = fabricClientWrapper.createChannelClient(Config.CHANNEL_NAME);
Channel channel = channelClientWrapper.getChannel();
//OLD PEER
//Peer peer = fabricClientWrapper.getClient().newPeer(Config.ORG_PEER,Config.ORG_PEER_URL);
//EventHub eventHub = fabricClientWrapper.getClient().newEventHub("eventhub01", Config.ORG_PEER_EVENT_URL);
//Orderer orderer = fabricClientWrapper.getClient().newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
Peer peer = fabricClientWrapper.getClient().newPeer(Config.ORG1_PEER_0,Config.ORG1_PEER_0_URL);
EventHub eventHub = fabricClientWrapper.getClient().newEventHub("eventhub01", "grpc://vps577432.ovh.net:8053");
Orderer orderer = fabricClientWrapper.getClient().newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
channel.addPeer(peer);
channel.addEventHub(eventHub);
channel.addOrderer(orderer);
channel.initialize();
TransactionProposalRequest tpr = fabricClientWrapper.getClient().newTransactionProposalRequest();
ChaincodeID cid = ChaincodeID.newBuilder().setName(Config.CHAINCODE_NAME).build();
tpr.setChaincodeID(cid);
tpr.setFcn("invoke");
tpr.setArgs(new String[]{"a","b","20"}); //send 20 from a to b
Collection<ProposalResponse> responses = channel.sendTransactionProposal(tpr);
List<ProposalResponse> invalid = responses.stream().filter(r -> r.isInvalid()).collect(Collectors.toList());
if (!invalid.isEmpty()) {
invalid.forEach(response -> {
logger.error(response.getMessage());
});
}
BlockEvent.TransactionEvent event = channel.sendTransaction(responses).get();
logger.info("Event transaction id : "+event.getTransactionID()); //print transaction id
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,62 @@
package blockchain.query;
import blockchain.client.ChannelClientWrapper;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//Test to create user on chaincode -> don't work, can't use function "Init"
public class CreateChaincodeUserTest {
private static Logger logger = Logger.getLogger(QueryTest.class);
@Test
public void TestCreateUser(){
BasicConfigurator.configure();
UserContext user = Util.readUserContext(Config.ORG1,Config.ADMIN);
try{
String chaincode = Config.CHAINCODE_NAME;
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(user);
ChannelClientWrapper channelClientWrapper = fabricClientWrapper.createChannelClient(Config.CHANNEL_NAME);
Channel channel = channelClientWrapper.getChannel();
//OLD
//Peer peer = fabricClientWrapper.getClient().newPeer(Config.ORG_PEER,Config.ORG_PEER_URL);
//EventHub eventHub = fabricClientWrapper.getClient().newEventHub("eventhub01", Config.ORG_PEER_EVENT_URL);
//Orderer orderer = fabricClientWrapper.getClient().newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
Peer peer = fabricClientWrapper.getClient().newPeer(Config.ORG1_PEER_0,Config.ORG1_PEER_0_URL);
EventHub eventHub = fabricClientWrapper.getClient().newEventHub("eventhub01", "grpc://vps577432.ovh.net:8053");
Orderer orderer = fabricClientWrapper.getClient().newOrderer(Config.ORDERER_NAME,Config.ORDERER_URL);
channel.addPeer(peer);
channel.addEventHub(eventHub);
channel.addOrderer(orderer);
channel.initialize();
String[] args = {"user1","200","user2","180"};
Collection<ProposalResponse> responseQuery = channelClientWrapper.queryByChainCode(chaincode,"init",args);
for(ProposalResponse pres : responseQuery){
ChaincodeResponse.Status status = pres.getStatus();
if(status.getStatus()!=200){
throw new Exception(pres.getMessage());
}
String stringResponse = new String(pres.getChaincodeActionResponsePayload());
logger.info("RESPONSE : "+stringResponse);
}
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,34 @@
package blockchain.query;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.Peer;
import org.junit.Test;
import java.util.Set;
//Test to show channels on a node
public class QueryChannelTest {
private static Logger logger = Logger.getLogger(QueryTest.class);
@Test
public void testQ(){
BasicConfigurator.configure();
UserContext userContext = Util.readUserContext(Config.ORG1,"User-org1");
try{
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(userContext);
Set<String> channels = fabricClientWrapper.queryForChannels();
logger.info("CHANNELS : "+channels);
}catch(Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,48 @@
package blockchain.query;
import blockchain.client.ChannelClientWrapper;
import blockchain.client.FabricClientWrapper;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import blockchain.utility.Util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.*;
import org.junit.Test;
import java.util.Collection;
//Test to get balance of a User
public class QueryTest {
private static Logger logger = Logger.getLogger(QueryTest.class);
@Test
public void TestAQueryChannels() {
BasicConfigurator.configure();
//UserContext user = Util.readUserContext(Config.ORG1,Config.ADMIN);
UserContext user = Util.readUserContext(Config.ORG1,"User-org1");
try{
String chaincode = Config.CHAINCODE_NAME;
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(user);
ChannelClientWrapper channelClientWrapper = ChannelClientWrapper.setupChannel(fabricClientWrapper);
String[] args1 = {"a"};
Collection<ProposalResponse> responseQuery = channelClientWrapper.queryByChainCode(chaincode,"query",args1);
for(ProposalResponse pres : responseQuery){
ChaincodeResponse.Status status = pres.getStatus();
if(status.getStatus()!=200){
throw new Exception(pres.getMessage());
}
String stringResponse = new String(pres.getChaincodeActionResponsePayload());
logger.info("RESPONSE : "+stringResponse);
}
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,18 @@
package blockchain.queryWrapper;
import blockchain.query.QueryWrapper;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Test;
public class QueryWrapperTest {
private static Logger logger = Logger.getLogger(QueryWrapperTest.class);
@Test
public void TestGerUserBalance() {
BasicConfigurator.configure();
QueryWrapper queryWrapper = new QueryWrapper();
String response = queryWrapper.getUserBalance("a");
logger.info(response);
}
}

View file

@ -0,0 +1,26 @@
package blockchain.queryWrapper;
import blockchain.query.QueryWrapper;
import blockchain.query.TransactionWrapper;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Test;
public class TransactionWrapperTest {
private static Logger logger = Logger.getLogger(TransactionWrapperTest.class);
@Test
public void TestTransaction() {
BasicConfigurator.configure();
QueryWrapper queryWrapper = new QueryWrapper();
TransactionWrapper transactionWrapper = new TransactionWrapper();
String responseTransaction = transactionWrapper.sendTransaction("a","b","15"); //do transaction
logger.info("TRANSACTION ID : "+responseTransaction);
String responseUserB = queryWrapper.getUserBalance("b"); //check new balance of user b
logger.info("BALANCE USER B : "+responseUserB);
String responseUserA = queryWrapper.getUserBalance("a"); //check new balance of user a
logger.info("BALANCE USER A :"+responseUserA);
}
}

View file

@ -0,0 +1,21 @@
package blockchain.user;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
//Test to create a User
public class UserContextTest {
@Test
public void TestACreateUser(){
UserContext userContext = new UserContext();
userContext.setName("admin");
userContext.setAffiliation("org1");
userContext.setMspId("MspidOrg1");
userContext.setEnrollment(null);
assertEquals("org1",userContext.getAffiliation());
assertEquals("admin",userContext.getName());
assertEquals(null,userContext.getEnrollment());
}
}

View file

@ -0,0 +1,22 @@
package blockchain.utility;
import blockchain.configuration.Config;
import blockchain.user.UserContext;
import org.junit.Test;
//Test to Read User
public class ReadUserTest {
@Test
public void testReadUserOrg1(){
try{
UserContext userContext = Util.readUserContext(Config.ORG1, "User-org1");
System.out.println(userContext.getAffiliation());
System.out.println(userContext.getMspId());
System.out.println(userContext.getEnrollment().getCert());
System.out.println(userContext.getEnrollment().getKey());
System.out.println(userContext.getName());
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,55 @@
package blockchain.utility;
import blockchain.user.UserContext;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
//Test to Read and Write user from files
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UtilTest {
private static Logger logger = Logger.getLogger(UtilTest.class);
@Test
public void TestAReadNullUser(){
BasicConfigurator.configure();
logger.info("----- START TEST READ NULL USER ----");
UserContext uc = Util.readUserContext("tata","abdel");
if(uc!=null){
logger.info("UserContext is : "+uc.toString());
}else{
logger.info("UserContext doesn't exist");
}
}
@Test
public void TestBWriteUser(){
BasicConfigurator.configure();
logger.info("----- START TEST WRITE NULL USER ----");
UserContext user = new UserContext();
user.setName("abdel");
user.setAffiliation("toto");
user.setEnrollment(null);
user.setMspId("test");
Util.writeUserContext(user);
}
@Test
public void TestCReadCreatedUser(){
BasicConfigurator.configure();
logger.info("----- START TEST READ CREATED USER ----");
UserContext uc = Util.readUserContext("toto","abdel");
if(uc!=null){
logger.info("UserContext is : "+uc.toString());
}else{
logger.info("UserContext doesn't exist");
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,11 @@
restService\WelcomeController.class
blockchain\user\UserContext.class
blockchain\client\CAClientWrapper.class
blockchain\utility\Util.class
blockchain\client\ChannelClientWrapper.class
blockchain\user\CAEnrollement.class
Application\App.class
blockchain\configuration\Config.class
blockchain\query\QueryWrapper.class
blockchain\query\TransactionWrapper.class
blockchain\client\FabricClientWrapper.class

View file

@ -0,0 +1,11 @@
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\client\ChannelClientWrapper.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\client\FabricClientWrapper.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\user\CAEnrollement.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\client\CAClientWrapper.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\query\QueryWrapper.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\restService\WelcomeController.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\Application\App.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\configuration\Config.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\query\TransactionWrapper.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\user\UserContext.java
B:\SCIENCES U\GroupProject\java-api\src\main\java\blockchain\utility\Util.java

View file

@ -0,0 +1,11 @@
blockchain\query\QueryTest.class
blockchain\queryWrapper\QueryWrapperTest.class
blockchain\query\QueryChannelTest.class
blockchain\queryWrapper\TransactionWrapperTest.class
blockchain\utility\UtilTest.class
blockchain\client\TestEnrollAdmin.class
blockchain\query\ChaincodeTransactionTest.class
blockchain\utility\ReadUserTest.class
blockchain\client\TestRegisterEnrollUser.class
blockchain\query\CreateChaincodeUserTest.class
blockchain\user\UserContextTest.class

View file

@ -0,0 +1,11 @@
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\client\TestRegisterEnrollUser.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\query\QueryTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\client\TestEnrollAdmin.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\query\CreateChaincodeUserTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\queryWrapper\TransactionWrapperTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\utility\UtilTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\query\QueryChannelTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\query\ChaincodeTransactionTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\utility\ReadUserTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\queryWrapper\QueryWrapperTest.java
B:\SCIENCES U\GroupProject\java-api\src\test\java\blockchain\user\UserContextTest.java

Binary file not shown.

Binary file not shown.

Binary file not shown.