diff --git a/src/main/java/com/semuxpool/pool/Constants.java b/src/main/java/com/semuxpool/pool/Constants.java index 475496d..da67633 100644 --- a/src/main/java/com/semuxpool/pool/Constants.java +++ b/src/main/java/com/semuxpool/pool/Constants.java @@ -2,12 +2,10 @@ /** */ -public class Constants -{ +public class Constants { public static final long SEM = 1_000_000_000; - public static String getInSEM(long amount) - { + public static String getInSEM(long amount) { return String.format("%.8f", amount / (float) Constants.SEM); } } diff --git a/src/main/java/com/semuxpool/pool/PoolChecker.java b/src/main/java/com/semuxpool/pool/PoolChecker.java index 15ec0a1..f55a119 100644 --- a/src/main/java/com/semuxpool/pool/PoolChecker.java +++ b/src/main/java/com/semuxpool/pool/PoolChecker.java @@ -18,17 +18,12 @@ /** * Small util to verify payments */ -public class PoolChecker -{ - public static void main(String[] args) throws IOException, SemuxException - { +public class PoolChecker { + public static void main(String[] args) throws IOException, SemuxException { Properties properties = new Properties(); - if (args.length > 0) - { + if (args.length > 0) { properties.load(new FileInputStream(new File("./config/" + args[0]))); - } - else - { + } else { properties.load(new FileInputStream(new File("./config/semuxpool.properties"))); } @@ -48,21 +43,17 @@ public static void main(String[] args) throws IOException, SemuxException JsonPersistence persistence = new JsonPersistence(payoutsDirectory); List payouts = persistence.getAllPayouts(); Set blocksForged = new HashSet<>(); - for(Payout payout : payouts) - { + for (Payout payout : payouts) { TreeMap forged = payout.getBlocksForged(); blocksForged.addAll(forged.keySet()); } //let's scan all blocks since beginning of time and see what's missing Long totalBlocks = (long) client.getInfo().getLatestBlockNumber(); - for(long i =0; i<= totalBlocks;i++) - { + for (long i = 0; i <= totalBlocks; i++) { Block block = client.getBlock(i); - if(block.getCoinbase().equals(delegateAddress)) - { - if(!blocksForged.contains(block.getNumber())) - { + if (block.getCoinbase().equals(delegateAddress)) { + if (!blocksForged.contains(block.getNumber())) { System.out.println("Missed block " + block.getNumber()); } } diff --git a/src/main/java/com/semuxpool/pool/aggregation/AggregationSiteSubmitter.java b/src/main/java/com/semuxpool/pool/aggregation/AggregationSiteSubmitter.java index e405b0f..58f23a3 100644 --- a/src/main/java/com/semuxpool/pool/aggregation/AggregationSiteSubmitter.java +++ b/src/main/java/com/semuxpool/pool/aggregation/AggregationSiteSubmitter.java @@ -29,12 +29,10 @@ * todo - work in progress. * need to figure out ssl certs issue */ -public class AggregationSiteSubmitter -{ +public class AggregationSiteSubmitter { private static final Logger logger = LoggerFactory.getLogger(AggregationSiteSubmitter.class); - public void registerValidator(String validatorAddress, float donationPercent, SemuxClient client) - { + public void registerValidator(String validatorAddress, float donationPercent, SemuxClient client) { /** * The software is free/open without restriction, but semuxpool.com advertising for pool * It costs money to run, and my web dev guy likes to be paid for his work :D @@ -43,14 +41,11 @@ public void registerValidator(String validatorAddress, float donationPercent, Se */ // don't register with semuxpool.com if not supporting site operation. // advertising is not free. - if (donationPercent >= 0.05f) - { + if (donationPercent >= 0.05f) { HttpPost post = new HttpPost("https://semuxpool.com/api/delegates"); - try - { + try { Delegate delegate = client.getDelegate(validatorAddress); - if (delegate == null) - { + if (delegate == null) { logger.error("Unable to find delegate with address " + validatorAddress); return; } @@ -63,50 +58,40 @@ public void registerValidator(String validatorAddress, float donationPercent, Se post.setHeader("Content-type", "application/json"); CloseableHttpResponse response = httpClient.execute(post); - if (response.getStatusLine().getStatusCode() != 200) - { + if (response.getStatusLine().getStatusCode() != 200) { logger.error("Unable to register delegate with semuxpool.com"); } httpClient.close(); - } - catch (IOException | SemuxException | NoSuchAlgorithmException | KeyManagementException e) - { + } catch (IOException | SemuxException | NoSuchAlgorithmException | KeyManagementException e) { logger.error(e.getMessage(), e); } - } - else - { + } else { logger.warn("Not registering with semuxpool.com, donation amount too low."); } } - private CloseableHttpClient getClient() throws KeyManagementException, NoSuchAlgorithmException - { + private CloseableHttpClient getClient() throws KeyManagementException, NoSuchAlgorithmException { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything temporarily sslContext.init( - null, new TrustManager[] { - new X509TrustManager() - { - public X509Certificate[] getAcceptedIssuers() - { - System.out.println("getAcceptedIssuers ============="); - return null; - } + null, new TrustManager[]{ + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + System.out.println("getAcceptedIssuers ============="); + return null; + } - public void checkClientTrusted(X509Certificate[] certs, - String authType) - { - System.out.println("checkClientTrusted ============="); - } + public void checkClientTrusted(X509Certificate[] certs, + String authType) { + System.out.println("checkClientTrusted ============="); + } - public void checkServerTrusted(X509Certificate[] certs, - String authType) - { - System.out.println("checkServerTrusted ============="); - } - } }, new SecureRandom()); + public void checkServerTrusted(X509Certificate[] certs, + String authType) { + System.out.println("checkServerTrusted ============="); + } + }}, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); diff --git a/src/main/java/com/semuxpool/pool/api/BlockResult.java b/src/main/java/com/semuxpool/pool/api/BlockResult.java index 1fa6d5a..cb36769 100644 --- a/src/main/java/com/semuxpool/pool/api/BlockResult.java +++ b/src/main/java/com/semuxpool/pool/api/BlockResult.java @@ -9,50 +9,41 @@ /** * Payout results for a single given forged block. */ -public class BlockResult -{ +public class BlockResult { private Long blockId; private Long totalVotes; private Map votes; private Long blockReward; private String delegate; - public Long getTotalVotes() - { + public Long getTotalVotes() { return totalVotes; } - public void setTotalVotes(Long totalVotes) - { + public void setTotalVotes(Long totalVotes) { this.totalVotes = totalVotes; } - public Map getVotes() - { + public Map getVotes() { return votes; } - public void setVotes(Map votes) - { + public void setVotes(Map votes) { this.votes = votes; } - public Long getBlockReward() - { + public Long getBlockReward() { return blockReward; } - public void setBlockReward(Long blockReward) - { + public void setBlockReward(Long blockReward) { this.blockReward = blockReward; } @JsonIgnore - public Map getPayouts() - { + public Map getPayouts() { Map payout = new HashMap<>(); - for (Map.Entry voter : votes.entrySet()) - { + for (Map.Entry voter : votes.entrySet()) { payout.put(voter.getKey(), getPartialReward(voter.getValue())); } return payout; @@ -64,33 +55,27 @@ public Map getPayouts() * @param value value * @return partial reward */ - private Long getPartialReward(Long value) - { - if(totalVotes == 0) - { + private Long getPartialReward(Long value) { + if (totalVotes == 0) { return 0l; } BigInteger results = BigInteger.valueOf(getBlockReward()).multiply(BigInteger.valueOf(value)).divide(BigInteger.valueOf(totalVotes)); return results.longValue(); } - public void setDelegate(String delegate) - { + public void setDelegate(String delegate) { this.delegate = delegate; } - public String getDelegate() - { + public String getDelegate() { return delegate; } - public Long getBlockId() - { + public Long getBlockId() { return blockId; } - public void setBlockId(Long blockId) - { + public void setBlockId(Long blockId) { this.blockId = blockId; } } diff --git a/src/main/java/com/semuxpool/pool/api/DelegateInfo.java b/src/main/java/com/semuxpool/pool/api/DelegateInfo.java index 376376f..5a81fe2 100644 --- a/src/main/java/com/semuxpool/pool/api/DelegateInfo.java +++ b/src/main/java/com/semuxpool/pool/api/DelegateInfo.java @@ -3,50 +3,41 @@ /** * Information about a delegate */ -public class DelegateInfo -{ +public class DelegateInfo { private String name; private String address; private Long blocksForged; private Float votesSem; - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public String getAddress() - { + public String getAddress() { return address; } - public void setAddress(String address) - { + public void setAddress(String address) { this.address = address; } - public Long getBlocksForged() - { + public Long getBlocksForged() { return blocksForged; } - public void setBlocksForged(Long blocksForged) - { + public void setBlocksForged(Long blocksForged) { this.blocksForged = blocksForged; } - public Float getVotesSem() - { + public Float getVotesSem() { return votesSem; } - public void setVotesSem(Float votesSem) - { + public void setVotesSem(Float votesSem) { this.votesSem = votesSem; } } diff --git a/src/main/java/com/semuxpool/pool/api/Payment.java b/src/main/java/com/semuxpool/pool/api/Payment.java index a36c7a4..bb3a971 100644 --- a/src/main/java/com/semuxpool/pool/api/Payment.java +++ b/src/main/java/com/semuxpool/pool/api/Payment.java @@ -5,51 +5,42 @@ /** * A payment made to a voter */ -public class Payment -{ +public class Payment { private String to; private Date date; private Long amount; private String hash; private boolean includesPriorOwed; - public Date getDate() - { + public Date getDate() { return date; } - public void setDate(Date date) - { + public void setDate(Date date) { this.date = date; } - public Long getAmount() - { + public Long getAmount() { return amount; } - public void setAmount(Long amount) - { + public void setAmount(Long amount) { this.amount = amount; } - public String getHash() - { + public String getHash() { return hash; } - public void setHash(String hash) - { + public void setHash(String hash) { this.hash = hash; } - public String getTo() - { + public String getTo() { return to; } - public void setTo(String to) - { + public void setTo(String to) { this.to = to; } @@ -57,13 +48,11 @@ public void setTo(String to) * If this payment includes back-due payments for payment periods * that were less than minimum payments */ - public boolean isIncludesPriorOwed() - { + public boolean isIncludesPriorOwed() { return includesPriorOwed; } - public void setIncludesPriorOwed(boolean includesPriorOwed) - { + public void setIncludesPriorOwed(boolean includesPriorOwed) { this.includesPriorOwed = includesPriorOwed; } } diff --git a/src/main/java/com/semuxpool/pool/api/Payout.java b/src/main/java/com/semuxpool/pool/api/Payout.java index 6f1f499..2eb8093 100644 --- a/src/main/java/com/semuxpool/pool/api/Payout.java +++ b/src/main/java/com/semuxpool/pool/api/Payout.java @@ -8,8 +8,7 @@ /** * Defines a logged payment over a given block range */ -public class Payout -{ +public class Payout { private Map payouts = new HashMap<>(); //address to payment confirmation address private Map paidPayouts = new HashMap<>(); @@ -24,119 +23,96 @@ public class Payout private String id; private Date date; - public Map getPayouts() - { + public Map getPayouts() { return payouts; } - public void setPayouts(Map payouts) - { + public void setPayouts(Map payouts) { this.payouts = payouts; long total = 0l; - for (Long payout : payouts.values()) - { + for (Long payout : payouts.values()) { total += payout; } setTotalPayouts(total); } - public Long getStartBlock() - { + public Long getStartBlock() { return startBlock; } - public void setStartBlock(Long startBlock) - { + public void setStartBlock(Long startBlock) { this.startBlock = startBlock; } - public Long getEndBlock() - { + public Long getEndBlock() { return endBlock; } - public void setEndBlock(Long endBlock) - { + public void setEndBlock(Long endBlock) { this.endBlock = endBlock; } - public long getPoolProfits() - { + public long getPoolProfits() { return poolProfits; } - public void setPoolProfits(long poolProfits) - { + public void setPoolProfits(long poolProfits) { this.poolProfits = poolProfits; } - public Map getPaidPayouts() - { + public Map getPaidPayouts() { return paidPayouts; } - public void setPaidPayouts(Map paidPayouts) - { + public void setPaidPayouts(Map paidPayouts) { this.paidPayouts = paidPayouts; } - public long getTotalPayouts() - { + public long getTotalPayouts() { return totalPayouts; } - public void setTotalPayouts(long totalPayouts) - { + public void setTotalPayouts(long totalPayouts) { this.totalPayouts = totalPayouts; } - public TreeMap getBlocksForged() - { + public TreeMap getBlocksForged() { return blocksForged; } - public void setBlocksForged(TreeMap blocksForged) - { + public void setBlocksForged(TreeMap blocksForged) { this.blocksForged = blocksForged; } - public Long getFee() - { + public Long getFee() { return fee; } - public void setFee(Long fee) - { + public void setFee(Long fee) { this.fee = fee; } - public String getId() - { + public String getId() { return id; } - public void setId(String id) - { + public void setId(String id) { this.id = id; } - public Date getDate() - { + public Date getDate() { return date; } - public void setDate(Date date) - { + public void setDate(Date date) { this.date = date; } - public int getNumForgedBlocks() - { + public int getNumForgedBlocks() { return blocksForged.size(); } - public void setNumForgedBlocks(int size) - { + public void setNumForgedBlocks(int size) { //virtual - no setter. } } diff --git a/src/main/java/com/semuxpool/pool/api/Status.java b/src/main/java/com/semuxpool/pool/api/Status.java index 8eb6c3e..cd0704b 100644 --- a/src/main/java/com/semuxpool/pool/api/Status.java +++ b/src/main/java/com/semuxpool/pool/api/Status.java @@ -6,68 +6,56 @@ /** * Pools current status - * + *

* TODO - WIP */ -public class Status -{ +public class Status { private Long currentBlock; private Long poolPaid; private Map payments; private Set delegates; private Date updated; - public Status() - { + public Status() { } - public Long getCurrentBlock() - { + public Long getCurrentBlock() { return currentBlock; } - public void setCurrentBlock(Long currentBlock) - { + public void setCurrentBlock(Long currentBlock) { this.currentBlock = currentBlock; } - public Long getPoolPaid() - { + public Long getPoolPaid() { return poolPaid; } - public void setPoolPaid(Long poolPaid) - { + public void setPoolPaid(Long poolPaid) { this.poolPaid = poolPaid; } - public Map getPayments() - { + public Map getPayments() { return payments; } - public void setPayments(Map payments) - { + public void setPayments(Map payments) { this.payments = payments; } - public Set getDelegates() - { + public Set getDelegates() { return delegates; } - public void setDelegates(Set delegates) - { + public void setDelegates(Set delegates) { this.delegates = delegates; } - public Date getUpdated() - { + public Date getUpdated() { return updated; } - public void setUpdated(Date updated) - { + public void setUpdated(Date updated) { this.updated = updated; } } diff --git a/src/main/java/com/semuxpool/pool/block/PayoutFactory.java b/src/main/java/com/semuxpool/pool/block/PayoutFactory.java index 05e2089..923d4f1 100644 --- a/src/main/java/com/semuxpool/pool/block/PayoutFactory.java +++ b/src/main/java/com/semuxpool/pool/block/PayoutFactory.java @@ -13,15 +13,13 @@ /** * Construct Payouts from BlockResults */ -public class PayoutFactory -{ +public class PayoutFactory { //the address for pool profits to be paid out to. private final PoolProfitAddresses profitsAddress; private final String delegateName; private final long fee; - public PayoutFactory(String delegateName, PoolProfitAddresses profitsAddress, long fee) - { + public PayoutFactory(String delegateName, PoolProfitAddresses profitsAddress, long fee) { this.delegateName = delegateName; this.profitsAddress = profitsAddress; this.fee = fee; @@ -34,38 +32,31 @@ public PayoutFactory(String delegateName, PoolProfitAddresses profitsAddress, lo * @param startBlockId startBlockId * @return Payout */ - public synchronized Payout getPayoutForBlockResults(List blocks, Long startBlockId) - { + public synchronized Payout getPayoutForBlockResults(List blocks, Long startBlockId) { Payout payout = new Payout(); - if (blocks.isEmpty()) - { + if (blocks.isEmpty()) { return null; } long totalPoolFees = 0l; TreeMap blocksForged = new TreeMap<>(); - for (BlockResult blockResult : blocks) - { + for (BlockResult blockResult : blocks) { blocksForged.put(blockResult.getBlockId(), delegateName); //add up pool fees Long poolProfit = 0l; - if (blockResult.getPayouts() != null) - { - for (String address : profitsAddress.getAddresses()) - { + if (blockResult.getPayouts() != null) { + for (String address : profitsAddress.getAddresses()) { Long blockProfit = blockResult.getPayouts().get(address); - if (blockProfit != null) - { + if (blockProfit != null) { poolProfit += blockProfit; } } } - if (poolProfit != null) - { + if (poolProfit != null) { totalPoolFees += poolProfit; } } @@ -83,16 +74,12 @@ public synchronized Payout getPayoutForBlockResults(List blocks, Lo return payout; } - private synchronized Map getPayouts(List blockResults) - { + private synchronized Map getPayouts(List blockResults) { Map unPaidPayouts = new HashMap<>(); - for (BlockResult result : blockResults) - { - for (Map.Entry payout : result.getPayouts().entrySet()) - { + for (BlockResult result : blockResults) { + for (Map.Entry payout : result.getPayouts().entrySet()) { Long val = unPaidPayouts.get(payout.getKey()); - if (val == null) - { + if (val == null) { val = 0l; } val += payout.getValue(); diff --git a/src/main/java/com/semuxpool/pool/pay/PoolPayer.java b/src/main/java/com/semuxpool/pool/pay/PoolPayer.java index b61c4ae..70eeb81 100644 --- a/src/main/java/com/semuxpool/pool/pay/PoolPayer.java +++ b/src/main/java/com/semuxpool/pool/pay/PoolPayer.java @@ -19,8 +19,7 @@ /** * Handle sending payments */ -public class PoolPayer -{ +public class PoolPayer { private static final Logger logger = LoggerFactory.getLogger(PoolPayer.class); private final SemuxClient client; private final String delegateAddress; @@ -34,8 +33,7 @@ public class PoolPayer private final Set poolAddresses; public PoolPayer(SemuxClient client, String delegateAddress, Persistence persistence, long fee, - long minPayout, String note, boolean dontPayPoolQuitters, String payQuitterAddress, Set poolAddresses) - { + long minPayout, String note, boolean dontPayPoolQuitters, String payQuitterAddress, Set poolAddresses) { this.client = client; this.delegateAddress = delegateAddress; this.persistence = persistence; @@ -50,8 +48,7 @@ public PoolPayer(SemuxClient client, String delegateAddress, Persistence persist poolAddresses.add(BlockResultFactory.DONATION_ADDRESS); } - public void pay(Payout payout, PoolState poolState) throws IOException, SemuxException - { + public void pay(Payout payout, PoolState poolState) throws IOException, SemuxException { //save this payout persistence.persistPayout(payout); @@ -61,60 +58,48 @@ public void pay(Payout payout, PoolState poolState) throws IOException, SemuxExc Map currentVotes = client.getVotes(delegateAddress); - for (Map.Entry pay : payout.getPayouts().entrySet()) - { + for (Map.Entry pay : payout.getPayouts().entrySet()) { boolean includesDeferred = false; long amountToSend = pay.getValue() - fee; //look for any owed money and add it to it; Long unpaid = poolState.getUnpaidBalances().get(pay.getKey()); - if (unpaid != null) - { + if (unpaid != null) { amountToSend += unpaid; includesDeferred = true; } - try - { + try { //make sure we haven't already sent it - if (payout.getPaidPayouts().get(pay.getKey()) != null) - { + if (payout.getPaidPayouts().get(pay.getKey()) != null) { continue; } //make sure its enough to pay out - if (amountToSend < minPayout) - { + if (amountToSend < minPayout) { continue; } //make sure we have enough balance - if (payoutAddressBalance < amountToSend) - { + if (payoutAddressBalance < amountToSend) { logger.warn("Pool has insufficient balance to pay! Deferring payment."); continue; } - if (unpaid != null && unpaid > 0) - { + if (unpaid != null && unpaid > 0) { logger.debug("Paying " + pay.getKey() + " " + unpaid + " deferred payment"); } //pay them String confirmation; //if we voted for our own pool, just mark it as paid - if (delegateAddress.contains(pay.getKey())) - { + if (delegateAddress.contains(pay.getKey())) { confirmation = "SELF"; - } - else if (dontPayPoolQuitters && !isCurrentVoter(pay.getKey(), currentVotes)) - { + } else if (dontPayPoolQuitters && !isCurrentVoter(pay.getKey(), currentVotes)) { //if someone has unvoted for pool, this hurts the pool, so their last day's payout is void //if they leave some in the pool, they'll be paid out as normal. //this is only enabled if the pool operator has configured it to do so (default off) //Requested feature by a pool operator. client.transfer(amountToSend, delegateAddress, payQuitterAddress, fee, note.getBytes()); confirmation = "VOID"; - } - else - { + } else { confirmation = client.transfer(amountToSend, delegateAddress, pay.getKey(), fee, note.getBytes()); } @@ -129,9 +114,7 @@ else if (dontPayPoolQuitters && !isCurrentVoter(pay.getKey(), currentVotes)) payout.getPaidPayouts().put(pay.getKey(), payment); //update immediately in case of crash persistence.update(payout); - } - catch (SemuxException e) - { + } catch (SemuxException e) { logger.error("Unable to send payment to " + delegateAddress, e); } } @@ -140,11 +123,9 @@ else if (dontPayPoolQuitters && !isCurrentVoter(pay.getKey(), currentVotes)) persistence.update(payout); } - private boolean isCurrentVoter(String address, Map currentVotes) - { + private boolean isCurrentVoter(String address, Map currentVotes) { //this is a pool operation address, it gets a pass - if (poolAddresses.contains(address)) - { + if (poolAddresses.contains(address)) { return true; } Long current = currentVotes.get(address); diff --git a/src/main/java/com/semuxpool/pool/pay/PoolProfitAddresses.java b/src/main/java/com/semuxpool/pool/pay/PoolProfitAddresses.java index f407feb..48e815b 100644 --- a/src/main/java/com/semuxpool/pool/pay/PoolProfitAddresses.java +++ b/src/main/java/com/semuxpool/pool/pay/PoolProfitAddresses.java @@ -10,44 +10,37 @@ /** * Contains information about multiple payouts */ -public class PoolProfitAddresses -{ +public class PoolProfitAddresses { private static final Logger logger = LoggerFactory.getLogger(PoolProfitAddresses.class); private final Map addressToPercent = new HashMap<>(); - public static PoolProfitAddresses fromString(String addresses) - { + public static PoolProfitAddresses fromString(String addresses) { String[] addressBlocks = addresses.split(","); PoolProfitAddresses ret = new PoolProfitAddresses(); Float totalPercent = 0f; - for (String address : addressBlocks) - { + for (String address : addressBlocks) { String[] namePercent = address.split(":"); Float percent = 1.0f; - if (namePercent.length > 1) - { + if (namePercent.length > 1) { percent = Float.valueOf(namePercent[1].trim()); } totalPercent += percent; ret.addressToPercent.put(namePercent[0].trim(), percent); } - if (totalPercent < 0.999f || totalPercent > 1.001f) - { + if (totalPercent < 0.999f || totalPercent > 1.001f) { throw new InternalError("Total percent for pool addresses must equal 1.0"); } return ret; } - public Collection getAddresses() - { + public Collection getAddresses() { return addressToPercent.keySet(); } - public Float getPercent(String address) - { + public Float getPercent(String address) { return addressToPercent.get(address); } } diff --git a/src/main/java/com/semuxpool/pool/persistence/JsonPersistence.java b/src/main/java/com/semuxpool/pool/persistence/JsonPersistence.java index 5cd897c..f27ed10 100644 --- a/src/main/java/com/semuxpool/pool/persistence/JsonPersistence.java +++ b/src/main/java/com/semuxpool/pool/persistence/JsonPersistence.java @@ -17,31 +17,25 @@ * Persist payouts to readable json. * An actual datastore would be nicer long-term, but this is easy to debug. */ -public class JsonPersistence implements Persistence -{ +public class JsonPersistence implements Persistence { private static final Logger logger = LoggerFactory.getLogger(JsonPersistence.class); private static final ObjectMapper MAPPER = new ObjectMapper(); private String payoutsDirectory = "payouts"; - public JsonPersistence(String payoutsDirectory) - { + public JsonPersistence(String payoutsDirectory) { this.payoutsDirectory = payoutsDirectory; MAPPER.enable(SerializationFeature.INDENT_OUTPUT); } - public String persistPayout(Payout payout) - { - if (payout.getPayouts().isEmpty() && payout.getPaidPayouts().isEmpty()) - { + public String persistPayout(Payout payout) { + if (payout.getPayouts().isEmpty() && payout.getPaidPayouts().isEmpty()) { return null; } String fileName = payoutsDirectory + File.separator + "Payout-" + System.currentTimeMillis() + "-" + payout.getStartBlock() + "-" + payout.getEndBlock() + ".json"; //persist the block - try - { + try { //don't double persist - if (payout.getId() != null) - { + if (payout.getId() != null) { logger.error("Already persisted block! Use Update method"); System.exit(-1); } @@ -51,24 +45,20 @@ public String persistPayout(Payout payout) return fileName; - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } return null; } - public PoolState loadPoolState() throws IOException - { + public PoolState loadPoolState() throws IOException { PoolState poolState = new PoolState(); long block = 0l; List payouts = getAllPayouts(); - for (Payout payout : payouts) - { + for (Payout payout : payouts) { poolState.addPayout(payout); block = payout.getEndBlock(); poolState.setLastPayoutDate(payout.getDate()); @@ -81,50 +71,39 @@ public PoolState loadPoolState() throws IOException } @Override - public void update(Payout payout) - { - if (payout.getId() == null) - { + public void update(Payout payout) { + if (payout.getId() == null) { logger.error("Unpersisted object, use persist"); System.exit(-1); } - try - { + try { MAPPER.writeValue(new File(payout.getId()), payout); - } - catch (IOException e) - { + } catch (IOException e) { logger.error("Unable to persist file", e); } } - public List getAllPayouts() throws IOException - { + public List getAllPayouts() throws IOException { //load all the payouts ObjectMapper mapper = new ObjectMapper(); File directory = new File(payoutsDirectory); - if (!directory.isDirectory()) - { + if (!directory.isDirectory()) { boolean success = directory.mkdir(); - if (!success) - { + if (!success) { throw new IOException("Unable to create payout directory"); } } List payoutFileNames = new ArrayList<>(); //noinspection ConstantConditions - for (File file : directory.listFiles()) - { + for (File file : directory.listFiles()) { payoutFileNames.add(file.getAbsolutePath()); } Collections.sort(payoutFileNames); List payouts = new ArrayList<>(); - for (String fileName : payoutFileNames) - { - if(!fileName.endsWith(".json")) - { + for (String fileName : payoutFileNames) { + if (!fileName.endsWith(".json")) { continue; } logger.info("Checking file " + fileName); diff --git a/src/main/java/com/semuxpool/pool/persistence/Persistence.java b/src/main/java/com/semuxpool/pool/persistence/Persistence.java index b6934a1..20dc960 100644 --- a/src/main/java/com/semuxpool/pool/persistence/Persistence.java +++ b/src/main/java/com/semuxpool/pool/persistence/Persistence.java @@ -8,8 +8,7 @@ /** * Persistence for pool stats */ -public interface Persistence -{ +public interface Persistence { String persistPayout(Payout payout); PoolState loadPoolState() throws IOException; diff --git a/src/main/java/com/semuxpool/pool/state/PoolState.java b/src/main/java/com/semuxpool/pool/state/PoolState.java index d229551..53c0b80 100644 --- a/src/main/java/com/semuxpool/pool/state/PoolState.java +++ b/src/main/java/com/semuxpool/pool/state/PoolState.java @@ -13,8 +13,7 @@ /** */ -public class PoolState -{ +public class PoolState { private static final Logger logger = LoggerFactory.getLogger(PoolState.class); private final Map unpaidBalances = new HashMap<>(); private final Map paidBalances = new HashMap<>(); @@ -31,93 +30,76 @@ public class PoolState private Date lastPayoutDate; - public long getTotalPoolProfits() - { + public long getTotalPoolProfits() { return totalPoolProfits; } - public void setTotalPoolProfits(long totalPoolProfits) - { + public void setTotalPoolProfits(long totalPoolProfits) { this.totalPoolProfits = totalPoolProfits; } - public long getTotalPaidOut() - { + public long getTotalPaidOut() { return totalPaidOut; } - public void setTotalPaidOut(long totalPaidOut) - { + public void setTotalPaidOut(long totalPaidOut) { this.totalPaidOut = totalPaidOut; } - public long getTotalUnpaid() - { + public long getTotalUnpaid() { return totalUnpaid; } - public long getTotalFeesPaid() - { + public long getTotalFeesPaid() { return totalFeesPaid; } - public Set getDelegates() - { + public Set getDelegates() { return delegates; } - public void setDelegates(Set delegates) - { + public void setDelegates(Set delegates) { this.delegates = delegates; } - public long getCurrentBlock() - { + public long getCurrentBlock() { return currentBlock; } - public void setCurrentBlock(long currentBlock) - { + public void setCurrentBlock(long currentBlock) { this.currentBlock = currentBlock; } - public Map getUnpaidBalances() - { + public Map getUnpaidBalances() { return unpaidBalances; } - public Map getPaidBalances() - { + public Map getPaidBalances() { return paidBalances; } - public long getBlocksForged() - { + public long getBlocksForged() { return blocksForged; } - public synchronized void addPayout(Payout payouts) - { + public synchronized void addPayout(Payout payouts) { totalPoolProfits += payouts.getPoolProfits(); //for each set of blocks we owe, first add what we owe long subtotalUnpaid = 0; - for (Map.Entry payout : payouts.getPayouts().entrySet()) - { + for (Map.Entry payout : payouts.getPayouts().entrySet()) { Long amount = add(payout.getValue(), unpaidBalances.get(payout.getKey())); unpaidBalances.put(payout.getKey(), amount); subtotalUnpaid += payout.getValue(); } logger.info("SubtotalUnpaid:" + Constants.getInSEM(subtotalUnpaid)); - if (subtotalUnpaid != payouts.getTotalPayouts()) - { + if (subtotalUnpaid != payouts.getTotalPayouts()) { logger.error("Calculated " + subtotalUnpaid + " payout but was " + payouts.getTotalPayouts()); } totalUnpaid += subtotalUnpaid; //then subtract what we paid. long subtotalPaid = 0; - for (Map.Entry paid : payouts.getPaidPayouts().entrySet()) - { + for (Map.Entry paid : payouts.getPaidPayouts().entrySet()) { Long paymentTotalWithFees = paid.getValue().getAmount() + payouts.getFee(); Long amount = add(-paymentTotalWithFees, unpaidBalances.get(paid.getKey())); subtotalPaid += paymentTotalWithFees; @@ -128,18 +110,14 @@ public synchronized void addPayout(Payout payouts) paidBalances.put(paid.getKey(), paidAmount); - if (amount != 0) - { - if (amount < 0) - { + if (amount != 0) { + if (amount < 0) { //this occurs in bugs in early versions. We'll just carry negative balance forward logger.error("Found negative balance for " + paid.getKey() + " : " + amount); } unpaidBalances.put(paid.getKey(), amount); - } - else - { + } else { unpaidBalances.remove(paid.getKey()); } } @@ -157,26 +135,21 @@ public synchronized void addPayout(Payout payouts) * @param b b * @return sum */ - private Long add(Long a, Long b) - { - if (a == null) - { + private Long add(Long a, Long b) { + if (a == null) { a = 0l; } - if (b == null) - { + if (b == null) { b = 0l; } return a + b; } - public Date getLastPayoutDate() - { + public Date getLastPayoutDate() { return lastPayoutDate; } - public void setLastPayoutDate(Date lastPayoutDate) - { + public void setLastPayoutDate(Date lastPayoutDate) { this.lastPayoutDate = lastPayoutDate; } } diff --git a/src/main/java/com/semuxpool/pool/status/StatusLogger.java b/src/main/java/com/semuxpool/pool/status/StatusLogger.java index c0e091e..7a517a7 100644 --- a/src/main/java/com/semuxpool/pool/status/StatusLogger.java +++ b/src/main/java/com/semuxpool/pool/status/StatusLogger.java @@ -10,12 +10,10 @@ /** * Logging for current state of pool payouts */ -public class StatusLogger -{ +public class StatusLogger { private static final Logger logger = LoggerFactory.getLogger(StatusLogger.class); - public void logState(PoolState poolState) - { + public void logState(PoolState poolState) { logger.info("====================="); logger.info("Block: " + poolState.getCurrentBlock()); logger.info("Pool profit: " + Constants.getInSEM(poolState.getTotalPoolProfits())); @@ -32,18 +30,13 @@ public void logState(PoolState poolState) logger.info("Current unpaid balances"); long calculatedUnpaid = 0; long calculatedOverpaid = 0; - for (Map.Entry unpaid : poolState.getUnpaidBalances().entrySet()) - { - if (unpaid.getValue() > 0) - { + for (Map.Entry unpaid : poolState.getUnpaidBalances().entrySet()) { + if (unpaid.getValue() > 0) { calculatedUnpaid += unpaid.getValue(); - } - else - { + } else { calculatedOverpaid -= unpaid.getValue(); } - if(unpaid.getValue() != 0) - { + if (unpaid.getValue() != 0) { logger.info(unpaid.getKey() + " : " + Constants.getInSEM(unpaid.getValue())); } } @@ -53,8 +46,7 @@ public void logState(PoolState poolState) logger.info("====================="); logger.info("Current paid balances"); long calculatedPaid = 0; - for (Map.Entry paid : poolState.getPaidBalances().entrySet()) - { + for (Map.Entry paid : poolState.getPaidBalances().entrySet()) { calculatedPaid += paid.getValue(); logger.info(paid.getKey() + " : " + Constants.getInSEM(paid.getValue())); } diff --git a/src/main/java/com/semuxpool/pool/util/PaymentsMerger.java b/src/main/java/com/semuxpool/pool/util/PaymentsMerger.java index 62b228b..25cb5ec 100644 --- a/src/main/java/com/semuxpool/pool/util/PaymentsMerger.java +++ b/src/main/java/com/semuxpool/pool/util/PaymentsMerger.java @@ -15,23 +15,18 @@ * Mostly due to developer error * you can combine sets */ -public class PaymentsMerger -{ - public static void main(String[] args) throws IOException - { +public class PaymentsMerger { + public static void main(String[] args) throws IOException { JsonPersistence jsonPersistence = new JsonPersistence("./fixme"); List payouts = jsonPersistence.getAllPayouts(); Payout merged = new Payout(); Map mergedPaid = new HashMap<>(); - for (Payout payout : payouts) - { + for (Payout payout : payouts) { Map paid = payout.getPaidPayouts(); - for (Map.Entry entry : paid.entrySet()) - { + for (Map.Entry entry : paid.entrySet()) { Payment mergedPayment = mergedPaid.get(entry.getKey()); Payment toMerge = entry.getValue(); - if (mergedPayment == null) - { + if (mergedPayment == null) { mergedPayment = new Payment(); mergedPayment.setDate(toMerge.getDate()); mergedPayment.setAmount(0l); @@ -41,8 +36,7 @@ public static void main(String[] args) throws IOException mergedPaid.put(entry.getKey(), mergedPayment); } //update with new - if (mergedPayment.getAmount() > 0) - { + if (mergedPayment.getAmount() > 0) { //consolidate the fees, since we only accounted for 1 mergedPayment.setAmount(mergedPayment.getAmount() + payout.getFee()); }