Дорабатываю добавление блоков!
This commit is contained in:
AidarKC
2025-12-23 15:48:23 +03:00
parent d949895fec
commit 62e4338e88
6 changed files with 333 additions and 217 deletions
@@ -2,18 +2,18 @@ package server.logic.ws_protocol.JSON.entyties.blockchain;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
/**
* Новый укороченный ответ:
* - reasonCode (null если ok)
* - serverLastGlobalNumber / serverLastGlobalHash
*/
public final class Net_AddBlock_Response extends Net_Response {
private String reasonCode; // null если ok
private String reasonCode; // null если ok
private int serverLastGlobalNumber;
private String serverLastGlobalHash;
private int serverLastLineNumber; // для линии блока
private String serverLastLineHash;
private int lineIndex; // какую линию сервер применил (из блока)
public String getReasonCode() { return reasonCode; }
public void setReasonCode(String reasonCode) { this.reasonCode = reasonCode; }
@@ -22,13 +22,4 @@ public final class Net_AddBlock_Response extends Net_Response {
public String getServerLastGlobalHash() { return serverLastGlobalHash; }
public void setServerLastGlobalHash(String v) { this.serverLastGlobalHash = v; }
public int getServerLastLineNumber() { return serverLastLineNumber; }
public void setServerLastLineNumber(int v) { this.serverLastLineNumber = v; }
public String getServerLastLineHash() { return serverLastLineHash; }
public void setServerLastLineHash(String v) { this.serverLastLineHash = v; }
public int getLineIndex() { return lineIndex; }
public void setLineIndex(int lineIndex) { this.lineIndex = lineIndex; }
}
}
@@ -1,5 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain_new.BchBlockEntry_new;
import blockchain_new.BchCryptoVerifier_new;
import server.logic.ws_protocol.WireCodes;
import shine.db.SqliteDbController;
import shine.db.dao.BlockchainStateDAO;
@@ -14,29 +16,31 @@ import java.sql.SQLException;
import java.util.Base64;
/**
* BlockchainStateService_new — атомарное добавление блока:
* - (опционально) проверки
* - вставка строки блока в таблицу blocks
* - обновление агрегатного состояния blockchain_state
* BlockchainStateService_new — атомарное добавление блока (НОВЫЙ формат):
* - decode Base64 -> FULL block bytes
* - parse block (recordSize must match)
* - взять loginKey (publicKey32) пользователя
* - взять prevGlobalHash / prevLineHash из DB-состояния
* - собрать preimage -> sha256 -> verify signature
* - вставить blocks
* - обновить blockchain_state: lastGlobalNumber/lastGlobalHash (и позже line stuff)
*
* Важно:
* - всё делается в одной транзакции
* - DAO-методы с Connection НЕ закрывают соединение
* Ответ наружу: только reasonCode + serverLastGlobalNumber/serverLastGlobalHash
*/
public final class BlockchainStateService_new {
/** Результат атомарного addBlock */
public static final class AddBlockResult {
public final int lineIndex; // 0..7 (пока ставим 0)
public final int httpStatus; // WireCodes.Status.*
public final int httpStatus;
public final String reasonCode; // null если ok
public final BlockchainStateEntry stateAfter; // состояние после (может быть null)
public final Integer serverLastGlobalNumber; // может быть null при ошибке
public final String serverLastGlobalHash; // может быть null при ошибке
public AddBlockResult(int lineIndex, int httpStatus, String reasonCode, BlockchainStateEntry stateAfter) {
this.lineIndex = lineIndex;
public AddBlockResult(int httpStatus, String reasonCode,
Integer serverLastGlobalNumber, String serverLastGlobalHash) {
this.httpStatus = httpStatus;
this.reasonCode = reasonCode;
this.stateAfter = stateAfter;
this.serverLastGlobalNumber = serverLastGlobalNumber;
this.serverLastGlobalHash = serverLastGlobalHash;
}
public boolean isOk() {
@@ -62,104 +66,145 @@ public final class BlockchainStateService_new {
return instance;
}
/**
* Атомарно добавляет блок (в рамках одной транзакции) и возвращает результат,
* чтобы хэндлер мог заполнить ответ клиенту.
*/
public AddBlockResult addBlockAtomically(
String login,
String blockchainName,
int globalNumber,
String prevGlobalHash,
String prevGlobalHashFromClient,
String blockBytesB64
) {
// Пока не парсим lineIndex из блока — ставим 0, чтобы протокол работал.
// Позже сделаем реальный разбор (и это же место будет правильным для вычисления хэшей).
final int lineIndex = 0;
byte[] blockBytes;
byte[] fullBytes;
try {
blockBytes = decodeBase64(blockBytesB64);
fullBytes = decodeBase64(blockBytesB64);
} catch (Exception e) {
return new AddBlockResult(
lineIndex,
WireCodes.Status.BAD_REQUEST,
"bad_block_base64",
null
);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_base64", null, null);
}
if (login == null || login.isBlank()) {
return new AddBlockResult(lineIndex, WireCodes.Status.BAD_REQUEST, "empty_login", null);
if (login == null || login.isBlank())
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "empty_login", null, null);
if (blockchainName == null || blockchainName.isBlank())
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "empty_blockchain_name", null, null);
if (fullBytes == null || fullBytes.length == 0)
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "empty_block_bytes", null, null);
// Разбор блока (проверит recordSize == fullBytes.length)
final BchBlockEntry_new block;
try {
block = new BchBlockEntry_new(fullBytes);
} catch (Exception e) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_format", null, null);
}
if (blockchainName == null || blockchainName.isBlank()) {
return new AddBlockResult(lineIndex, WireCodes.Status.BAD_REQUEST, "empty_blockchain_name", null);
}
if (blockBytes == null || blockBytes.length == 0) {
return new AddBlockResult(lineIndex, WireCodes.Status.BAD_REQUEST, "empty_block_bytes", null);
// Минимальные sanity-checks запроса vs блока
if (block.recordNumber != globalNumber) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "global_number_mismatch", null, null);
}
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
// 1) получаем пользователя по login (если надо валидировать существование)
// 1) user by login (loginKey нужен для подписи)
SolanaUserEntry u = solanaUsersDAO.getByLogin(c, login);
if (u == null) {
c.rollback();
return new AddBlockResult(
lineIndex,
WireCodes.Status.NOT_FOUND,
"user_not_found",
null
);
return new AddBlockResult(WireCodes.Status.NOT_FOUND, "user_not_found", null, null);
}
// 2) вставляем блок в blocks
insertBlockRow(c, login, blockchainName, globalNumber, prevGlobalHash, blockBytes, lineIndex);
byte[] loginKey32 = u.getLoginKeyByte();
if (loginKey32 == null || loginKey32.length != 32) {
c.rollback();
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_login_key", null, null);
}
// 3) обновляем агрегатное состояние blockchain_state (по blockchainName)
// 2) состояние цепочки по blockchainName
BlockchainStateEntry st = stateDAO.getByBlockchainName(c, blockchainName);
if (st == null) {
c.rollback();
return new AddBlockResult(
lineIndex,
WireCodes.Status.NOT_FOUND,
"blockchain_state_not_found",
null
);
return new AddBlockResult(WireCodes.Status.NOT_FOUND, "blockchain_state_not_found", null, null);
}
// MVP: обновляем “последний глобальный номер”.
// 3) проверка последовательности globalNumber (по DB, а не по клиенту)
int expected = st.getLastGlobalNumber() + 1;
if (globalNumber != expected) {
c.rollback();
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_global_sequence",
st.getLastGlobalNumber(), st.getLastGlobalHash());
}
// 4) prev hashes берём с сервера
byte[] prevGlobalHash32 = hexToBytes32(st.getLastGlobalHash());
short line = block.line;
int lineIndex = normalizeLineIndex(line);
byte[] prevLineHash32 = hexToBytes32(st.getLastLineHash(lineIndex));
// (опционально) можно сверить, что клиент прислал то же ожидание:
if (prevGlobalHashFromClient != null && !prevGlobalHashFromClient.isBlank()) {
String a = nn(prevGlobalHashFromClient).trim();
String b = nn(st.getLastGlobalHash()).trim();
if (!a.equalsIgnoreCase(b)) {
c.rollback();
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "prev_global_hash_mismatch",
st.getLastGlobalNumber(), st.getLastGlobalHash());
}
}
// 5) verify signature
byte[] rawBytes = block.getRawBytes();
byte[] preimage = BchCryptoVerifier_new.buildPreimage(
login,
prevGlobalHash32,
prevLineHash32,
rawBytes
);
byte[] computedHash32 = BchCryptoVerifier_new.sha256(preimage);
// hash, присланный в блоке
byte[] blockHash32 = block.getHash32();
if (!equals32(computedHash32, blockHash32)) {
c.rollback();
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_hash",
st.getLastGlobalNumber(), st.getLastGlobalHash());
}
boolean sigOk = BchCryptoVerifier_new.verifySignature(
computedHash32,
block.getSignature64(),
loginKey32
);
if (!sigOk) {
c.rollback();
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_signature",
st.getLastGlobalNumber(), st.getLastGlobalHash());
}
// 6) вставляем блок в blocks (пока line stuff MVP)
insertBlockRow(c, login, blockchainName, globalNumber, st.getLastGlobalHash(), fullBytes, lineIndex, block.lineNumber);
// 7) обновляем агрегатное состояние
st.setLastGlobalNumber(globalNumber);
st.setLastGlobalHash(nn(prevGlobalHash)); // TODO: заменить на hash нового блока
st.setLastGlobalHash(toHexLower(computedHash32));
st.setUpdatedAtMs(System.currentTimeMillis());
// (линии пока не трогаем — позже внесём логику lineNumber/lineHash)
// линии (пока минимально)
st.setLastLineNumber(lineIndex, block.lineNumber);
st.setLastLineHash(lineIndex, toHexLower(computedHash32)); // пока можно тем же, позже разделим
stateDAO.upsert(c, st);
c.commit();
return new AddBlockResult(lineIndex, WireCodes.Status.OK, null, st);
return new AddBlockResult(WireCodes.Status.OK, null, st.getLastGlobalNumber(), st.getLastGlobalHash());
} catch (Exception e) {
try { c.rollback(); } catch (SQLException ignore) {}
return new AddBlockResult(
lineIndex,
WireCodes.Status.INTERNAL_ERROR,
"internal_error",
null
);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "internal_error", null, null);
} finally {
try { c.setAutoCommit(oldAutoCommit); } catch (SQLException ignore) {}
}
} catch (Exception e) {
return new AddBlockResult(
lineIndex,
WireCodes.Status.INTERNAL_ERROR,
"db_error",
null
);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", null, null);
}
}
@@ -168,9 +213,10 @@ public final class BlockchainStateService_new {
String login,
String blockchainName,
int globalNumber,
String prevGlobalHash,
String prevGlobalHashServer,
byte[] blockBytes,
int lineIndex
int lineIndex,
int lineNumber
) throws SQLException {
BlockEntry e = new BlockEntry();
@@ -179,18 +225,16 @@ public final class BlockchainStateService_new {
e.setBchName(blockchainName);
e.setBlockGlobalNumber(globalNumber);
e.setBlockGlobalPreHashe(nn(prevGlobalHash));
e.setBlockGlobalPreHashe(nn(prevGlobalHashServer));
// Заглушки под линии — позже заменим на реальную логику из blockBytes.
e.setBlockLineIndex(lineIndex);
e.setBlockLineNumber(0);
e.setBlockLinePreHashe("");
e.setBlockLineNumber(lineNumber);
e.setBlockLinePreHashe(nn("")); // можно потом хранить prevLineHash
e.setMsgType(0);
e.setBlockByte(blockBytes);
// NEW: nullable ссылки (не забиваем фейковыми нулями)
// nullable links
e.setToLogin(null);
e.setToBchName(null);
e.setToBlockGlobalNumber(null);
@@ -209,4 +253,40 @@ public final class BlockchainStateService_new {
if (s == null || s.isBlank()) return null;
return Base64.getDecoder().decode(s);
}
private static int normalizeLineIndex(short line) {
int v = line & 0xFFFF;
// пока поддержим 0..7 как “линии”
if (v < 0 || v > 7) return 0;
return v;
}
private static boolean equals32(byte[] a, byte[] b) {
if (a == null || b == null || a.length != 32 || b.length != 32) return false;
int x = 0;
for (int i = 0; i < 32; i++) x |= (a[i] ^ b[i]);
return x == 0;
}
private static byte[] hexToBytes32(String hex) {
if (hex == null) return new byte[32];
String s = hex.trim();
if (s.isEmpty()) return new byte[32];
if (s.length() != 64 || !s.matches("^[0-9a-fA-F]{64}$")) return new byte[32];
byte[] out = new byte[32];
for (int i = 0; i < 32; i++) {
int hi = Character.digit(s.charAt(i * 2), 16);
int lo = Character.digit(s.charAt(i * 2 + 1), 16);
out[i] = (byte) ((hi << 4) | lo);
}
return out;
}
private static String toHexLower(byte[] b32) {
if (b32 == null) return "";
StringBuilder sb = new StringBuilder(b32.length * 2);
for (byte b : b32) sb.append(String.format("%02x", b));
return sb.toString();
}
}
@@ -25,7 +25,6 @@ public final class Net_AddBlock_new_Handler implements JsonMessageHandler {
Net_AddBlock_Response resp = new Net_AddBlock_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setLineIndex(r.lineIndex);
if (r.isOk()) {
resp.setStatus(WireCodes.Status.OK);
@@ -35,13 +34,12 @@ public final class Net_AddBlock_new_Handler implements JsonMessageHandler {
resp.setReasonCode(r.reasonCode);
}
if (r.stateAfter != null) {
resp.setServerLastGlobalNumber(r.stateAfter.getLastGlobalNumber());
resp.setServerLastGlobalHash(r.stateAfter.getLastGlobalHash());
int line = (r.lineIndex >= 0 && r.lineIndex <= 7) ? r.lineIndex : 0;
resp.setServerLastLineNumber(r.stateAfter.getLastLineNumber(line));
resp.setServerLastLineHash(r.stateAfter.getLastLineHash(line));
// Даже при ошибке (например bad_global_sequence) можно вернуть “что сервер считает последним”
if (r.serverLastGlobalNumber != null) {
resp.setServerLastGlobalNumber(r.serverLastGlobalNumber);
}
if (r.serverLastGlobalHash != null) {
resp.setServerLastGlobalHash(r.serverLastGlobalHash);
}
return resp;