public static BigInteger getBalance(String address, String asset) { Database db = Database.getInstance(); Blocks blocks = Blocks.getInstance(); if (asset.equals("BTC")) { /* BigInteger totalBalance = BigInteger.ZERO; LinkedList<TransactionOutput> unspentOutputs = blocks.wallet.calculateAllSpendCandidates(true); Set<Transaction> txs = blocks.wallet.getTransactions(true); for (TransactionOutput out : unspentOutputs) { Script script = out.getScriptPubKey(); if (script.getToAddress(blocks.params).toString().equals(address) && out.isAvailableForSpending()) { totalBalance = totalBalance.add(out.getValue()); } } return totalBalance; */ return getBTCBalance(address); } else { ResultSet rs = db.executeQuery( "select sum(amount) as amount from balances where address='" + address + "' and asset='" + asset + "';"); try { if (rs.next()) { return BigInteger.valueOf(rs.getLong("amount")); } } catch (SQLException e) { } } return BigInteger.ZERO; }
public static Integer getLastBlockTimestamp() { Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from blocks order by block_index desc limit 1;"); try { while (rs.next()) { return rs.getInt("block_time"); } } catch (SQLException e) { } return 0; }
public static BigInteger nbcSupply() { Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select sum(amount) as amount from balances where asset='NBC';"); try { if (rs.next()) { return BigInteger.valueOf(rs.getLong("amount")); } } catch (SQLException e) { } return BigInteger.ZERO; }
public static Integer getLastBlock() { Blocks blocks = Blocks.getInstance(); Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from blocks order by block_index desc limit 1;"); try { while (rs.next()) { return rs.getInt("block_index"); } } catch (SQLException e) { } return blocks.newbiecoinBlock; }
public static String getBlockHash(Integer blockIndex) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "select block_hash from blocks where block_index='" + blockIndex.toString() + "';"); try { if (rs.next()) { return rs.getString("block_hash"); } } catch (SQLException e) { } return null; }
public static Integer getLastParsedBlock() { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "SELECT para_value FROM sys_parameters WHERE para_name='last_parsed_block'"); try { while (rs.next()) { return rs.getInt("para_value"); } } catch (SQLException e) { } return 0; }
public static Integer getLastTxIndex() { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "SELECT * FROM transactions WHERE tx_index = (SELECT MAX(tx_index) from transactions);"); try { while (rs.next()) { return rs.getInt("tx_index"); } } catch (SQLException e) { } return 0; }
public static BigInteger btcBurned(String destination) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "select sum(burned) as amount from burns " + (destination == null ? "" : " where destination='" + destination + "'") + ";"); try { if (rs.next()) { return BigInteger.valueOf(rs.getLong("amount")); } } catch (SQLException e) { } return BigInteger.ZERO; }
/** 获取新的ID */ public int getId() { Database DB = new Database(); int ID = 1; sql = "select max(JourNo) from AssetsTrjn"; try { DB.OpenConn(); rs = DB.executeQuery(sql); if (rs.next()) { ID = rs.getInt(1) + 1; } else { ID = 1; } } catch (Exception e) { } return ID; }
/** 为借用 查询所有记录 */ public String[][] searchAllForUse() { Database DB = new Database(); AssetsBean aBean = new AssetsBean(); PersonBean pBean = new PersonBean(); String[][] sn = null; int row = 0; int i = 0; sql = "select * from AssetsTrjn where FromAcc ='设备借用' order by JourNo"; try { DB.OpenConn(); rs = DB.executeQuery(sql); if (rs.last()) { row = rs.getRow(); } if (row == 0) { sn = new String[1][6]; sn[0][0] = " "; sn[0][1] = " "; sn[0][2] = " "; sn[0][3] = " "; sn[0][4] = " "; sn[0][5] = " "; } else { sn = new String[row][6]; rs.first(); rs.previous(); while (rs.next()) { sn[i][0] = rs.getString("JourNo"); sn[i][1] = aBean.getAssetsName(rs.getString("AssetsID")); sn[i][2] = rs.getString("RegDate"); sn[i][3] = pBean.getPersonName(rs.getString("PersonID")); sn[i][4] = rs.getString("Use"); sn[i][5] = rs.getString("Other"); i++; } } } catch (Exception e) { } finally { DB.closeStmt(); DB.closeConn(); } return sn; }
public static Boolean hasBalance(String address, String asset) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "select amount from balances where address='" + address + "' and asset='" + asset + "';"); try { if (rs.next()) { return true; } } catch (SQLException e) { } return false; }
public static BigInteger getReserved(String address, String asset) { Database db = Database.getInstance(); Blocks blocks = Blocks.getInstance(); ResultSet rs = db.executeQuery( "select sum(give_amount) as amount from orders where source='" + address + "' and give_asset='" + asset + "' and validity='valid'"); try { if (rs.next()) { return BigInteger.valueOf(rs.getLong("amount")); } } catch (SQLException e) { } return BigInteger.ZERO; }
public static List<BetInfo> getPending(String source) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "select * from transactions where block_index<0 and source='" + source + "' order by tx_index desc;"); List<BetInfo> bets = new ArrayList<BetInfo>(); Blocks blocks = Blocks.getInstance(); try { while (rs.next()) { String destination = rs.getString("destination"); BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount")); BigInteger fee = BigInteger.valueOf(rs.getLong("fee")); Integer blockIndex = rs.getInt("block_index"); String txHash = rs.getString("tx_hash"); Integer txIndex = rs.getInt("tx_index"); String dataString = rs.getString("data"); ResultSet rsCheck = db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'"); if (!rsCheck.next()) { List<Byte> messageType = blocks.getMessageTypeFromTransaction(dataString); List<Byte> message = blocks.getMessageFromTransaction(dataString); if (messageType.get(3) == Bet.id.byteValue() && message.size() == length) { ByteBuffer byteBuffer = ByteBuffer.allocate(length); for (byte b : message) { byteBuffer.put(b); } BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0)); Double chance = byteBuffer.getDouble(8); Double payout = byteBuffer.getDouble(16); Double houseEdge = Config.houseEdge; // PROTOCOL CHANGE Double oldHouseEdge = 0.02; Boolean payoutChanceCongruent = Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6) || Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6); BigInteger chaSupply = Util.chaSupplyForBetting(); String validity = "invalid"; if (!source.equals("") && bet.compareTo(BigInteger.ZERO) > 0 && chance > 0.0 && chance < 100.0 && payout > 1.0 && payoutChanceCongruent) { if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) { if ((payout - 1.0) * bet.doubleValue() < chaSupply.doubleValue() * Config.maxProfit) { BetInfo betInfo = new BetInfo(); betInfo.bet = bet; betInfo.chance = chance; betInfo.payout = payout; betInfo.source = source; betInfo.txHash = txHash; bets.add(betInfo); } } } } } } } catch (SQLException e) { } return bets; }
public static void parse(Integer txIndex, List<Byte> message) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from transactions where tx_index=" + txIndex.toString()); try { if (rs.next()) { String source = rs.getString("source"); String destination = rs.getString("destination"); BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount")); BigInteger fee = BigInteger.valueOf(rs.getLong("fee")); Integer blockIndex = rs.getInt("block_index"); String txHash = rs.getString("tx_hash"); ResultSet rsCheck = db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'"); if (rsCheck.next()) return; if (message.size() == length) { ByteBuffer byteBuffer = ByteBuffer.allocate(length); for (byte b : message) { byteBuffer.put(b); } BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0)); Double chance = byteBuffer.getDouble(8); Double payout = byteBuffer.getDouble(16); Double houseEdge = Config.houseEdge; // PROTOCOL CHANGE Double oldHouseEdge = 0.02; Boolean payoutChanceCongruent = Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6) || Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6); BigInteger chaSupply = Util.chaSupplyForBetting(); String validity = "invalid"; if (!source.equals("") && bet.compareTo(BigInteger.ZERO) > 0 && chance > 0.0 && chance < 100.0 && payout > 1.0 && payoutChanceCongruent) { if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) { if ((payout - 1.0) * bet.doubleValue() < chaSupply.doubleValue() * Config.maxProfit) { validity = "valid"; Util.debit(source, "CHA", bet, "Debit bet amount", txHash, blockIndex); } } } db.executeUpdate( "insert into bets(tx_index, tx_hash, block_index, source, bet, chance, payout, profit, cha_supply, validity) values('" + txIndex.toString() + "','" + txHash + "','" + blockIndex.toString() + "','" + source + "','" + bet.toString() + "','" + chance.toString() + "','" + payout.toString() + "','0','" + chaSupply.toString() + "','" + validity + "')"); } } } catch (SQLException e) { } }
public static void resolve() { // resolve bets logger.info("Resolving bets"); Database db = Database.getInstance(); ResultSet rs = db.executeQuery( "select block_time,blocks.block_index as block_index,tx_index,tx_hash,source,bet,payout,chance,cha_supply from bets,blocks where bets.block_index=blocks.block_index and bets.validity='valid' and bets.resolved IS NOT 'true';"); // if (true) return; SimpleDateFormat dateFormatStandard = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); SimpleDateFormat dateFormatDateTimeLotto = new SimpleDateFormat("MM/dd/yyyy HH:mm"); SimpleDateFormat dateFormatDateLotto = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat dateFormatHour = new SimpleDateFormat("HH"); SimpleDateFormat dateFormatMinute = new SimpleDateFormat("mm"); TimeZone newYork = TimeZone.getTimeZone("America/New_York"); TimeZone UTC = TimeZone.getTimeZone("UTC"); dateFormatStandard.setTimeZone(UTC); dateFormatDateLotto.setTimeZone(newYork); dateFormatDateTimeLotto.setTimeZone(newYork); dateFormatHour.setTimeZone(newYork); dateFormatMinute.setTimeZone(newYork); try { while (rs.next()) { String source = rs.getString("source"); String txHash = rs.getString("tx_hash"); Integer txIndex = rs.getInt("tx_index"); Integer blockIndex = rs.getInt("block_index"); BigInteger bet = BigInteger.valueOf(rs.getLong("bet")); Double payout = rs.getDouble("payout"); Double chance = rs.getDouble("chance"); BigInteger chaSupply = BigInteger.valueOf(rs.getLong("cha_supply")); Date blockTime = new Date((long) rs.getLong("block_time") * 1000); logger.info("Attempting to resolve bet " + txHash); String lottoDate = dateFormatDateLotto.format(blockTime); Integer hour = Integer.parseInt(dateFormatHour.format(blockTime)); Integer minute = Integer.parseInt(dateFormatMinute.format(blockTime)); if (hour >= 23 && minute >= 56) { lottoDate = dateFormatDateLotto.format(addDays(blockTime, 1)); } String lottoUrl = "http://nylottery.ny.gov/wps/PA_NYSLNumberCruncher/NumbersServlet?game=quick&action=winningnumbers&startSearchDate=" + lottoDate + "&endSearchDate=&pageNo=&last=&perPage=999&sort="; String lottoPage = Util.getPage(lottoUrl); logger.info("Getting lottery numbers " + lottoUrl); try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); LottoResult lottoMap = objectMapper.readValue(lottoPage, LottoResult.class); for (LottoDraw draw : lottoMap.draw) { Date time = dateFormatDateTimeLotto.parse(draw.date); if (time.after(blockTime)) { logger.info("Found lottery numbers we can use to resolve bet"); BigInteger denominator = combinations(BigInteger.valueOf(80), BigInteger.valueOf(20)) .subtract(BigInteger.ONE); BigInteger n = BigInteger.ZERO; BigInteger i = BigInteger.ONE; for (BigInteger number : draw.numbersDrawn) { n = n.add(combinations(number.subtract(BigInteger.ONE), i)); i = i.add(BigInteger.ONE); } Double rollA = n.doubleValue() / (denominator.doubleValue()); Double rollB = (new BigInteger(txHash.substring(10, txHash.length()), 16)) .mod(BigInteger.valueOf(1000000000)) .doubleValue() / 1000000000.0; Double roll = (rollA + rollB) % 1.0; roll = roll * 100.0; logger.info("Roll = " + roll.toString() + ", chance = " + chance.toString()); BigInteger profit = BigInteger.ZERO; if (roll < chance) { logger.info("The bet is a winner"); // win profit = new BigDecimal( bet.doubleValue() * (payout.doubleValue() - 1.0) * chaSupply.doubleValue() / (chaSupply.doubleValue() - bet.doubleValue() * payout.doubleValue())) .toBigInteger(); BigInteger credit = profit.add(bet); Util.credit(source, "CHA", credit, "Bet won", txHash, blockIndex); } else { logger.info("The bet is a loser"); // lose profit = bet.multiply(BigInteger.valueOf(-1)); } db.executeUpdate( "update bets set profit='" + profit.toString() + "', rolla='" + (rollA * 100.0) + "', rollb='" + (rollB * 100.0) + "', roll='" + roll + "', resolved='true' where tx_index='" + txIndex + "';"); break; } } } catch (Exception e) { logger.error(e.toString()); } } } catch (SQLException e) { logger.error(e.toString()); } }
public static java.sql.ResultSet executeQuery(String query) throws SQLException { return Database.executeQuery(query); }
public static void main(String[] args) { Config.loadUserDefined(); Blocks blocks = Blocks.getInstanceAndWait(); Thread blocksThread = new Thread(blocks); blocksThread.setDaemon(true); blocksThread.start(); Config.loadUserDefined(); Database db = Database.getInstance(); JSONObject attributes = null; JSONObject attributesSaved = null; while (true) { attributes = new JSONObject(); ResultSet rs = db.executeQuery( "select address,amount as balance from balances where asset='CHA' group by address order by amount desc;"); JSONObject balances = new JSONObject(); try { while (rs.next()) { balances.put( rs.getString("address"), BigInteger.valueOf(rs.getLong("balance")).doubleValue() / Config.unit.doubleValue()); } } catch (Exception e) { } try { attributes.put("balances", balances); attributes.put("height", Util.getLastBlock()); if (attributesSaved == null || attributes.getDouble("height") > attributesSaved.getDouble("height")) { attributesSaved = attributes; PrintWriter out = new PrintWriter("balances.txt"); out.print(attributes.toString()); out.close(); try { // Git Commit the change and print out any output and errors in the process Runtime rt = Runtime.getRuntime(); String[] commands = {"sh", "git_commit.sh"}; Process proc = rt.exec(commands); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // read the output from the command String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command while ((s = stdError.readLine()) != null) { System.out.println(s); } } catch (Exception ex) { ex.printStackTrace(); } } } catch (Exception e) { } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { logger.error("Error during loop: " + e.toString()); } } }