Merge pull request #28 from domgolonka/master

TKNCoin: Cleaned up API + added zxing.jar + added Paperwallet
This commit is contained in:
GENERAL BYTES 2017-03-16 13:43:19 +01:00 committed by GitHub
commit 4e6ad0a7ae
13 changed files with 217 additions and 462 deletions

Binary file not shown.

View File

@ -59,7 +59,7 @@ public class TKNAddressValidator implements ICryptoAddressValidator {
@Override
public boolean isPaperWalletSupported() {
return false;
return true;
}
@Override

View File

@ -27,6 +27,7 @@ import com.generalbytes.batm.server.extensions.IPaymentProcessor;
import com.generalbytes.batm.server.extensions.IRateSource;
import com.generalbytes.batm.server.extensions.IWallet;
import com.generalbytes.batm.server.extensions.extra.tokencoin.sources.FixPriceRateSource;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.paperwallet.TokencoinPaperWalletGenerator;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.TokenWallet;
import com.generalbytes.batm.server.extensions.watchlist.IWatchList;
@ -75,6 +76,9 @@ public class TKNExtension implements IExtension{
@Override
public IPaperWalletGenerator createPaperWalletGenerator(String cryptoCurrency) {
if (ICurrencies.TKN.equalsIgnoreCase(cryptoCurrency)) {
return new TokencoinPaperWalletGenerator();
}
return null;
}

View File

@ -0,0 +1,72 @@
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.paperwallet;
import com.generalbytes.batm.server.extensions.IPaperWallet;
/**
* Created by Dominik Golonka on 2017-03-01.
*/
public class TokencoinPaperWallet implements IPaperWallet {
private String address;
private String privateKey;
private String message;
private String fileExtension = "png";
private String contentType = "image/png";
private byte[] content;
@Override
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String getFileExtension() {
return fileExtension;
}
public void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
@Override
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Override
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}

View File

@ -0,0 +1,110 @@
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.paperwallet;
/**
* Created by Dominik Golonka on 2017-03-01.
*/
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import java.util.Random;
import com.generalbytes.batm.server.extensions.IPaperWallet;
import com.generalbytes.batm.server.extensions.IPaperWalletGenerator;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class TokencoinPaperWalletGenerator implements IPaperWalletGenerator {
private static int imagesize = 400;
private static final String MESSAGE = "We have attached a QR code with your address. Please use your QR code to add more funds to your account. Your address is ";
@Override
public IPaperWallet generateWallet(String cryptoCurrency, String passphrase, String language) {
return generateWallet();
}
private TokencoinPaperWallet generateWallet() {
String charactersallowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String newtkn = "TKN-"
+ generateString(charactersallowed,4)
+"-"+generateString(charactersallowed,4)
+"-"+generateString(charactersallowed,4)
+"-"+generateString(charactersallowed,5);
TokencoinPaperWallet paperwallet = new TokencoinPaperWallet();
byte[] image = generateQR(newtkn, imagesize);
paperwallet.setMessage(MESSAGE + newtkn);
paperwallet.setFileExtension("png");
paperwallet.setAddress(newtkn);
paperwallet.setContentType("image/png");
paperwallet.setContent(image);
return paperwallet;
}
public static String generateString(String characters, int length)
{
Random rng = new Random();
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
public byte[] generateQR(String address, int size) {
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(address,
BarcodeFormat.QR_CODE, size, size, hintMap);
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth, matrixWidth,
BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// Paint and save the image using the ByteMatrix
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream stream = new MemoryCacheImageOutputStream(baos);
ImageIO.write(image, "png", stream);
stream.close();
return baos.toByteArray();
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -20,19 +20,19 @@ package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoi
import com.generalbytes.batm.server.extensions.ICurrencies;
import com.generalbytes.batm.server.extensions.IWallet;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.HttpStatusIOException;
import si.mazi.rescu.RestProxyFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
public class TokenWallet implements IWallet{
private static final Logger log = LoggerFactory.getLogger("batm.master.Tokenwallet");
private static final BigDecimal NQT = new BigDecimal("100000000");
private static final BigDecimal DEFAULT_FEE_IN_TKN = new BigDecimal(1);
private String host;
private int port;
@ -61,57 +61,41 @@ public class TokenWallet implements IWallet{
@Override
public String getCryptoAddress(String cryptoCurrency) {
if (!getCryptoCurrencies().contains(cryptoCurrency)) {
log.error("Cryptocurrency " + cryptoCurrency + " not supported.");
return null;
}
if (accountId != null) {
return accountId;
}
TokenAccountsResponse res = api.getAllAccounts();
if (res != null) {
Account[] accounts = res.getData().getAccounts();
Account selectedAccount = accounts[0];
accountId = selectedAccount.getId();
return accountId;
}else{
log.debug("No response received.");
try {
return api.getAddress(cryptoCurrency);
} catch (HttpStatusIOException e) {
log.error(e.getHttpBody());
} catch (IOException e) {
log.error("", e);
}
return null;
}
@Override
public BigDecimal getCryptoBalance(String cryptoCurrency) {
if (!getCryptoCurrencies().contains(cryptoCurrency)) {
log.error("Cryptocurrency " + cryptoCurrency + " not supported.");
return null;
}
if (accountId == null) {
getCryptoAddress(cryptoCurrency); //to load account_id
}
if (accountId != null) {
AccountResponse account = api.getBalance(accountId);
if (account != null) {
double balanceNQT = account.getFunds();
System.out.println("THIS IS THE WALLET " +account.toString() + " " + account.getFunds());
if (balanceNQT <= 0) {
return BigDecimal.ZERO;
}else{
return new BigDecimal(balanceNQT);
}
try {
Double amount = api.getCryptoBalance(accountId);
if (amount == null) {
return BigDecimal.ZERO;
}else{
log.debug("No response received.");
return new BigDecimal(amount);
}
} catch (HttpStatusIOException e) {
log.error(e.getHttpBody());
} catch (IOException e) {
log.error("", e);
}
return null;
}
@Override
public String sendCoins(String destinationAddress, BigDecimal amount, String cryptoCurrency, String description) {
if (!getCryptoCurrencies().contains(cryptoCurrency)) {
log.error("Cryptocurrency " + cryptoCurrency + " not supported.");
return null;
}
if (accountId == null) {
getCryptoAddress(cryptoCurrency); //to load account_id
}
@ -123,13 +107,12 @@ public class TokenWallet implements IWallet{
if (recipientInt != null) {
recipient = recipientInt.toString();
}*/
SendResponse res = api.send2( accId, recipient, amount.stripTrailingZeros(), "sendMoney");
if (res != null) {
log.debug("Transaction " + res.getTransaction() + " sent.");
return res.getTransaction();
}else{
log.debug("No response received.");
try{
return api.send2( accountId, destinationAddress, amount.stripTrailingZeros(), "sendMoney");
} catch (HttpStatusIOException e) {
log.error(e.getHttpBody());
} catch (IOException e) {
log.error("", e);
}
return null;
}

View File

@ -18,31 +18,22 @@
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto.AccountResponse;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto.TokenAccountsResponse;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto.TokenSendResponse;
import com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto.SendResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.math.BigDecimal;
@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
public interface TokenWalletAPI {
@GET
@Path("/Accounts")
public TokenAccountsResponse getAllAccounts();
@GET
@Path("/Accounts/{id}")
public AccountResponse getBalance( @PathParam("id") String accountId);
@POST
@Path("/send")
public TokenSendResponse send(@FormParam("email") String email, @FormParam("password") String password, @FormParam("masterPassword") String masterPassword, @FormParam("accountId") String accountId, @FormParam("recipient") String recipient, @QueryParam("amount") BigDecimal amountNQT, @FormParam("message") String message);
public String getAddress(@PathParam("id") String accountId) throws IOException;
@GET
@Path("/Accounts/{id}/balance")
public Double getCryptoBalance(@PathParam("id") String accountId) throws IOException;
@POST
@Path("/Accounts/{id}/{recipient}/{amount}/{message}/send")
public SendResponse send2( @PathParam("id") String accountId, @PathParam("recipient") String recipient, @PathParam("amount") BigDecimal amountNQT, @PathParam("message") String requestType);
public String send2( @PathParam("id") String accountId, @PathParam("recipient") String recipient, @PathParam("amount") BigDecimal amountNQT, @PathParam("message") String requestType)throws IOException;
}

View File

@ -1,85 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
public class Account {
private String id_account;
private String tx_account_id;
private String tx_public_key;
private String bl_selected;
private String tx_label;
private String bl_active;
private String id;
public String getId_account() {
return id_account;
}
public void setId_account(String id_account) {
this.id_account = id_account;
}
public String getTx_account_id() {
return tx_account_id;
}
public void setTx_account_id(String tx_account_id) {
this.tx_account_id = tx_account_id;
}
public String getTx_label() {
return tx_label;
}
public void setTx_label(String tx_label) {
this.tx_label = tx_label;
}
public String getBl_active() {
return bl_active;
}
public void setBl_active(String bl_active) {
this.bl_active = bl_active;
}
public String getBl_selected() {
return bl_selected;
}
public void setBl_selected(String bl_selected) {
this.bl_selected = bl_selected;
}
public String getTx_public_key() {
return tx_public_key;
}
public void setTx_public_key(String tx_public_key) {
this.tx_public_key = tx_public_key;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

View File

@ -1,125 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
import java.math.BigDecimal;
public class AccountResponse {
private String publicKey;
private long requestProcessingTime;
private String guaranteedBalanceNQT;
private String unconfirmedBalanceNQT;
private String forgedBalanceNQT;
private double funds;
private String accountRS;
private String id;
private BigDecimal effectiveBalanceTKN;
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public long getRequestProcessingTime() {
return requestProcessingTime;
}
public void setRequestProcessingTime(long requestProcessingTime) {
this.requestProcessingTime = requestProcessingTime;
}
public String getGuaranteedBalanceNQT() {
return guaranteedBalanceNQT;
}
public void setGuaranteedBalanceNQT(String guaranteedBalanceNQT) {
this.guaranteedBalanceNQT = guaranteedBalanceNQT;
}
public String getUnconfirmedBalanceNQT() {
return unconfirmedBalanceNQT;
}
public void setUnconfirmedBalanceNQT(String unconfirmedBalanceNQT) {
this.unconfirmedBalanceNQT = unconfirmedBalanceNQT;
}
public String getForgedBalanceNQT() {
return forgedBalanceNQT;
}
public void setForgedBalanceNQT(String forgedBalanceNQT) {
this.forgedBalanceNQT = forgedBalanceNQT;
}
public double getFunds() {
return funds;
}
public void setFunds(double funds) {
this.funds = funds;
}
public String getAccountRS() {
return accountRS;
}
public void setAccountRS(String accountRS) {
this.accountRS = accountRS;
}
public String getId() {
return id;
}
public void setAccount(String account) {
this.id = account;
}
public BigDecimal getEffectiveBalanceTKN() {
return effectiveBalanceTKN;
}
public void setEffectiveBalanceTKN(BigDecimal effectiveBalanceTKN) {
this.effectiveBalanceTKN = effectiveBalanceTKN;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Coin {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" funds: ").append(toIndentedString(funds)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -1,31 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
public class SendResponse {
private String transaction;
public String getTransaction() {
return transaction;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
}

View File

@ -1,45 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
public class TokenAccountsResponse extends TokenResponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private Account[] accounts;
public Account[] getAccounts() {
return accounts;
}
public void setAccounts(Account[] accounts) {
this.accounts = accounts;
}
}
}

View File

@ -1,40 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
public abstract class TokenResponse {
private String status;
private String message;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -1,79 +0,0 @@
/*************************************************************************************
* Copyright (C) 2015-2016 GENERAL BYTES s.r.o. All rights reserved.
*
* This software may be distributed and modified under the terms of the GNU
* General Public License version 2 (GPL2) as published by the Free Software
* Foundation and appearing in the file GPL2.TXT included in the packaging of
* this file. Please note that GPL2 Section 2[b] requires that all works based
* on this software must also be made publicly available under the terms of
* the GPL2 ("Copyleft").
*
* Contact information
* -------------------
*
* GENERAL BYTES s.r.o
* Web : http://www.generalbytes.com
*
************************************************************************************/
package com.generalbytes.batm.server.extensions.extra.tokencoin.wallets.tokencoind.dto;
public class TokenSendResponse extends TokenResponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private String fullHash;
private String signatureHash;
private String transactionBytes;
private String transaction;
private boolean broadcasted;
public String getFullHash() {
return fullHash;
}
public void setFullHash(String fullHash) {
this.fullHash = fullHash;
}
public String getSignatureHash() {
return signatureHash;
}
public void setSignatureHash(String signatureHash) {
this.signatureHash = signatureHash;
}
public String getTransactionBytes() {
return transactionBytes;
}
public void setTransactionBytes(String transactionBytes) {
this.transactionBytes = transactionBytes;
}
public String getTransaction() {
return transaction;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
public boolean isBroadcasted() {
return broadcasted;
}
public void setBroadcasted(boolean broadcasted) {
this.broadcasted = broadcasted;
}
}
}