SHA256
203 lines
12 KiB
Java
203 lines
12 KiB
Java
package shine.db.dao;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import shine.db.DbController;
|
|
import shine.db.entities.BlockEntry;
|
|
|
|
import java.sql.*;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/** DAO for SHiNE blocks. block_bytes contains the complete signed CORE/CONTENT container. */
|
|
public final class BlocksDAO {
|
|
private static volatile BlocksDAO instance;
|
|
private final DbController db = DbController.getInstance();
|
|
private static final Logger log = LoggerFactory.getLogger(BlocksDAO.class);
|
|
|
|
private BlocksDAO() { }
|
|
public static BlocksDAO getInstance() {
|
|
if (instance == null) synchronized (BlocksDAO.class) { if (instance == null) instance = new BlocksDAO(); }
|
|
return instance;
|
|
}
|
|
|
|
public void insert(Connection c, BlockEntry e) throws SQLException {
|
|
insert(c, e, null, null);
|
|
}
|
|
|
|
public void insert(Connection c, BlockEntry e, Integer accountType, List<String> previousAccounts) throws SQLException {
|
|
String sql = """
|
|
INSERT INTO blocks_store (
|
|
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
|
to_login,to_fork_number,to_block_number,to_block_hash,
|
|
block_hash,block_signature,data_item_id,
|
|
arweave_publish_pending,arweave_published_at_ms,
|
|
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number,
|
|
header_account_type,header_previous_accounts
|
|
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
""";
|
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
|
int i = 1;
|
|
ps.setString(i++, e.getLogin());
|
|
ps.setInt(i++, e.getForkNumber());
|
|
ps.setInt(i++, e.getBlockNumber());
|
|
ps.setInt(i++, e.getMsgType());
|
|
ps.setInt(i++, e.getMsgSubType());
|
|
ps.setBytes(i++, e.getBlockBytes());
|
|
setNullableString(ps, i++, e.getToLogin());
|
|
setNullableInt(ps, i++, e.getToForkNumber());
|
|
setNullableInt(ps, i++, e.getToBlockNumber());
|
|
setNullableBytes(ps, i++, e.getToBlockHash());
|
|
ps.setBytes(i++, e.getBlockHash());
|
|
ps.setBytes(i++, e.getBlockSignature());
|
|
ps.setBytes(i++, e.getDataItemId());
|
|
ps.setBoolean(i++, e.isArweavePublishPending());
|
|
if (e.getArweavePublishedAtMs() == null) ps.setNull(i++, Types.BIGINT); else ps.setLong(i++, e.getArweavePublishedAtMs());
|
|
setNullableInt(ps, i++, e.getEditedByBlockNumber());
|
|
setNullableInt(ps, i++, e.getLineCode());
|
|
setNullableInt(ps, i++, e.getPrevLineNumber());
|
|
setNullableBytes(ps, i++, e.getPrevLineHash());
|
|
setNullableInt(ps, i++, e.getThisLineNumber());
|
|
if (accountType == null) {
|
|
ps.setNull(i++, Types.SMALLINT); ps.setNull(i, Types.ARRAY);
|
|
} else {
|
|
ps.setInt(i++, accountType);
|
|
ps.setArray(i, c.createArrayOf("text", previousAccounts.toArray(String[]::new)));
|
|
}
|
|
ps.executeUpdate();
|
|
}
|
|
}
|
|
|
|
public void insert(BlockEntry e) throws SQLException { try (Connection c = db.getConnection()) { insert(c, e); } }
|
|
|
|
public boolean existsByDataItemId(byte[] dataItemId) throws SQLException {
|
|
if (dataItemId == null || dataItemId.length != 32) return false;
|
|
try (Connection c = db.getConnection();
|
|
PreparedStatement ps = c.prepareStatement("SELECT 1 FROM blocks WHERE data_item_id=? LIMIT 1")) {
|
|
ps.setBytes(1, dataItemId);
|
|
try (ResultSet rs = ps.executeQuery()) { return rs.next(); }
|
|
}
|
|
}
|
|
|
|
/** Возвращает ещё не опубликованный пользовательский DataItem для быстрой Turbo-попытки. */
|
|
public BlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException {
|
|
if (dataItemId == null || dataItemId.length != 32) return null;
|
|
String sql = baseSelect() + " WHERE data_item_id=? AND arweave_publish_pending=TRUE LIMIT 1";
|
|
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
|
ps.setBytes(1, dataItemId);
|
|
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? mapRow(rs) : null; }
|
|
}
|
|
}
|
|
|
|
public List<BlockEntry> listPendingArweave(int limit) throws SQLException {
|
|
int safeLimit = Math.max(1, Math.min(limit, 100_000));
|
|
String sql = """
|
|
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
|
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
|
arweave_publish_pending,arweave_published_at_ms,
|
|
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
|
FROM blocks
|
|
WHERE arweave_publish_pending = TRUE
|
|
ORDER BY login ASC, fork_number ASC, block_number ASC
|
|
LIMIT ?
|
|
""";
|
|
List<BlockEntry> out = new ArrayList<>();
|
|
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
|
ps.setInt(1, safeLimit);
|
|
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
|
|
}
|
|
return out;
|
|
}
|
|
|
|
public void markArweavePublished(List<byte[]> dataItemIds, long publishedAtMs) throws SQLException {
|
|
if (dataItemIds == null || dataItemIds.isEmpty()) return;
|
|
String sql = """
|
|
UPDATE blocks_store
|
|
SET arweave_publish_pending=FALSE, arweave_published_at_ms=?
|
|
WHERE data_item_id=?
|
|
""";
|
|
try (Connection c = db.getConnection()) {
|
|
c.setAutoCommit(false);
|
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
|
for (byte[] id : dataItemIds) {
|
|
ps.setLong(1, publishedAtMs); ps.setBytes(2, id); ps.addBatch();
|
|
}
|
|
ps.executeBatch(); c.commit();
|
|
} catch (Exception e) { c.rollback(); throw e; }
|
|
finally { c.setAutoCommit(true); }
|
|
}
|
|
}
|
|
|
|
public byte[] getHashByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
|
|
try (PreparedStatement ps = c.prepareStatement("SELECT block_hash FROM blocks WHERE login=? AND fork_number=? AND block_number=? LIMIT 1")) {
|
|
ChainRef r=chainRef(bchName); ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber);
|
|
try (ResultSet rs=ps.executeQuery()) { return rs.next()?rs.getBytes(1):null; }
|
|
}
|
|
}
|
|
public byte[] getHashByNumber(String bchName, int blockNumber) throws SQLException { try(Connection c=db.getConnection()){return getHashByNumber(c,bchName,blockNumber);} }
|
|
|
|
public BlockEntry getByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
|
|
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND block_number=? LIMIT 1";
|
|
ChainRef r=chainRef(bchName);
|
|
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber); try(ResultSet rs=ps.executeQuery()){return rs.next()?mapRow(rs):null;} }
|
|
}
|
|
public BlockEntry getByNumber(String bchName,int blockNumber)throws SQLException{try(Connection c=db.getConnection()){return getByNumber(c,bchName,blockNumber);} }
|
|
|
|
/** Последний принятый блок конкретной логической линии в текущем physical fork. */
|
|
public BlockEntry getLastLineBlock(Connection c, String bchName, int msgType, int lineCode) throws SQLException {
|
|
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND msg_type=? AND line_code=? ORDER BY block_number DESC LIMIT 1";
|
|
ChainRef r=chainRef(bchName);
|
|
try(PreparedStatement ps=c.prepareStatement(sql)){
|
|
ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,msgType); ps.setInt(4,lineCode);
|
|
try(ResultSet rs=ps.executeQuery()){ return rs.next()?mapRow(rs):null; }
|
|
}
|
|
}
|
|
public BlockEntry getLastLineBlock(String bchName, int msgType, int lineCode) throws SQLException {
|
|
try(Connection c=db.getConnection()){ return getLastLineBlock(c,bchName,msgType,lineCode); }
|
|
}
|
|
|
|
public List<BlockEntry> listRangeByNumber(String bchName,int from,int to)throws SQLException{try(Connection c=db.getConnection()){return listRangeByNumber(c,bchName,from,to);} }
|
|
public List<BlockEntry> listRangeByNumber(Connection c,String bchName,int from,int to)throws SQLException{
|
|
String sql=baseSelect()+" WHERE login=? AND fork_number=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
|
|
List<BlockEntry> out=new ArrayList<>();
|
|
ChainRef r=chainRef(bchName);
|
|
try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,r.login());ps.setInt(2,r.fork());ps.setInt(3,from);ps.setInt(4,to);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(mapRow(rs));}}
|
|
return out;
|
|
}
|
|
|
|
private static String baseSelect(){return """
|
|
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
|
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
|
arweave_publish_pending,arweave_published_at_ms,
|
|
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
|
FROM blocks
|
|
""";}
|
|
|
|
private BlockEntry mapRow(ResultSet rs)throws SQLException{
|
|
BlockEntry e=new BlockEntry();
|
|
e.setLogin(rs.getString("login")); e.setForkNumber(rs.getInt("fork_number")); e.setBlockNumber(rs.getInt("block_number"));
|
|
e.setMsgType(rs.getInt("msg_type")); e.setMsgSubType(rs.getInt("msg_sub_type")); e.setBlockBytes(rs.getBytes("block_bytes"));
|
|
e.setToLogin(rs.getString("to_login")); e.setToForkNumber((Integer)rs.getObject("to_fork_number")); e.setToBlockNumber((Integer)rs.getObject("to_block_number")); e.setToBlockHash(rs.getBytes("to_block_hash"));
|
|
e.setBlockHash(rs.getBytes("block_hash")); e.setBlockSignature(rs.getBytes("block_signature")); e.setDataItemId(rs.getBytes("data_item_id"));
|
|
e.setArweavePublishPending(rs.getBoolean("arweave_publish_pending")); e.setArweavePublishedAtMs((Long)rs.getObject("arweave_published_at_ms"));
|
|
e.setEditedByBlockNumber((Integer)rs.getObject("edited_by_block_number")); e.setLineCode((Integer)rs.getObject("line_code")); e.setPrevLineNumber((Integer)rs.getObject("prev_line_number")); e.setPrevLineHash(rs.getBytes("prev_line_hash")); e.setThisLineNumber((Integer)rs.getObject("this_line_number"));
|
|
return e;
|
|
}
|
|
|
|
private record ChainRef(String login, int fork) {}
|
|
private static ChainRef chainRef(String name) {
|
|
if (name == null) throw new IllegalArgumentException("blockchainName is null");
|
|
String s=name.trim(); int dash=s.lastIndexOf('-');
|
|
if (dash <= 0 || s.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+name);
|
|
try {
|
|
int fork=Integer.parseInt(s.substring(dash+1));
|
|
if (fork < 1 || fork > 999) throw new IllegalArgumentException("fork out of range: "+name);
|
|
return new ChainRef(s.substring(0,dash),fork);
|
|
} catch(NumberFormatException ex){ throw new IllegalArgumentException("Bad blockchainName: "+name,ex); }
|
|
}
|
|
|
|
private static void setNullableString(PreparedStatement ps,int i,String v)throws SQLException{if(v==null)ps.setNull(i,Types.VARCHAR);else ps.setString(i,v);}
|
|
private static void setNullableInt(PreparedStatement ps,int i,Integer v)throws SQLException{if(v==null)ps.setNull(i,Types.INTEGER);else ps.setInt(i,v);}
|
|
private static void setNullableBytes(PreparedStatement ps,int i,byte[] v)throws SQLException{if(v==null)ps.setNull(i,Types.BINARY);else ps.setBytes(i,v);}
|
|
}
|