use of net.osmand.bitcoinsender.utils.BlockIOException in project OsmAnd-tools by osmandapp.
the class BlockIO method doApiCall.
private Response doApiCall(String method, Map<String, String> params, Class<?> responseType) throws BlockIOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(Constants.buildUri(method));
URIBuilder uriBuilder = new URIBuilder(request.getURI());
uriBuilder.addParameter(Constants.Params.API_KEY, apiKey);
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response;
try {
request.setURI(uriBuilder.build());
response = client.execute(request);
return getResponse(response, responseType);
} catch (IOException e) {
throw new BlockIOException("Network connectivity problem.");
} catch (URISyntaxException e) {
throw new BlockIOException("URI build failed. That is an internal error. Please file an issue.");
}
}
use of net.osmand.bitcoinsender.utils.BlockIOException in project OsmAnd-tools by osmandapp.
the class BlockIO method doPostApiCall.
private Response doPostApiCall(String method, Map<String, String> params, Class<?> responseType) throws BlockIOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(Constants.buildUri(method, true));
List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
postParams.add(new BasicNameValuePair(Constants.Params.API_KEY, apiKey));
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
postParams.add(new BasicNameValuePair("priority", PRIORITY));
CloseableHttpResponse response;
try {
request.setEntity(new UrlEncodedFormEntity(postParams));
response = client.execute(request);
return getResponse(response, responseType);
} catch (IOException e) {
throw new BlockIOException("Network connectivity problem.");
}
}
use of net.osmand.bitcoinsender.utils.BlockIOException in project OsmAnd-tools by osmandapp.
the class BlockIO method getResponse.
private Response getResponse(CloseableHttpResponse response, Class<?> responseType) throws BlockIOException {
Gson gson = new Gson();
String responseString;
try {
responseString = EntityUtils.toString(response.getEntity());
response.close();
} catch (IOException e) {
throw new BlockIOException("Received invalid data from API.");
}
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
return (Response) gson.fromJson(responseString, responseType);
case HttpStatus.SC_NOT_FOUND:
Response.ResponseError error = gson.fromJson(responseString, Response.ResponseError.class);
throw new BlockIOException("API returned error: " + error.error.message);
default:
throw new BlockIOException("Unknown API response.");
}
}
use of net.osmand.bitcoinsender.utils.BlockIOException in project OsmAnd-tools by osmandapp.
the class BlockIO method setupWithdrawalParams.
private HashMap<String, String> setupWithdrawalParams(Map<String, Double> addrsAndAmounts, ParamType targetType) throws BlockIOException {
String addrsParamString = "";
String amountsParamString = "";
// NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); // This will force '.' as decimal separator
DecimalFormat df = new DecimalFormat("#.########");
df.setRoundingMode(RoundingMode.CEILING);
for (Map.Entry<String, Double> entry : addrsAndAmounts.entrySet()) {
addrsParamString += entry.getKey() + ",";
amountsParamString += df.format(entry.getValue()) + ",";
}
// Now remove the trailing ','
addrsParamString = addrsParamString.replaceAll(",$", "");
amountsParamString = amountsParamString.replaceAll(",$", "");
// And put it where it belongs
HashMap<String, String> params = new HashMap<String, String>(2);
switch(targetType) {
case ADDRS:
params.put(Constants.Params.TO_ADDRS, addrsParamString);
break;
case LABELS:
params.put(Constants.Params.TO_LABELS, addrsParamString);
break;
case USERIDS:
params.put(Constants.Params.TO_USERIDS, addrsParamString);
break;
default:
throw new BlockIOException("You did not set the target type.");
}
params.put(Constants.Params.AMOUNTS, amountsParamString);
return params;
}
use of net.osmand.bitcoinsender.utils.BlockIOException in project OsmAnd-tools by osmandapp.
the class CoinSenderMain method main.
public static void main(String[] args) throws IOException {
if (args.length <= 0) {
System.out.println("Usage: --prepare | --send");
return;
}
Scanner in = new Scanner(System.in);
System.out.print(String.format("Enter your API key (default %s): ", DEFAULT_KEY));
guid = in.nextLine();
if (guid.trim().length() == 0) {
guid = DEFAULT_KEY;
}
System.out.print("Enter your PIN: ");
pass = in.nextLine();
System.out.print(String.format("Enter your part size (default %d): ", PART_SIZE));
String ll = in.nextLine();
if (ll.trim().length() > 0) {
PART_SIZE = Integer.parseInt(ll);
}
System.out.print("Enter satoshi per byte price (default " + FEE_BYTE_SATOSHI + "): ");
ll = in.nextLine();
if (ll.trim().length() > 0) {
FEE_BYTE_SATOSHI = Double.parseDouble(ll);
}
double MIN_PAY = getMinPayInBTC();
System.out.println(String.format("Minimal payment in mBTC: %.4f", MIN_PAY * 1000));
if (guid.equals("") || pass.equals("")) {
System.out.println("You forgot to enter Client_ID or Secret. Exiting...");
return;
}
BlockIO api = new BlockIO(guid);
System.out.println();
AccountBalance balance = null;
try {
balance = api.getAccountBalance();
} catch (BlockIOException e) {
e.printStackTrace();
System.out.println("Incorrect API key. Exiting...");
return;
}
System.out.println("Balance for account " + balance.network + ": Confirmed: " + balance.availableBalance + " Pending: " + balance.getPendingReceivedBalance());
System.out.println();
URL ur = new URL(URL_TO_PAY);
Map<String, Double> payments = convertPaymentsToMap(getPayments(new InputStreamReader(ur.openConnection().getInputStream())), MIN_PAY);
double allMoney = calculateTotalSum(payments);
List<Map> splitPayment = splitResults(payments);
for (Map<String, Double> map : splitPayment) {
payments.putAll(map);
}
if (args.length > 0) {
if (args[0].equals("--prepare")) {
String totalSum = String.format("%.12f", (allMoney));
System.out.println("Number of chunks: " + splitPayment.size());
System.out.println("Total sum in BTC: " + totalSum);
} else if (args[0].equals("--send")) {
boolean done = false;
List<Integer> paidChunks = new ArrayList<Integer>();
while (!done) {
System.out.println("Number of chunks: " + splitPayment.size());
System.out.println("You have already paid for these chunks: " + paidChunks.toString());
String chunkString = "Chunks: ";
for (int i = 0; i < splitPayment.size(); i++) {
chunkString += (i + 1) + ". " + (i * PART_SIZE + 1) + "-" + ((i + 1) * PART_SIZE) + ", ";
}
System.out.println(chunkString);
System.out.print("Enter the number of chunk you want to pay for ('-1' to exit): ");
int chunk = in.nextInt() - 1;
if (chunk == -2) {
break;
}
while (chunk < 0 || chunk >= splitPayment.size()) {
System.out.print("Please enter a number between 1 and " + splitPayment.size() + ": ");
chunk = in.nextInt() - 1;
if (chunk == -2) {
break;
}
}
if (paidChunks.contains(chunk + 1)) {
System.out.println("You've already paid for this chunk!");
continue;
}
Map<String, Double> paymentToPay = splitPayment.get(chunk);
Map<String, Double> currentPayment = new LinkedHashMap<>();
System.out.println("All payments: ");
double total = 0l;
int id = 0;
for (String key : paymentToPay.keySet()) {
id++;
Double toPay = paymentToPay.get(key);
String currentPaymentString = String.format("%.12f", toPay);
int addId = chunk * PART_SIZE + id;
if (toPay >= MIN_PAY) {
total += toPay;
currentPayment.put(key, toPay);
} else {
currentPaymentString += " [NOT PAID - less than minimal] ";
}
System.out.println(addId + ". Address: " + key + ", BTC: " + currentPaymentString);
}
Scanner scanner = new Scanner(System.in);
String totalString = String.format("%.10f", total);
System.out.println("Total: " + totalString);
System.out.println();
System.out.println();
int chunkUI = (chunk + 1);
System.out.println("Prepare to pay for chunk " + chunkUI + " (" + (chunk * PART_SIZE + 1) + "-" + ((chunk + 1) * PART_SIZE) + ") ...");
int numberOfInputs = 1;
int txSize = currentPayment.size() * 34 + numberOfInputs * 180 + 10 + 40;
float calculatedFee = (float) (((float) txSize * FEE_BYTE_SATOSHI) / BITCOIN_SATOSHI);
api.printFeeForTransaction(currentPayment);
System.out.println(String.format("!!! Estimated fee should be around : %.10f BTC !!!", calculatedFee));
FeeResponse feeForTransaction = api.getFeeForTransaction(currentPayment);
String pm = String.format("Actual fee to pay %.1f satoshi per byte (total %s BTC) - set as %.1f satoshi per byte", Double.parseDouble(feeForTransaction.fee) / calculatedFee * FEE_BYTE_SATOSHI, feeForTransaction.fee, FEE_BYTE_SATOSHI);
if (Double.parseDouble(feeForTransaction.fee) > FACTOR_MULT_ALLOWED_FEE * calculatedFee) {
System.out.println("Payment won't proceed: " + pm);
continue;
}
System.out.println(pm);
System.out.print("Are you sure you want to pay " + totalString + " BTC? [y/n]: ");
String answer = scanner.nextLine();
if (!answer.toLowerCase().equals("y")) {
continue;
}
System.out.println("Paying for chunk " + chunkUI + " (" + (chunk * PART_SIZE + 1) + "-" + ((chunk + 1) * PART_SIZE) + ") ...");
Withdrawal withdrawal = null;
try {
withdrawal = api.withdraw(null, null, currentPayment, BlockIO.ParamType.ADDRS, pass);
paidChunks.add(chunkUI);
} catch (BlockIOException e) {
e.printStackTrace();
System.out.println("Unable to pay fo this chunk");
continue;
}
System.out.println("Withdrawal done. Transaction ID: " + withdrawal.txid + " Amount withdrawn: " + withdrawal.amountWithdrawn + " Amount sent: " + withdrawal.amountSent + " Network fee: " + withdrawal.networkFee + " Block.io fee: " + withdrawal.blockIOFee);
System.out.println("Transaction url: https://chain.so/tx/BTC/" + withdrawal.txid);
if (splitPayment.size() == paidChunks.size()) {
System.out.println("You've successfully paid for all chunks!");
System.out.println("Exiting...");
break;
}
}
}
}
}
Aggregations