Blockchain first

This commit is contained in:
GME 2018-10-14 18:50:55 +02:00
parent 73132974db
commit 07d3f94a40
14 changed files with 518 additions and 176 deletions

View file

@ -25,9 +25,7 @@
</value>
</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$/build/classes" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
<component name="ProjectType">
<option name="id" value="Android" />
</component>

View file

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

View file

@ -21,21 +21,32 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/INDEX.LIST'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/io.netty.versions.properties'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'org.glassfish:javax.json:1.0.4'
implementation 'com.google.code.gson:gson:2.8.5'
implementation ('org.hyperledger.fabric-sdk-java:fabric-sdk-java:1.2.1'){
exclude group:'org.glassfish', module:'javax.json'
exclude group:'log4j', module:'log4j'
}
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test:rules:1.0.1'
androidTestImplementation 'com.android.support:support-annotations:26.1.0'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
androidTestImplementation 'com.android.support:support-annotations:28.0.0'
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'org.web3j:core:3.3.1-android'
implementation 'com.j256.ormlite:ormlite-core:5.1'
implementation 'com.j256.ormlite:ormlite-jdbc:5.1'
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.5'

View file

@ -0,0 +1,66 @@
package monnethic.mobile.test;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.example.monnthic.monnethicmobile.R;
import org.hyperledger.fabric.sdk.NetworkConfig;
import org.json.JSONObject;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import io.grpc.internal.JsonParser;
public class LearningTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
System.out.println(appContext.getFilesDir());
System.out.println(appContext.getPackageName());
InputStream is = appContext.getResources().openRawResource(R.raw.config);
try (JsonReader reader = Json.createReader(is)) {
JsonObject jsonConfig = (JsonObject) reader.read();
System.out.println(jsonConfig);
System.out.println(jsonConfig.getClass());
NetworkConfig config;
config = NetworkConfig.fromJsonObject(jsonConfig);
//System.out.println(config!=null);
}
/*
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String jsonString = writer.toString();
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getJSONObject("organizations"));
*/
}
}

View file

@ -1,157 +0,0 @@
package monnethic.mobile.blockchain;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.utils.Convert;
import java.math.BigInteger;
import monnethic.mobile.transaction.Transaction;
/**
* Created by Guillaume on 28/05/2018.
*/
public class AccessBlockchain {
private static final String node3 = "http://5.51.59.70:1403";
private static final String node2 = "http://93.30.148.59:1402";
private static final String node1 = "http://93.30.148.59:1401";
//private static String address_test = "0x5421c79d465a288c28e10aa43f9b7dff1b313c8e";
private static String address_node3 = "0x869abc2dadd7e23c8b38f054276813a67d8131a7";
//Web3j web3jNode2 = Web3jFactory.build(new HttpService(node2));
public static void main(String [ ] args)
{
try{
//USED FOR TEST
/*
Web3j web3jNode1 = Web3jFactory.build(new HttpService(node1));
System.out.println(web3jNode1.ethCoinbase().sendAsync().get().getResult());
EthGetTransactionCount transactionCount = web3jNode1.ethGetTransactionCount(address_test, DefaultBlockParameterName.LATEST).sendAsync().get();
System.out.println(transactionCount);
BigInteger nonce = transactionCount.getTransactionCount();
System.out.println(nonce);
*/
Web3j web3jNode1 = Web3jFactory.build(new HttpService(node1));
System.out.println("Node 1 : ethAccounts : "+web3jNode1.ethAccounts().send().getAccounts());
EthGetBalance ethGetBalance1 = web3jNode1.ethGetBalance("0x5421c79d465a288c28e10aa43f9b7dff1b313c8e", DefaultBlockParameterName.LATEST).sendAsync().get();
Web3j web3jNode2 = Web3jFactory.build(new HttpService(node2));
System.out.println("Noded 2 ethAccounts : "+web3jNode2.ethAccounts().send().getAccounts());
EthGetBalance ethGetBalance2 = web3jNode2.ethGetBalance("0xef816528949bda3b87e19b86848fb28767156232", DefaultBlockParameterName.LATEST).sendAsync().get();
System.out.println("Node 1 ethMining : "+web3jNode1.ethMining().send().getResult());
System.out.println("Node 1 sync : "+web3jNode1.ethSyncing().send().getResult().toString());
BigInteger wei1 = ethGetBalance1.getBalance();
System.out.println("Node 1 balance is : "+wei1);
BigInteger wei2 = ethGetBalance2.getBalance();
System.out.println("Node 2 balance is : "+wei2);
System.out.println("ethBlockNumber Node 1 : "+web3jNode1.ethBlockNumber().send().getResult());
System.out.println("ethGetWork Node 1 : "+web3jNode1.ethGetWork().send().getResult());
Web3j web3jNode3 = Web3jFactory.build(new HttpService(node3));
System.out.println("Node 3 : ethAccounts : "+web3jNode3.ethAccounts().send().getAccounts());
EthGetBalance ethGetBalance_n3 = web3jNode1.ethGetBalance(address_node3, DefaultBlockParameterName.LATEST).sendAsync().get();
System.out.println("TEST node 1 wallet 3 : "+ethGetBalance_n3);
//BigInteger test = getTheBalanceOfWallet(address);
//System.out.println(test);
//Web3j web3jNode1 = Web3jFactory.build(new HttpService(node1));
//Web3j web3jNode2 = Web3jFactory.build(new HttpService(node2));
//System.out.println("ethAccounts : "+web3jNode1.ethAccounts().send().getAccounts());
//System.out.println("ethGasPrice : "+web3jNode1.ethGasPrice().send().getGasPrice());
//System.out.println("ethGetWork : "+web3jNode1.ethGetWork().send().getResult());
//System.out.println("ethBlockNumber : "+web3jNode1.ethBlockNumber().send().getResult());
//EthGetBalance ethGetBalance = web3jNode1.ethGetBalance("0x5421c79d465a288c28e10aa43f9b7dff1b313c8e", DefaultBlockParameterName.LATEST).sendAsync().get();
// BigInteger wei = ethGetBalance.getBalance();
//System.out.println("wei is : "+wei);
//System.out.println("*************************************************");
//Web3j web3jNode1 = Web3jFactory.build(new HttpService(node1));
//Web3j web3jNode2 = Web3jFactory.build(new HttpService(node2));
//System.out.println("ethAccounts : "+web3jNode1.ethAccounts().send().getAccounts());
//System.out.println("ethAccounts : "+web3jNode2.ethAccounts().send().getAccounts());
//System.out.println("ethGasPrice : "+web3jNode2.ethGasPrice().send().getGasPrice());
//System.out.println("ethGetWork : "+web3jNode2.ethGetWork().send().getResult());
//System.out.println("ethBlockNumber : "+web3jNode2.ethBlockNumber().send().getResult());
//EthGetBalance ethGetBalance2 = web3jNode2.ethGetBalance("0x0278467c617c13604b3d88b95c2257a3a8a7bc01", DefaultBlockParameterName.LATEST).sendAsync().get();
//BigInteger wei2 = ethGetBalance2.getBalance();
//System.out.println("wei is : "+wei2);
}catch (Exception e){
e.printStackTrace();
}
}
//Get Balance function
public BigInteger getTheBalanceOfWallet(String walletAddress){
Web3j web3jNode1 = Web3jFactory.build(new HttpService(node1));
try{
EthGetBalance ethGetBalance = web3jNode1.ethGetBalance(walletAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger wei = ethGetBalance.getBalance();
return wei;
}catch (Exception e){
e.getMessage();
e.printStackTrace();
}
return null;
}
//Send Transaction demo function
public static boolean sendTransationTo(String addressSource, String addressDestination, BigInteger amountToSend){
Web3j n1 = Web3jFactory.build(new HttpService(node1));
try{
EthGetTransactionCount transactionCount = n1.ethGetTransactionCount(addressSource, DefaultBlockParameterName.LATEST).sendAsync().get();
String coinbase = n1.ethCoinbase().sendAsync().get().getResult();
BigInteger nonce = transactionCount.getTransactionCount();
BigInteger gasPrice = n1.ethGasPrice().send().getGasPrice();
BigInteger gasLimit = gasPrice.multiply(BigInteger.valueOf(2));
BigInteger amountEther = Convert.toWei(amountToSend.toString(), Convert.Unit.ETHER).toBigInteger();
org.web3j.protocol.core.methods.request.Transaction transaction = org.web3j.protocol.core.methods.request.Transaction.createEtherTransaction(coinbase, nonce, gasPrice, gasLimit, addressDestination, amountEther);
String txUnit = "ETHER";
System.out.println("source : "+coinbase+"\nnonce : "+nonce+"\ngasPrice : "+gasPrice);
System.out.println("gasLimit : "+gasLimit+"\ndestination : "+addressDestination+"\namount : "+amountEther);
/*
Send the transaction
*/
//EthSendTransaction ethSendTransaction = n1.ethSendTransaction(transaction).sendAsync().get();
//String txHash = ethSendTransaction.getTransactionHash();
//TransactionReceipt txR = n1.ethGetTransactionReceipt(txHash).send().getResult();
//txR.getBlockNumber();
//insertTransaction(addressSource, addressDestination, amountToSend, txHash, txR.getBlockNumber().toString(), txUnit);
return true;
}catch (Exception e){
e.getMessage();
e.printStackTrace();
}
return false;
}
private void insertTransaction(String adS, String adD, BigInteger amTs, String txH, String blN, String txUnit){
Transaction dbTrs = new Transaction();
}
}

View file

@ -0,0 +1,112 @@
package monnethic.mobile.blockchain.client;
import android.content.Context;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.hyperledger.fabric_ca.sdk.RegistrationRequest;
import java.util.logging.Level;
import java.util.logging.Logger;
import monnethic.mobile.blockchain.participant.UserContext;
import monnethic.mobile.blockchain.utility.Util;
public class CAClientWrapper {
private HFCAClient hfcaClient;
private String org;
private String url = "http://ca.org1.example.com:7054";
private String mspId = "";
public CAClientWrapper(String url, String org){
this.org=org;
init(url);
}
void init(String url){
try{
this.hfcaClient = HFCAClient.createNewInstance(url,null);
}catch (Exception e){
e.printStackTrace();
}
}
//Method to enroll admin
public void enrollAdmin(Context context, String name, String secret, String org) throws Exception {
UserContext adminContext;
adminContext = Util.readUserContext(context,name,secret);
if(adminContext!=null){
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.WARNING, "Admin already enrolled, skip");
return;
}
Enrollment enrollment = hfcaClient.enroll(name,secret);
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.INFO, "Admin enrolled");
adminContext = new UserContext();
adminContext.setName(name);
adminContext.setEnrollment(enrollment);
adminContext.setAffiliation(org);
adminContext.setMspId(mspId);
Util.writeUserContext(context,adminContext);
}
//Method to register and enroll user
public void regiserUser(Context context, String userName, String registrarAdmin) throws Exception{
UserContext userContext;
userContext = Util.readUserContext(context,org,userName);
if(userContext!=null){
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.WARNING, "User already registered");
return;
}
RegistrationRequest registrationRequest = new RegistrationRequest(userName,org);
UserContext registrarContext = Util.readUserContext(context,org,registrarAdmin);
if(registrarAdmin==null){
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.SEVERE, "Registar not enrolled");
throw new Exception("registrar context not found");
}
String enrollSecret = hfcaClient.register(registrationRequest, registrarContext);
Enrollment enrollment = hfcaClient.enroll(userName,enrollSecret);
userContext = new UserContext();
userContext.setMspId(mspId);
userContext.setAffiliation(org); //TODO GET MSPID IN ORGANIZATIONS, ORGNAME
userContext.setEnrollment(enrollment);
userContext.setName(userName);
Util.writeUserContext(context,userContext);
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.INFO, "User has been successfully registered");
}
//Method to get userContext
public static UserContext getUserContext(Context context, String userName, String org){
UserContext userContext;
userContext = Util.readUserContext(context,org,userName);
if(userContext!=null){
return userContext;
}
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.SEVERE, "User context not found : "+userName+" - "+org);
return userContext;
}
//Method to enroll user.
public UserContext enrollUser(Context context, String userName, String enrollSecret, String org) throws Exception {
Enrollment enrollment = hfcaClient.enroll(userName,enrollSecret);
UserContext userContext = new UserContext();
userContext.setMspId(mspId);
userContext.setAffiliation(this.org);
userContext.setEnrollment(enrollment);
userContext.setName(userName);
Util.writeUserContext(context, userContext);
Logger.getLogger(CAClientWrapper.class.getName()).log(Level.INFO, "UserName - "+userName+" enrolled");
return userContext;
}
}

View file

@ -0,0 +1,86 @@
package monnethic.mobile.blockchain.network;
import android.content.Context;
import com.example.monnthic.monnethicmobile.R;
import org.hyperledger.fabric.sdk.NetworkConfig;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.XMLFormatter;
import javax.json.JsonObject;
public class LoadConfigInfo {
private static final Integer lock = 0;
private static JSONObject jsonObject;
//Generate JSONObject from configFile
private LoadConfigInfo(Context context) {
InputStream is = context.getResources().openRawResource(R.raw.config);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (Exception e){
e.getMessage();
} finally {
try{
if(is!=null) {
is.close();
}
}catch (Exception e){
e.getMessage();
}
}
String jsonString = writer.toString();
try{
jsonObject = new JSONObject(jsonString);
}catch (Exception e){
e.getMessage();
}
}
private static void getInstanceFile(Context context){
try{
synchronized (lock){
if(jsonObject == null){
new LoadConfigInfo(context);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
//TODO GET ORGANIZATION INFOS
public static String getOrgInfo(Context context, String org) {
getInstanceFile(context);
return "";
}
//TODO GET ORGANIZATION NAME
public static String getOrgName(Context context){
getInstanceFile(context);
return "";
}
//TODO GET MSPID IN ORG NAME
public static String getMspId(Context context,String orgName){
getInstanceFile(context);
return "";
}
}

View file

@ -0,0 +1,72 @@
package monnethic.mobile.blockchain.participant;
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;
@Override
public String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
@Override
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles){
this.roles=roles;
}
@Override
public String getAccount() {
return account;
}
public void setAccount(String account){
this.account=account;
}
@Override
public String getAffiliation() {
return null;
}
public void setAffiliation(String affiliation){
this.affiliation=affiliation;
}
@Override
public Enrollment getEnrollment() {
return enrollment;
}
public void setEnrollment(Enrollment enrollment){
this.enrollment=enrollment;
}
@Override
public String getMspId() {
return mspId;
}
public void setMspId(String mspId){
this.mspId=mspId;
}
}

View file

@ -0,0 +1,98 @@
package monnethic.mobile.blockchain.utility;
import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import monnethic.mobile.blockchain.participant.UserContext;
public class Util {
private Context context;
public Util(Context context){
this.context=context;
}
//Method which write user info into a directory
public static void writeUserContext(Context context, UserContext userContext){
ObjectOutputStream out = null;
FileOutputStream file = null;
try{
String filename = userContext.getName()+".context";
String dirPath = context.getFilesDir()+"userInfos/"+userContext.getAffiliation();
String pathFile = dirPath+"/"+filename;
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdirs();
}
file = null;
file = new FileOutputStream(pathFile);
out = new ObjectOutputStream(file);
out.writeObject(userContext);
}catch (Exception e){
e.printStackTrace();
} finally {
try {
if (out != null){
out.close();
}
}catch (Exception e){
e.printStackTrace();
}
try{
if(file != null){
file.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//Method to read user in file
public static UserContext readUserContext(Context context, String affiliation, String username){
UserContext userContext = null;
FileInputStream fileInputStream = null;
ObjectInputStream in = null;
try{
String filename = username+".context";
String dirPath = context.getFilesDir()+"userInfos/"+affiliation;
String pathFile = dirPath+"/"+filename;
File file = new File(pathFile);
if(file.exists()){
fileInputStream = new FileInputStream(pathFile);
in = new ObjectInputStream(fileInputStream);
userContext = (UserContext) in.readObject();
}
} catch (Exception e){
e.printStackTrace();
} finally {
try {
if(in != null){
in.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(fileInputStream!=null){
fileInputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return userContext;
}
}

View file

@ -10,9 +10,7 @@ import android.widget.TextView;
import com.example.monnthic.monnethicmobile.R;
import org.web3j.utils.Convert;
import monnethic.mobile.blockchain.AccessBlockchain;
import monnethic.mobile.transaction.TransactionActivity;
public class WalletPresenterActivity extends AppCompatActivity {
@ -34,9 +32,9 @@ public class WalletPresenterActivity extends AppCompatActivity {
addressPublic.setText(address);
if(initiateBalance(address)==null){
balance.setText("Error");
balance.setText("IN DEV");
}else{
balance.setText(Convert.fromWei(initiateBalance(address).toString(), Convert.Unit.ETHER).toString());
balance.setText("IN DEV");
}
buttonSendTransaction.setOnClickListener(new View.OnClickListener() {
@ -61,9 +59,6 @@ public class WalletPresenterActivity extends AppCompatActivity {
}
public String initiateBalance(String address){
AccessBlockchain ab = new AccessBlockchain();
System.out.println("addresse "+ address);
String balanceIs = ab.getTheBalanceOfWallet(address).toString();
return balanceIs;
return "";
}
}

View file

@ -0,0 +1,61 @@
{
"name": "hlfv1",
"x-type": "hlfv1",
"x-commitTimeout": 300,
"version": "1.0.0",
"client": {
"organization": "Org1",
"connection": {
"timeout": {
"peer": {
"endorser": "300",
"eventHub": "300",
"eventReg": "300"
},
"orderer": "300"
}
}
},
"channels": {
"composerchannel": {
"orderers": [
"orderer.example.com"
],
"peers": {
"peer0.org1.example.com": {
"endorsingPeer": true,
"chaincodeQuery": true,
"ledgerQuery": true,
"eventSource": true
}
}
}
},
"organizations": {
"Org1": {
"mspid": "Org1MSP",
"peers": [
"peer0.org1.example.com"
],
"certificateAuthorities": [
"ca.org1.example.com"
]
}
},
"orderers": {
"orderer.example.com": {
"url": "grpc://orderer.example.com:7050"
}
},
"peers": {
"peer0.org1.example.com": {
"url": "grpc://peer0.org1.example.com:7051"
}
},
"certificateAuthorities": {
"ca.org1.example.com": {
"url": "http://ca.org1.example.com:7054",
"caName": "ca.org1.example.com"
}
}
}

View file

@ -7,7 +7,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong

View file

@ -1,6 +1,6 @@
#Mon Sep 24 08:37:23 CEST 2018
#Sun Oct 14 15:18:06 CEST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip