SHA256
Обновить shine-users и синхронизацию пользователей
This commit is contained in:
+3
-3
@@ -390,7 +390,7 @@ public final class ArweaveBlockSyncService {
|
||||
|
||||
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
|
||||
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
|
||||
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
|
||||
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
||||
@@ -482,12 +482,12 @@ public final class ArweaveBlockSyncService {
|
||||
try{
|
||||
validateGenericStaging(login);
|
||||
cleanupDAO.cleanupLoginForCanonicalReplay(login);
|
||||
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
|
||||
String bch=login+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=usersDAO.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
INSERT INTO blockchain_state_store (
|
||||
login, fork_number, blockchain_key, size_limit, file_size_bytes,
|
||||
last_block_number, last_block_hash, updated_at_ms)
|
||||
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
|
||||
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login);
|
||||
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
|
||||
|
||||
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
|
||||
}
|
||||
}
|
||||
|
||||
/** Change ONLY the quota projection; 0 means unbounded. */
|
||||
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
|
||||
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
|
||||
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
""")) {
|
||||
ChainRef r = chainRef(blockchainName);
|
||||
ps.setLong(1, limit);
|
||||
ps.setLong(2, System.currentTimeMillis());
|
||||
ps.setString(3, r.login());
|
||||
ps.setInt(4, r.fork());
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
|
||||
*/
|
||||
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
|
||||
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
|
||||
String sql = """
|
||||
UPDATE blockchain_state_store
|
||||
SET
|
||||
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
|
||||
updated_at_ms = ?
|
||||
WHERE
|
||||
LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
AND (file_size_bytes + ?) <= size_limit
|
||||
AND file_size_bytes <= 9223372036854775807 - ?
|
||||
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
|
||||
ps.setString(3, r.login());
|
||||
ps.setInt(4, r.fork());
|
||||
ps.setLong(5, deltaBytes);
|
||||
ps.setLong(6, deltaBytes);
|
||||
return ps.executeUpdate() > 0;
|
||||
}
|
||||
}
|
||||
|
||||
+20
-4
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) {
|
||||
return null;
|
||||
}
|
||||
return mapRow(rs);
|
||||
if (rs.next()) return mapRow(rs);
|
||||
}
|
||||
}
|
||||
// Old forks remain valid separate blockchains even after root rotation.
|
||||
String forkSql = """
|
||||
SELECT u.login,
|
||||
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
|
||||
f.value ->> 'blockchainKey' AS blockchain_key,
|
||||
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
|
||||
FROM solana_user_pda_current u
|
||||
CROSS JOIN LATERAL jsonb_array_elements(
|
||||
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
|
||||
) AS f(value)
|
||||
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
if (major != 1 || (minor != 2 && minor != 3)) return null;
|
||||
return parseUserPdaV12(raw);
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
|
||||
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
|
||||
int major = u8(raw, 5);
|
||||
int minor = u8(raw, 6);
|
||||
if (major != 1 || minor != 2) return null;
|
||||
if (major != 1 || (minor != 2 && minor != 3)) return null;
|
||||
return parseServerProfileV12(raw);
|
||||
}
|
||||
|
||||
|
||||
+15
-2
@@ -38,6 +38,8 @@ import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.ChannelNameStateDAO;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.dao.UserNotificationsStateDAO;
|
||||
import shine.db.dao.UserParamsDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
@@ -53,6 +55,7 @@ import java.util.List;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
@@ -67,6 +70,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
|
||||
|
||||
private static long resolveChainLimit(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
|
||||
return current == null ? 0L : current.getPaidLimitBytes();
|
||||
}
|
||||
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
|
||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||
@@ -281,7 +289,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
recovered.setBlockchainName(user.getBlockchainName());
|
||||
recovered.setLogin(user.getLogin());
|
||||
recovered.setBlockchainKey(user.getBlockchainKey());
|
||||
recovered.setSizeLimit(100_000L);
|
||||
recovered.setSizeLimit(Math.max(0L, resolveChainLimit(user.getBlockchainName())));
|
||||
recovered.setFileSizeBytes(0L);
|
||||
recovered.setLastBlockNumber(-1);
|
||||
recovered.setLastBlockHash(new byte[32]);
|
||||
@@ -335,7 +343,12 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
// 3) лимит (оставляем как было)
|
||||
try {
|
||||
long oldSize = st.getFileSizeBytes();
|
||||
long limit = st.getSizeLimit();
|
||||
// Current synced Solana PDA is authoritative; free users have no PDA.
|
||||
long limit = resolveChainLimit(blockchainName);
|
||||
if (limit != st.getSizeLimit()) {
|
||||
stateDAO.updateSizeLimit(blockchainName, limit);
|
||||
st.setSizeLimit(limit);
|
||||
}
|
||||
long newSize = safeAdd(oldSize, blockBytes.length);
|
||||
|
||||
if (limit > 0 && newSize > limit) {
|
||||
|
||||
+8
-1
@@ -13,6 +13,8 @@ import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.DbController;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.CurrentUserEntry;
|
||||
|
||||
@@ -26,6 +28,11 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
|
||||
|
||||
private static long resolveChainLimit(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
|
||||
return current == null ? 0L : current.getPaidLimitBytes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
|
||||
@@ -80,7 +87,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
|
||||
st.setLastBlockNumber(-1);
|
||||
st.setLastBlockHash(new byte[32]);
|
||||
st.setFileSizeBytes(0);
|
||||
st.setSizeLimit(1_000_000L);
|
||||
st.setSizeLimit(Math.max(0L, resolveChainLimit(u.getBlockchainName())));
|
||||
st.setUpdatedAtMs(System.currentTimeMillis());
|
||||
stateDAO.upsert(st);
|
||||
log.warn("GetUser: восстановлена запись blockchain_state для login={}, blockchainName={}",
|
||||
|
||||
+17
-24
@@ -142,20 +142,17 @@ public final class ShineUsersCodec {
|
||||
null
|
||||
);
|
||||
|
||||
case IX_UPDATE_USERS_ECONOMY_CONFIG ->
|
||||
new ParsedInstruction(
|
||||
TxKind.UPDATE_USERS_ECONOMY_CONFIG,
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
new EconomyConfigState(
|
||||
1,
|
||||
reader.readU64(),
|
||||
reader.readU64(),
|
||||
reader.readU64()
|
||||
),
|
||||
null
|
||||
);
|
||||
case IX_UPDATE_USERS_ECONOMY_CONFIG -> {
|
||||
// Historical v1 transactions contain three u64s, v2 only update fee.
|
||||
int payloadBytes = reader.remaining();
|
||||
EconomyConfigState economy = switch (payloadBytes) {
|
||||
case 8 -> new EconomyConfigState(2, 0L, 0L, 0L, reader.readU64());
|
||||
case 24 -> new EconomyConfigState(1, reader.readU64(), reader.readU64(), reader.readU64(), 20_000L);
|
||||
default -> throw new IllegalArgumentException("Invalid economy config instruction length");
|
||||
};
|
||||
yield new ParsedInstruction(TxKind.UPDATE_USERS_ECONOMY_CONFIG,
|
||||
false, null, null, economy, null);
|
||||
}
|
||||
|
||||
case IX_UPDATE_NAMESPACE_PRICE ->
|
||||
new ParsedInstruction(
|
||||
@@ -260,7 +257,7 @@ public final class ShineUsersCodec {
|
||||
if (formatMajor != 1) {
|
||||
throw new IllegalArgumentException("Unsupported PDA format " + formatMajor + "." + formatMinor);
|
||||
}
|
||||
if (formatMinor == 2) {
|
||||
if (formatMinor == 2 || formatMinor == 3) {
|
||||
return parseUserPdaAccountV12(pdaAddress, slot, rawDataBase64, lastTxSignature, raw);
|
||||
}
|
||||
if (formatMinor == 0) {
|
||||
@@ -862,17 +859,13 @@ public final class ShineUsersCodec {
|
||||
|
||||
public record EconomyConfigState(
|
||||
int version,
|
||||
long registrationFeeLamports,
|
||||
long lamportsPerLimitStep,
|
||||
long startBonusLimit
|
||||
long registrationFeeLamports, // legacy v1 only
|
||||
long lamportsPerLimitStep, // legacy v1 only
|
||||
long startBonusLimit, // legacy v1 only
|
||||
long updateFeeLamports // v2 (v1 fallback 20_000)
|
||||
) {
|
||||
public static EconomyConfigState initial() {
|
||||
return new EconomyConfigState(
|
||||
1,
|
||||
START_REGISTRATION_FEE_LAMPORTS,
|
||||
START_LAMPORTS_PER_LIMIT_STEP,
|
||||
START_BONUS_LIMIT
|
||||
);
|
||||
return new EconomyConfigState(2, 0L, 0L, 0L, 20_000L);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-5
@@ -63,7 +63,7 @@ public final class PostgresStorageRepository
|
||||
"last_error, economy_config_version, " +
|
||||
"registration_fee_lamports, " +
|
||||
"lamports_per_limit_step, " +
|
||||
"start_bonus_limit, updated_at_ms " +
|
||||
"start_bonus_limit, update_fee_lamports, updated_at_ms " +
|
||||
"FROM solana_sync_state WHERE id = 1"
|
||||
);
|
||||
ResultSet resultSet =
|
||||
@@ -106,7 +106,8 @@ public final class PostgresStorageRepository
|
||||
),
|
||||
resultSet.getLong(
|
||||
"start_bonus_limit"
|
||||
)
|
||||
),
|
||||
resultSet.getLong("update_fee_lamports")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -274,6 +275,7 @@ public final class PostgresStorageRepository
|
||||
connection,
|
||||
snapshots
|
||||
);
|
||||
syncBlockchainStateLimits(connection, snapshots);
|
||||
|
||||
reconcileConfirmedKeyRotations(
|
||||
connection,
|
||||
@@ -314,6 +316,7 @@ public final class PostgresStorageRepository
|
||||
connection,
|
||||
snapshots
|
||||
);
|
||||
syncBlockchainStateLimits(connection, snapshots);
|
||||
|
||||
reconcileConfirmedKeyRotations(
|
||||
connection,
|
||||
@@ -337,6 +340,36 @@ public final class PostgresStorageRepository
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy on-chain fork limits into the server's runtime state. 0 = unbounded.
|
||||
* Never touch block tips, used bytes, or keys. Works after PDA updates even
|
||||
* when record_number remains unchanged (future system-only limit mutation).
|
||||
*/
|
||||
private void syncBlockchainStateLimits(Connection connection,
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots) throws SQLException {
|
||||
if (snapshots == null || snapshots.isEmpty()) return;
|
||||
try (PreparedStatement exists = connection.prepareStatement("SELECT to_regclass('public.blockchain_state_store')")) {
|
||||
try (ResultSet rs = exists.executeQuery()) {
|
||||
if (!rs.next() || rs.getString(1) == null) return;
|
||||
}
|
||||
}
|
||||
try (PreparedStatement stmt = connection.prepareStatement("""
|
||||
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
|
||||
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
""")) {
|
||||
for (ShineUsersCodec.UserPdaSnapshot snapshot : snapshots) {
|
||||
if (snapshot == null || snapshot.blockchainForks() == null) continue;
|
||||
for (ShineUsersCodec.BlockchainForkSnapshot fork : snapshot.blockchainForks()) {
|
||||
stmt.setLong(1, fork.paidLimitBytes());
|
||||
stmt.setLong(2, System.currentTimeMillis());
|
||||
stmt.setString(3, snapshot.login());
|
||||
stmt.setInt(4, fork.forkIndex() + 1);
|
||||
stmt.addBatch();
|
||||
}
|
||||
}
|
||||
stmt.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void upsertTxHistory(
|
||||
Connection connection,
|
||||
List<TxHistoryEntry> txEntries
|
||||
@@ -862,8 +895,8 @@ public final class PostgresStorageRepository
|
||||
"last_seen_slot, last_relevant_signature, " +
|
||||
"last_relevant_slot, last_error, economy_config_version, " +
|
||||
"registration_fee_lamports, lamports_per_limit_step, " +
|
||||
"start_bonus_limit, updated_at_ms" +
|
||||
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
"start_bonus_limit, update_fee_lamports, updated_at_ms" +
|
||||
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
||||
"ON CONFLICT (id) DO UPDATE SET " +
|
||||
"status = EXCLUDED.status, " +
|
||||
"ready = EXCLUDED.ready, " +
|
||||
@@ -878,6 +911,7 @@ public final class PostgresStorageRepository
|
||||
"registration_fee_lamports = EXCLUDED.registration_fee_lamports, " +
|
||||
"lamports_per_limit_step = EXCLUDED.lamports_per_limit_step, " +
|
||||
"start_bonus_limit = EXCLUDED.start_bonus_limit, " +
|
||||
"update_fee_lamports = EXCLUDED.update_fee_lamports, " +
|
||||
"updated_at_ms = EXCLUDED.updated_at_ms";
|
||||
|
||||
try (PreparedStatement statement =
|
||||
@@ -898,14 +932,16 @@ public final class PostgresStorageRepository
|
||||
statement.setNull(11, Types.BIGINT);
|
||||
statement.setNull(12, Types.BIGINT);
|
||||
statement.setNull(13, Types.BIGINT);
|
||||
statement.setNull(14, Types.BIGINT);
|
||||
} else {
|
||||
statement.setInt(10, snapshot.economyConfigState().version());
|
||||
statement.setLong(11, snapshot.economyConfigState().registrationFeeLamports());
|
||||
statement.setLong(12, snapshot.economyConfigState().lamportsPerLimitStep());
|
||||
statement.setLong(13, snapshot.economyConfigState().startBonusLimit());
|
||||
statement.setLong(14, snapshot.economyConfigState().updateFeeLamports());
|
||||
}
|
||||
|
||||
bindNullableLong(statement, 14, snapshot.updatedAtMs());
|
||||
bindNullableLong(statement, 15, snapshot.updatedAtMs());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
@@ -934,10 +970,13 @@ public final class PostgresStorageRepository
|
||||
"registration_fee_lamports BIGINT, " +
|
||||
"lamports_per_limit_step BIGINT, " +
|
||||
"start_bonus_limit BIGINT, " +
|
||||
"update_fee_lamports BIGINT, " +
|
||||
"updated_at_ms BIGINT" +
|
||||
")"
|
||||
);
|
||||
|
||||
statement.executeUpdate("ALTER TABLE solana_sync_state ADD COLUMN IF NOT EXISTS update_fee_lamports BIGINT");
|
||||
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO solana_sync_state (id, status, ready) " +
|
||||
"VALUES (1, 'EMPTY', FALSE) " +
|
||||
|
||||
@@ -58,10 +58,10 @@ public final class KeyRotationRebuildService {
|
||||
}
|
||||
private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}}
|
||||
private void replayStaging(KeyRotationSessionEntry s)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=users.getByLogin(s.getLogin());long limit=u!=null&&u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L;long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
|
||||
long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){ps.setLong(1,s.getId());try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);String key=rs.getString(3);byte[] raw=rs.getBytes(4),hash=rs.getBytes(5);String bch=s.getLogin()+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=users.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
|
||||
String target=bch;BlockchainResyncGuard.withBypass(target,()->{Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(target,raw);if(!r.ok())throw new IllegalStateException("canonical replay rejected #"+n+": "+r.reasonCode());});
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}}
|
||||
|
||||
@@ -370,7 +370,7 @@ public final class PeriodicBlockchainSyncService {
|
||||
state.setBlockchainName(currentUser.getBlockchainName());
|
||||
state.setLogin(currentUser.getLogin());
|
||||
state.setBlockchainKey(currentUser.getBlockchainKey());
|
||||
state.setSizeLimit(currentUser.getPaidLimitBytes() > 0 ? currentUser.getPaidLimitBytes() : 100_000L);
|
||||
state.setSizeLimit(currentUser.getPaidLimitBytes());
|
||||
state.setFileSizeBytes(existingState == null ? 0L : existingState.getFileSizeBytes());
|
||||
state.setLastBlockNumber(existingState == null ? -1 : existingState.getLastBlockNumber());
|
||||
state.setLastBlockHash(existingState == null ? null : existingState.getLastBlockHash());
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
client.version=1.20.59
|
||||
server.version=1.16.30
|
||||
client.version=1.20.60
|
||||
server.version=1.16.31
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# SHiNE User PDA 1.3 — Root-signature, system limits, economy v2
|
||||
|
||||
## Canonical binary record
|
||||
|
||||
* Outer record layout and fork size **remain unchanged** from PDA 1.2; `paid_limit_bytes` remains `u32` (4 bytes) in **every fork**.
|
||||
* The new `format_minor = 3`. On create every fork limit is `0`. No `additional_limit` instruction argument or paid top-up.
|
||||
* `0` means **unlimited total blockchain bytes**, positive `N` means maximum `N` bytes. This does not remove per-block/request limits.
|
||||
* Canonical signing preimage = **exact serialized unsigned PDA bytes**, omitting **only four quota bytes in each fork**. Keep original physical `record_len` and variable-block `payload_len` fields unchanged in the canonical preimage; changing length values would change hashes.
|
||||
* `SHA256(canonical signing bytes)` is verified by an Ed25519 instruction from the Root Key. The 64-byte signature stored in PDA is **Root Key's signature**. The contract verifies signatures; it never signs for the user.
|
||||
* Normal update: one root Ed25519 instruction. Full key rotation: old root Ed25519 followed by new root Ed25519; stored signature is from new root. New root/client/blockchain keys must be rotated together. Blockchain Key remains for signing user-blockchain content, not User PDA.
|
||||
* Changes to on-chain limits are **not implemented** in this patch. Future privileged instruction must mutate ONLY the 4 bytes and have explicit authorization/audit. It must not permit untrusted PDA input to override the limit.
|
||||
* Every new fork starts with `paid_limit_bytes = 0` (unlimited), regardless of the previous fork's limit. Historical forks retain their own values. The existing fork cooldown is retained for ordinary forks.
|
||||
* `prev_record_hash` for a predecessor v1.2 is SHA256(physical v1.2 unsigned bytes). For v1.3 it is SHA256(canonical unsigned bytes without limit bytes). The first signed update migrates v1.2 -> 1.3 at the same PDA address.
|
||||
* Old v1.2 accounts remain readable and usable for Stars support operations. Their record signatures follow the old v1.2 rule until the first root-authorized migration to 1.3.
|
||||
|
||||
## Economy PDA v2
|
||||
|
||||
The on-chain state contains **only** `version=2:u8` and `update_fee_lamports:u64` (9 useful bytes; old allocated space may remain padded). No registration fee or quota price in this PDA. Registration fee lives in the namespace PDA. User PDA update fee comes from this economy PDA.
|
||||
|
||||
For existing v1 economy PDA, the program temporarily reads the legacy state and uses the previous fixed update fee 20,000 lamports; submit the authorized `IX_UPDATE_USERS_ECONOMY_CONFIG` with **only** 8-byte LE `update_fee_lamports` to migrate the existing economy PDA to v2. Its PDA address does not change.
|
||||
|
||||
## Wire changes
|
||||
|
||||
* `IX_CREATE_USER_PDA(3)`: removed `additional_limit:u64` after `created_at_ms`.
|
||||
* `IX_UPDATE_USER_PDA(4)`: removed `additional_limit:u64` after `updated_at_ms`; retained `auth_mode:u8` with **only 1 (root)** supported. The normal update requires the old root; rotation requires both old/new root signatures.
|
||||
* `IX_UPDATE_USERS_ECONOMY_CONFIG(2)`: now **only** `update_fee_lamports:u64`; same authority and account list as v1.
|
||||
|
||||
## Server
|
||||
|
||||
* Keep `size_limit=0` in runtime `blockchain_state_store` as unlimited, and `size_limit>0` as the active block-size total quota.
|
||||
* Both the optimistic handler check and the atomic SQL file-size update must treat zero as unlimited.
|
||||
* Synchronize limits for all historical forks from `solana_user_pda_current` into existing runtime blockchain states without resetting tips, size, or key material; use current fork value when accepting a block. If a valid free user has no Solana PDA yet, default to 0.
|
||||
* Limit mutation is not yet exposed; future change will require sync by slot/signature even without a changed `record_number`.
|
||||
|
||||
## Deployment order
|
||||
|
||||
1. Deploy server and client handling v1.2 + 1.3, economy v2 and zero-unlimited semantics together.
|
||||
2. Upgrade Solana `shine_users` program with the existing Program ID using authorized upgrade procedures; do **not** rotate seeds or PDA addresses.
|
||||
3. Migrate economy PDA v1 -> v2 through the authorized update instruction (default 20,000 lamports or chosen value).
|
||||
4. Create a new v1.3 account and verify stored root signature, first zero quota, added blocks >100 KB, Stars support, old v1.2 read, first v1.2 -> v1.3 root migration.
|
||||
5. Test full root/client/blockchain rotation requiring signatures from **both roots**, old fork read, and paid namespace creation.
|
||||
|
||||
Deployment and live signed chain transactions have **not** been performed by this source patch.
|
||||
@@ -2915,7 +2915,8 @@
|
||||
"text_303": "When the current queue limit is filled, a new limit with a lower coefficient will open.",
|
||||
"text_300": "Tickets are tied to queue 1 and the recipient’s address you specify when you purchase.",
|
||||
"text_301": "The payment is considered in USD, and the write-off goes to SOL at the USDT/SOL rate, which is checked at the time of the transaction.",
|
||||
"text_305": "Refresh balance"
|
||||
"text_305": "Refresh balance",
|
||||
"unlimited": "Unlimited"
|
||||
},
|
||||
"device_view": {
|
||||
"text_008": "Are you sure you want to close the other sessions?",
|
||||
|
||||
@@ -3101,7 +3101,8 @@
|
||||
"text_302": "Если курс уезжает слишком далеко, покупка отклоняется. Для интерфейса заложен допуск 3%.",
|
||||
"text_303": "Когда текущий лимит очереди заполнится, откроется новый лимит с более низким коэффициентом.",
|
||||
"text_304": "Номер билета нужно сохранить отдельно: именно по нему удобно отслеживать, когда он дойдет до выплаты.",
|
||||
"text_305": "Скопировать адрес в буфер обмена"
|
||||
"text_305": "Скопировать адрес в буфер обмена",
|
||||
"unlimited": "Без ограничений"
|
||||
},
|
||||
"solana_users_init_view": {
|
||||
"text_001": "Подключите кошелёк и выполните init_users_economy_config.",
|
||||
|
||||
@@ -482,10 +482,12 @@ export function render({navigate, chrome}) {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const savedRoot = String(saved?.rootKey || '').trim();
|
||||
const savedBlockchain = String(saved?.blockchainKey || '').trim();
|
||||
const savedClient = String(saved?.clientKey || '').trim();
|
||||
if (savedBlockchain && savedClient) {
|
||||
if (savedRoot && savedBlockchain && savedClient) {
|
||||
return {
|
||||
rootPrivatePkcs8B64: savedRoot,
|
||||
blockchainPrivatePkcs8B64: savedBlockchain,
|
||||
clientPrivatePkcs8B64: savedClient,
|
||||
payerAddress: await clientAddressFromPrivatePkcs8(savedBlockchain),
|
||||
@@ -513,10 +515,14 @@ export function render({navigate, chrome}) {
|
||||
if (!equalBytes(derivedClientPublic, currentPda.clientKey)) {
|
||||
throw new Error(t('screens.access_servers_view.text_013'));
|
||||
}
|
||||
if (!equalBytes(base64ToBytes(keyBundle.rootPair.publicKeyB64), currentPda.rootKey)) {
|
||||
throw new Error('Root Key не соответствует PDA');
|
||||
}
|
||||
|
||||
await authService.persistSelectedKeys(sessionLogin, storagePwd, keyBundle);
|
||||
|
||||
return {
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
payerAddress: clientAddressFromPublicB64(keyBundle.blockchainPair.publicKeyB64),
|
||||
@@ -546,6 +552,7 @@ export function render({navigate, chrome}) {
|
||||
const tx = await updateShineUserPdaOnSolana({
|
||||
login: sessionLogin,
|
||||
solanaEndpoint,
|
||||
rootPrivatePkcs8B64: signingMaterial.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signingMaterial.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signingMaterial.clientPrivatePkcs8B64,
|
||||
accessServers: normalizedList,
|
||||
|
||||
@@ -21,10 +21,7 @@ import { getUsdtBalance, getUsdtAsset } from '../services/solana-usdt-service.js
|
||||
import { openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
|
||||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer } from '../services/arweave-file-service.js';
|
||||
import {
|
||||
calcLimitTopupPriceLamports,
|
||||
getLimitStepBytes,
|
||||
getShineBlockchainUsage,
|
||||
getShineUsersEconomyConfig,
|
||||
updateShineUserPdaOnSolana,
|
||||
} from '../services/shine-blockchain-wallet-service.js?v=202605300007';
|
||||
import {
|
||||
@@ -71,16 +68,6 @@ function lamportsToSolText(lamportsBigInt) {
|
||||
return formatNumber(value, { minimumFractionDigits: 0, maximumFractionDigits: 9 });
|
||||
}
|
||||
|
||||
function formatLimitTopupError(error) {
|
||||
const message = String(error?.message || '').trim();
|
||||
const logs = Array.isArray(error?.logs) ? error.logs.join(' | ') : '';
|
||||
const haystack = `${message} ${logs}`.toLowerCase();
|
||||
if (haystack.includes('insufficient funds for rent')) {
|
||||
return t('screens.wallet_view.text_106');
|
||||
}
|
||||
return t('screens.wallet_view.text_153', { value1: message || 'unknown' });
|
||||
}
|
||||
|
||||
function createModeBackButton(renderWalletChoice) {
|
||||
const backBtn = document.createElement('button');
|
||||
backBtn.className = 'text-btn';
|
||||
@@ -537,32 +524,14 @@ export function render({navigate, chrome}) {
|
||||
|
||||
async function resolveWalletSigningMaterial() {
|
||||
const { login, storagePwd } = sessionArgsOrThrow();
|
||||
let saved = null;
|
||||
try {
|
||||
saved = await loadEncryptedUserSecrets(login, storagePwd);
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const blockchainKey = String(saved?.blockchainKey || '').trim();
|
||||
const clientKey = String(saved?.clientKey || '').trim();
|
||||
if (blockchainKey && clientKey) {
|
||||
return {
|
||||
rootPrivatePkcs8B64: '',
|
||||
blockchainPrivatePkcs8B64: blockchainKey,
|
||||
clientPrivatePkcs8B64: clientKey,
|
||||
};
|
||||
}
|
||||
|
||||
const password = window.prompt(
|
||||
t('dialogs.pages.wallet_view.prompt_001'),
|
||||
'',
|
||||
);
|
||||
// Root key is intentionally not kept in IndexedDB or encrypted key vault.
|
||||
// Solana PDA updates are rare, so require a fresh password on every update.
|
||||
const password = window.prompt(t('dialogs.pages.wallet_view.prompt_001'), '');
|
||||
if (password == null) throw new Error(t('screens.wallet_view.text_138'));
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(login, password);
|
||||
await authService.persistSelectedKeys(login, storagePwd, keyBundle);
|
||||
return {
|
||||
rootPrivatePkcs8B64: '',
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
};
|
||||
@@ -1419,14 +1388,11 @@ export function render({navigate, chrome}) {
|
||||
actions.className = 'stack';
|
||||
actions.innerHTML = `
|
||||
<button class="ghost-btn" id="refresh-shine-bch" style="width:100%;">${th('screens.wallet_view.text_266')}</button>
|
||||
<button class="primary-btn" id="topup-shine-limit" style="width:100%;">${th('screens.wallet_view.text_267')}</button>
|
||||
`;
|
||||
const refreshBtn = actions.querySelector('#refresh-shine-bch');
|
||||
const topupBtn = actions.querySelector('#topup-shine-limit');
|
||||
|
||||
const setButtonsDisabled = (disabled) => {
|
||||
refreshBtn.disabled = disabled;
|
||||
topupBtn.disabled = disabled;
|
||||
};
|
||||
|
||||
const refreshUsage = async () => {
|
||||
@@ -1440,11 +1406,11 @@ export function render({navigate, chrome}) {
|
||||
fetchServerBlockchainState(),
|
||||
]);
|
||||
if (modeToken !== activeModeToken) return;
|
||||
limitValue.textContent = formatKbFromBytes(usage.paidLimitBytes);
|
||||
limitValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(usage.paidLimitBytes);
|
||||
const usedServerBytes = BigInt(Math.max(0, Number(serverState.sizeBytes || 0)));
|
||||
const leftServerBytes = usage.paidLimitBytes > usedServerBytes ? (usage.paidLimitBytes - usedServerBytes) : 0n;
|
||||
usedValue.textContent = formatKbFromBytes(usedServerBytes);
|
||||
leftValue.textContent = formatKbFromBytes(leftServerBytes);
|
||||
leftValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(leftServerBytes);
|
||||
pdaLabel.textContent = `PDA: ${usage.userPda}`;
|
||||
endpointLabel.textContent = `RPC: ${usage.endpoint}`;
|
||||
updatedLabel.textContent = t('screens.wallet_view.text_162', { value1: nowRu() });
|
||||
@@ -1623,7 +1589,7 @@ export function render({navigate, chrome}) {
|
||||
pdaLastEl.textContent = t('screens.wallet_view.text_167', { value1: usage.lastBlockNumber });
|
||||
pdaHashEl.textContent = `Hash: ${usage.lastBlockHashHex || '–'}`;
|
||||
pdaUsedEl.textContent = t('screens.wallet_view.text_168', { value1: formatBytesRu(usage.usedBytes) });
|
||||
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: formatBytesRu(usage.paidLimitBytes) });
|
||||
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatBytesRu(usage.paidLimitBytes) });
|
||||
pdaArweaveEl.textContent = `Arweave tx: ${usage.arweaveTxId || '–'}`;
|
||||
if (usage.arweaveTxId) {
|
||||
pdaArweaveLinkEl.href = buildArweaveDataUrl({ gateway: state.entrySettings.arweaveServer, txId: usage.arweaveTxId });
|
||||
@@ -1778,7 +1744,6 @@ export function render({navigate, chrome}) {
|
||||
rootPrivatePkcs8B64: signing.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signing.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signing.clientPrivatePkcs8B64,
|
||||
additionalLimitBytes: 0n,
|
||||
nextUsedBytes: BigInt(Math.max(0, serverState.sizeBytes)),
|
||||
nextLastBlockNumber: serverState.lastNumber,
|
||||
nextLastBlockHashHex: serverState.lastHash,
|
||||
|
||||
@@ -209,6 +209,7 @@ export class KeyRotationClient {
|
||||
payerPrivatePkcs8B64:oldBundle.blockchainPair.privatePkcs8B64,
|
||||
authorityMode:'root',
|
||||
newRootPublicKey32:base64ToBytes(newBundle.rootPair.publicKeyB64),
|
||||
newRootPrivatePkcs8B64:newBundle.rootPair.privatePkcs8B64,
|
||||
nextClientPublicKey32:base64ToBytes(newBundle.clientPair.publicKeyB64),
|
||||
newBlockchainPublicKey32:base64ToBytes(newBundle.blockchainPair.publicKeyB64),
|
||||
newBlockchainPrivatePkcs8B64:newBundle.blockchainPair.privatePkcs8B64,
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
export {
|
||||
calcLimitTopupPriceLamports,
|
||||
getLimitStepBytes,
|
||||
getShineBlockchainUsage,
|
||||
getShineUsersEconomyConfig,
|
||||
updateShineUserPdaOnSolana,
|
||||
|
||||
@@ -13,11 +13,11 @@ import { getNamespace, assertLoginInNamespace, normalizeFullLogin, userPdaSeed32
|
||||
const MAGIC = 'SHiNE';
|
||||
const FORMAT_MAJOR = 1;
|
||||
const FORMAT_MINOR_LEGACY = 0;
|
||||
const FORMAT_MINOR_CURRENT = 2;
|
||||
const FORMAT_MINOR_CURRENT = 3;
|
||||
const FORMAT_MINOR_PREVIOUS = 2;
|
||||
const SHINE_PAYMENTS_INFLOW_VAULT_SEED = 'shine_payments_inflow_vault';
|
||||
const SHINE_USERS_USER_PDA_SEED_PREFIX = 'user_login=';
|
||||
const SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX = 'promo_seller=';
|
||||
const LIMIT_STEP = 10_000n;
|
||||
const ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';
|
||||
const SYSVAR_INSTRUCTIONS_ID = 'Sysvar1nstructions1111111111111111111111111';
|
||||
const PROMO_SIGN_PREFIX = 'shine_promo_v1:';
|
||||
@@ -56,7 +56,7 @@ function normalizeAccessServers(values) {
|
||||
const login = normalizeLogin(value);
|
||||
if (!login || seen.has(login)) continue;
|
||||
if (result.length >= MAX_EFFECTIVE_ACCESS_SERVERS) {
|
||||
throw new Error('PDA 1.2 поддерживает максимум один сервер доступа');
|
||||
throw new Error('PDA 1.3 поддерживает максимум один сервер доступа');
|
||||
}
|
||||
seen.add(login);
|
||||
result.push(login);
|
||||
@@ -122,13 +122,11 @@ function makeReader(bytes) {
|
||||
|
||||
function parseUsersEconomyConfig(dataBytes) {
|
||||
const view = new DataView(dataBytes.buffer, dataBytes.byteOffset, dataBytes.byteLength);
|
||||
if (dataBytes.byteLength < 25) throw new Error('Некорректный economy config');
|
||||
return {
|
||||
version: view.getUint8(0),
|
||||
registrationFeeLamports: view.getBigUint64(1, true),
|
||||
lamportsPerLimitStep: view.getBigUint64(9, true),
|
||||
startBonusLimit: view.getBigUint64(17, true),
|
||||
};
|
||||
if (dataBytes.byteLength < 9) throw new Error('Некорректный economy config');
|
||||
const version = view.getUint8(0);
|
||||
if (version === 2) return { version, updateFeeLamports: view.getBigUint64(1, true) };
|
||||
if (version === 1 && dataBytes.byteLength >= 25) return { version, updateFeeLamports: 20_000n };
|
||||
throw new Error('Неподдерживаемая версия economy config');
|
||||
}
|
||||
|
||||
function buildEd25519IxData(sig64, pubkey32, messageBytes) {
|
||||
@@ -157,7 +155,7 @@ function buildEd25519IxData(sig64, pubkey32, messageBytes) {
|
||||
|
||||
function normalizeServerAddresses(values, fallback = null) {
|
||||
const src = Array.isArray(values) && values.length ? values : (fallback ? [fallback] : []);
|
||||
if (src.length > 1) throw new Error('PDA 1.2 поддерживает только один адрес сервера');
|
||||
if (src.length > 1) throw new Error('PDA 1.3 поддерживает только один адрес сервера');
|
||||
return src.map((item) => {
|
||||
const address = String(item?.address ?? item?.serverAddress ?? '').trim();
|
||||
const bytes = new TextEncoder().encode(address);
|
||||
@@ -225,7 +223,7 @@ function parseV12Pda(bytes, header) {
|
||||
if (payload.remaining !== 0) throw new Error('Повреждённый BlockchainRegistry');
|
||||
} else if (blockType === BLOCK_TYPE_SERVER_PROFILE) {
|
||||
const count = payload.readU8();
|
||||
if (count !== 1) throw new Error('PDA 1.2 допускает ровно один адрес в ServerProfileBlock');
|
||||
if (count !== 1) throw new Error('PDA 1.3 допускает ровно один адрес в ServerProfileBlock');
|
||||
serverAddresses = [];
|
||||
for (let j = 0; j < count; j += 1) {
|
||||
serverAddresses.push({
|
||||
@@ -237,13 +235,13 @@ function parseV12Pda(bytes, header) {
|
||||
if (payload.remaining !== 0) throw new Error('Повреждённый ServerProfileBlock');
|
||||
} else if (blockType === BLOCK_TYPE_ACCESS_SERVERS) {
|
||||
const count = payload.readU8();
|
||||
if (count > 1) throw new Error('PDA 1.2 допускает максимум один access server');
|
||||
if (count > 1) throw new Error('PDA 1.3 допускает максимум один access server');
|
||||
accessServers = [];
|
||||
for (let j = 0; j < count; j += 1) accessServers.push(payload.readStrU8());
|
||||
if (payload.remaining !== 0) throw new Error('Повреждённый AccessServersBlock');
|
||||
}
|
||||
}
|
||||
if (!rootKey || !clientKey || !forks) throw new Error('PDA 1.2 не содержит обязательные блоки');
|
||||
if (!rootKey || !clientKey || !forks) throw new Error('PDA не содержит обязательные блоки');
|
||||
const firstAddress = serverAddresses[0] || null;
|
||||
const blockchain = activeBlockchainCompatibility(header.login, forks);
|
||||
return {
|
||||
@@ -279,7 +277,7 @@ export function parseShineUserPda(dataBytes) {
|
||||
const formatMajor = reader.readU8();
|
||||
const formatMinor = reader.readU8();
|
||||
const recordLen = reader.readU16();
|
||||
if (formatMajor !== FORMAT_MAJOR || formatMinor !== FORMAT_MINOR_CURRENT) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
|
||||
if (formatMajor !== FORMAT_MAJOR || ![FORMAT_MINOR_PREVIOUS, FORMAT_MINOR_CURRENT].includes(formatMinor)) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
|
||||
if (recordLen < 9 + 64 || recordLen > bytes.length) throw new Error('Некорректный record_len');
|
||||
const createdAtMs = reader.readU64();
|
||||
const updatedAtMs = reader.readU64();
|
||||
@@ -313,6 +311,58 @@ function writeVariableBlock(out, blockType, writer) {
|
||||
out[lenPos + 1] = (len >>> 8) & 0xff;
|
||||
}
|
||||
|
||||
/** PDA 1.3 canonical signing message. Only the four limit bytes per fork are skipped.
|
||||
* All physical length fields remain unchanged, so changing a limit preserves signatures.
|
||||
*/
|
||||
export function canonicalPdaSigningBytes(unsignedBytes) {
|
||||
const bytes = toUint8Array(unsignedBytes);
|
||||
if (bytes.length < 64 || new TextDecoder().decode(bytes.slice(0, 5)) !== MAGIC || bytes[5] !== 1 || bytes[6] !== 3) {
|
||||
throw new Error('Ожидается unsigned PDA v1.3');
|
||||
}
|
||||
const rd16 = (i) => bytes[i] | (bytes[i + 1] << 8);
|
||||
if (rd16(7) !== bytes.length + 64) throw new Error('Неверный record_len');
|
||||
let c = 9 + 8 + 8 + 4 + 32;
|
||||
c += 1 + bytes[c];
|
||||
const blocks = bytes[c++];
|
||||
const chunks = [bytes.slice(0, c)];
|
||||
let registry = false;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
const start = c;
|
||||
if (c + 2 > bytes.length) throw new Error('Обрезан PDA');
|
||||
const type = bytes[c], ver = bytes[c + 1];
|
||||
c += 2;
|
||||
if (type === 1 || type === 2) {
|
||||
c += 32;
|
||||
if (c > bytes.length) throw new Error('Обрезан PDA');
|
||||
chunks.push(bytes.slice(start, c));
|
||||
continue;
|
||||
}
|
||||
if (c + 2 > bytes.length) throw new Error('Обрезан блок PDA');
|
||||
const len = rd16(c); c += 2;
|
||||
const end = c + len;
|
||||
if (end > bytes.length) throw new Error('Обрезан payload PDA');
|
||||
if (type === 3 && ver === 0) {
|
||||
if (registry || c + 2 > end) throw new Error('Некорректный реестр fork');
|
||||
registry = true;
|
||||
const count = rd16(c);
|
||||
if (!count || len !== 2 + count * 44) throw new Error('Некорректная длина реестра fork');
|
||||
chunks.push(bytes.slice(start, c + 2));
|
||||
c += 2;
|
||||
for (let k = 0; k < count; k++) {
|
||||
chunks.push(bytes.slice(c, c + 40)); // never sign these four limit bytes
|
||||
c += 44;
|
||||
}
|
||||
if (c !== end) throw new Error('Некорректная длина fork');
|
||||
} else chunks.push(bytes.slice(start, end));
|
||||
c = end;
|
||||
}
|
||||
if (!registry || c !== bytes.length) throw new Error('Некорректная структура PDA');
|
||||
const out = new Uint8Array(chunks.reduce((n, b) => n + b.length, 0));
|
||||
let at = 0;
|
||||
for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }
|
||||
return out;
|
||||
}
|
||||
|
||||
export function serializeUnsignedRecordFromState(stateLike) {
|
||||
const state = stateLike || {};
|
||||
const login = String(state.login || '');
|
||||
@@ -379,7 +429,6 @@ export function serializeCreateUserPdaArgs(args) {
|
||||
pushStrU8(out, args.login);
|
||||
pushBytes(out, toUint8Array(args.rootKey32, 32));
|
||||
pushU64LE(out, args.createdAtMs);
|
||||
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
|
||||
pushBytes(out, toUint8Array(args.clientKey32, 32));
|
||||
pushBytes(out, toUint8Array(args.blockchainKey32, 32));
|
||||
const addresses = normalizeServerAddresses(args.serverAddresses || []);
|
||||
@@ -403,7 +452,6 @@ function serializeUpdateUserPdaArgs(args) {
|
||||
pushStrU8(out, args.login);
|
||||
pushBytes(out, toUint8Array(args.rootKey32, 32));
|
||||
pushU64LE(out, args.updatedAtMs);
|
||||
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
|
||||
pushBytes(out, toUint8Array(args.clientKey32, 32));
|
||||
out.push(Number(args.authMode) & 0xff);
|
||||
if (args.newBlockchainKey32) {
|
||||
@@ -570,7 +618,6 @@ async function createShineUserPdaOnSolana({
|
||||
const blockchainKey32 = base64ToBytes(keyBundle.blockchainPair.publicKeyB64);
|
||||
const clientKey32 = base64ToBytes(keyBundle.clientPair.publicKeyB64);
|
||||
const rootPriv = await importPkcs8Ed25519(keyBundle.rootPair.privatePkcs8B64);
|
||||
const bchPriv = await importPkcs8Ed25519(keyBundle.blockchainPair.privatePkcs8B64);
|
||||
const ctx = await buildCommonContext({
|
||||
login: cleanLogin,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
@@ -587,8 +634,7 @@ async function createShineUserPdaOnSolana({
|
||||
? [namespace.serverLogin] : accessServers;
|
||||
const ecoInfo = await ctx.connection.getAccountInfo(ctx.economyConfigPda, 'confirmed');
|
||||
if (!ecoInfo?.data) throw new Error('Economy config не инициализирован.');
|
||||
const startBonusLimit = parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)).startBonusLimit;
|
||||
if (startBonusLimit > 0xffffffffn) throw new Error('Стартовый лимит не помещается в PDA 1.2 u32');
|
||||
parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)); // economy PDA presence/version
|
||||
const createdAtMs = BigInt(Date.now());
|
||||
const addresses = normalizeServerAddresses(serverAddresses, isServer ? { addressFormatType, addressFormatVersion, address: serverAddress } : null);
|
||||
const initial = {
|
||||
@@ -599,14 +645,13 @@ async function createShineUserPdaOnSolana({
|
||||
prevRecordHash: new Uint8Array(32),
|
||||
rootKey: rootKey32,
|
||||
clientKey: clientKey32,
|
||||
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: startBonusLimit }],
|
||||
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: 0n }],
|
||||
serverAddresses: addresses,
|
||||
accessServers: effectiveAccessServers,
|
||||
};
|
||||
const unsigned = serializeUnsignedRecordFromState(initial);
|
||||
const hash = await sha256Bytes(unsigned);
|
||||
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
|
||||
const rootSig = await signBytes(rootPriv, hash);
|
||||
const recordSig = await signBytes(bchPriv, hash);
|
||||
|
||||
// Namespace читается из цепи, комиссия никогда не берётся из старого economy.registrationFee.
|
||||
const certMessage = registrar
|
||||
@@ -617,9 +662,8 @@ async function createShineUserPdaOnSolana({
|
||||
data: buildEd25519IxData(registrar, namespace.registrarPublicKey32, certMessage),
|
||||
}) : null;
|
||||
|
||||
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, additionalLimitBytes: 0n, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: recordSig, registrarSignature64: registrar });
|
||||
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: rootSig, registrarSignature64: registrar });
|
||||
const rootIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(rootSig, rootKey32, hash) });
|
||||
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, blockchainKey32, hash) });
|
||||
const createIx = new ctx.solana.TransactionInstruction({
|
||||
programId: ctx.usersProgram,
|
||||
keys: [
|
||||
@@ -636,7 +680,7 @@ async function createShineUserPdaOnSolana({
|
||||
try {
|
||||
const tx = new ctx.solana.Transaction();
|
||||
if (registrarIx) tx.add(registrarIx);
|
||||
tx.add(rootIx, recordIx, createIx);
|
||||
tx.add(rootIx, createIx);
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, tx, [ctx.payerKeypair]);
|
||||
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001`, registrationFeeLamports: namespace.registrationFeeLamports };
|
||||
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
|
||||
@@ -692,7 +736,6 @@ export async function updateShineUserPdaOnSolana({
|
||||
payerPrivatePkcs8B64 = '',
|
||||
blockchainPrivatePkcs8B64,
|
||||
authorityMode,
|
||||
additionalLimitBytes = 0n,
|
||||
newRootPublicKey32 = null,
|
||||
newRootPrivatePkcs8B64 = '',
|
||||
nextClientPublicKey32 = null,
|
||||
@@ -709,8 +752,6 @@ export async function updateShineUserPdaOnSolana({
|
||||
payerPrivatePkcs8B64: String(payerPrivatePkcs8B64 || blockchainPrivatePkcs8B64 || ''),
|
||||
solanaEndpoint,
|
||||
});
|
||||
const addLimit = BigInt(additionalLimitBytes || 0);
|
||||
if (addLimit < 0n || addLimit % LIMIT_STEP !== 0n) throw new Error(`Лимит можно увеличивать только шагом ${LIMIT_STEP}`);
|
||||
const rootKey = newRootPublicKey32 ? toUint8Array(newRootPublicKey32, 32) : current.rootKey;
|
||||
const clientKey = nextClientPublicKey32 ? toUint8Array(nextClientPublicKey32, 32) : current.clientKey;
|
||||
const rootChanged = bytesToBase58(rootKey) !== bytesToBase58(current.rootKey);
|
||||
@@ -719,10 +760,9 @@ export async function updateShineUserPdaOnSolana({
|
||||
if ((rootChanged || clientChanged) && !fullKeyRotation) {
|
||||
throw new Error('Root/client keys меняются только как полная ротация: новый root + новый client + новый blockchain fork');
|
||||
}
|
||||
const authMode = fullKeyRotation ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
|
||||
if (authorityMode != null) {
|
||||
const requestedMode = authorityMode === 'root' || authorityMode === AUTH_MODE_ROOT ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
|
||||
if (requestedMode !== authMode) throw new Error(fullKeyRotation ? 'Полная ротация требует root authority' : 'Обычное обновление PDA выполняется blockchain authority');
|
||||
const authMode = AUTH_MODE_ROOT; // Root is the sole user PDA authority in v1.3.
|
||||
if (authorityMode != null && authorityMode !== 'root' && authorityMode !== 'blockchain' && authorityMode !== AUTH_MODE_ROOT && authorityMode !== AUTH_MODE_BLOCKCHAIN) {
|
||||
throw new Error('Неподдерживаемый режим authority');
|
||||
}
|
||||
|
||||
const updatedAtMs = BigInt(Date.now());
|
||||
@@ -733,13 +773,8 @@ export async function updateShineUserPdaOnSolana({
|
||||
if (forks.some((f) => bytesToBase58(f.blockchainKey) === bytesToBase58(appendedKey))) throw new Error('Этот blockchain key уже был в истории fork');
|
||||
const lastForkAt = BigInt(forks.at(-1).createdAtMs);
|
||||
if (!fullKeyRotation && updatedAtMs - lastForkAt < FORK_COOLDOWN_MS) throw new Error('Новый fork обычным blockchain authority можно создавать не чаще одного раза в 72 часа');
|
||||
const newLimit = forks.at(-1).paidLimitBytes + addLimit;
|
||||
if (newLimit > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
|
||||
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: newLimit });
|
||||
} else if (addLimit > 0n) {
|
||||
const active = forks.at(-1);
|
||||
active.paidLimitBytes += addLimit;
|
||||
if (active.paidLimitBytes > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
|
||||
// Each new fork starts at 0 (unlimited); older forks keep their own limits.
|
||||
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: 0n });
|
||||
}
|
||||
|
||||
let addresses = current.serverAddresses;
|
||||
@@ -755,7 +790,8 @@ export async function updateShineUserPdaOnSolana({
|
||||
createdAtMs: current.createdAtMs,
|
||||
updatedAtMs,
|
||||
recordNumber: current.recordNumber + 1,
|
||||
prevRecordHash: await sha256Bytes(current.unsignedBytes),
|
||||
prevRecordHash: await sha256Bytes(current.formatMinor === FORMAT_MINOR_CURRENT
|
||||
? canonicalPdaSigningBytes(current.unsignedBytes) : current.unsignedBytes),
|
||||
rootKey,
|
||||
clientKey,
|
||||
forks,
|
||||
@@ -763,29 +799,21 @@ export async function updateShineUserPdaOnSolana({
|
||||
accessServers: nextAccess,
|
||||
};
|
||||
const unsigned = serializeUnsignedRecordFromState(next);
|
||||
const hash = await sha256Bytes(unsigned);
|
||||
|
||||
const oldAuthorityPub = fullKeyRotation ? current.rootKey : current.forks.at(-1).blockchainKey;
|
||||
const oldAuthorityPrivB64 = fullKeyRotation ? rootPrivatePkcs8B64 : blockchainPrivatePkcs8B64;
|
||||
if (!oldAuthorityPrivB64) throw new Error(fullKeyRotation ? 'Для полной ротации нужен старый root private key' : 'Для обновления PDA нужен blockchain private key');
|
||||
const oldAuthorityPriv = await importPkcs8Ed25519(oldAuthorityPrivB64);
|
||||
const authSig = await signBytes(oldAuthorityPriv, hash);
|
||||
|
||||
let recordSignerPub;
|
||||
let recordSignerPrivB64;
|
||||
if (appendedKey) {
|
||||
recordSignerPub = appendedKey;
|
||||
recordSignerPrivB64 = newBlockchainPrivatePkcs8B64;
|
||||
} else {
|
||||
recordSignerPub = current.forks.at(-1).blockchainKey;
|
||||
recordSignerPrivB64 = blockchainPrivatePkcs8B64;
|
||||
}
|
||||
if (!recordSignerPrivB64) throw new Error('Нет приватного ключа нового authority для подписи новой PDA');
|
||||
const recordSignerPriv = await importPkcs8Ed25519(recordSignerPrivB64);
|
||||
const recordSig = await signBytes(recordSignerPriv, hash);
|
||||
|
||||
const authIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(authSig, oldAuthorityPub, hash) });
|
||||
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, recordSignerPub, hash) });
|
||||
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
|
||||
if (!rootPrivatePkcs8B64) throw new Error('Для изменения PDA нужен приватный Root Key');
|
||||
const oldRootPriv = await importPkcs8Ed25519(rootPrivatePkcs8B64);
|
||||
// Never allow an old root to authorize replacing itself without a new root signature.
|
||||
const oldRootSig = await signBytes(oldRootPriv, hash);
|
||||
const nextRootPriv = rootChanged
|
||||
? await importPkcs8Ed25519(newRootPrivatePkcs8B64)
|
||||
: oldRootPriv;
|
||||
const recordSig = rootChanged ? await signBytes(nextRootPriv, hash) : oldRootSig;
|
||||
const authIx = rootChanged ? new ctx.solana.TransactionInstruction({
|
||||
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(oldRootSig, current.rootKey, hash),
|
||||
}) : null;
|
||||
const recordIx = new ctx.solana.TransactionInstruction({
|
||||
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, rootKey, hash),
|
||||
});
|
||||
const updateIx = new ctx.solana.TransactionInstruction({
|
||||
programId: ctx.usersProgram,
|
||||
keys: [
|
||||
@@ -796,10 +824,10 @@ export async function updateShineUserPdaOnSolana({
|
||||
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
|
||||
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
||||
],
|
||||
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, additionalLimitBytes: addLimit, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
|
||||
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
|
||||
});
|
||||
try {
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(authIx, recordIx, updateIx), [ctx.payerKeypair]);
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(...(authIx ? [authIx] : []), recordIx, updateIx), [ctx.payerKeypair]);
|
||||
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), paidLimitBytes: forks.at(-1).paidLimitBytes, forkCount: forks.length };
|
||||
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
|
||||
}
|
||||
@@ -811,20 +839,11 @@ export async function updateServerOnSolana({ login, keyBundle, serverAddress, se
|
||||
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
authorityMode: 'blockchain',
|
||||
authorityMode: 'root',
|
||||
serverAddresses: serverAddresses || [{ addressFormatType, addressFormatVersion, address: serverAddress }],
|
||||
});
|
||||
}
|
||||
|
||||
export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLimitStep) {
|
||||
const add = BigInt(additionalLimitBytes || 0);
|
||||
const pricePerStep = BigInt(lamportsPerLimitStep || 0);
|
||||
if (add < 0n || add % LIMIT_STEP !== 0n) throw new Error(`Увеличение лимита должно быть кратно ${LIMIT_STEP} байт`);
|
||||
return (add / LIMIT_STEP) * pricePerStep;
|
||||
}
|
||||
|
||||
export function getLimitStepBytes() { return LIMIT_STEP; }
|
||||
|
||||
function supportData(tag, senderLogin, recipientLogin, amountLamports, starCents, target) {
|
||||
const out = [tag];
|
||||
const putString = (value) => { const bytes = new TextEncoder().encode(String(value)); if (bytes.length > 255) throw new Error('Слишком длинный login'); out.push(bytes.length, ...bytes); };
|
||||
|
||||
@@ -25,7 +25,8 @@ entrypoint!(process_instruction);
|
||||
|
||||
const MAGIC: &[u8; 5] = b"SHiNE";
|
||||
const FORMAT_MAJOR: u8 = 1;
|
||||
const FORMAT_MINOR: u8 = 2;
|
||||
const FORMAT_MINOR: u8 = 3;
|
||||
const PREVIOUS_FORMAT_MINOR: u8 = 2;
|
||||
const LEGACY_FORMAT_MINOR: u8 = 0;
|
||||
const MAX_AUTO_REALLOC_INCREASE: usize = 10_000;
|
||||
const ZERO_HASH: [u8; 32] = [0; 32];
|
||||
@@ -36,7 +37,6 @@ const BLOCK_TYPE_SERVER_PROFILE: u8 = 30;
|
||||
const BLOCK_TYPE_ACCESS_SERVERS: u8 = 40;
|
||||
const BLOCK_VERSION_0: u8 = 0;
|
||||
|
||||
const AUTH_MODE_BLOCKCHAIN: u8 = 0;
|
||||
const AUTH_MODE_ROOT: u8 = 1;
|
||||
const DAY_MS: u64 = 86_400_000;
|
||||
const FORK_COOLDOWN_MS: u64 = 3 * DAY_MS;
|
||||
@@ -202,7 +202,6 @@ pub struct CreateUserPdaArgs {
|
||||
pub login: String,
|
||||
pub root_key: Pubkey,
|
||||
pub created_at_ms: u64,
|
||||
pub additional_limit: u64,
|
||||
pub client_key: Pubkey,
|
||||
pub blockchain_key: Pubkey,
|
||||
pub server_addresses: Vec<ServerAddressRecordV12>,
|
||||
@@ -216,7 +215,6 @@ pub struct UpdateUserPdaArgs {
|
||||
pub login: String,
|
||||
pub root_key: Pubkey,
|
||||
pub updated_at_ms: u64,
|
||||
pub additional_limit: u64,
|
||||
pub client_key: Pubkey,
|
||||
pub auth_mode: u8,
|
||||
pub new_blockchain_key: Option<Pubkey>,
|
||||
@@ -232,17 +230,13 @@ pub struct CloseLegacyUserPdaArgs {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UpdateUsersEconomyConfigArgs {
|
||||
pub registration_fee_lamports: u64,
|
||||
pub lamports_per_limit_step: u64,
|
||||
pub start_bonus_limit: u64,
|
||||
pub update_fee_lamports: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UsersEconomyConfigState {
|
||||
pub version: u8,
|
||||
pub registration_fee_lamports: u64,
|
||||
pub lamports_per_limit_step: u64,
|
||||
pub start_bonus_limit: u64,
|
||||
pub update_fee_lamports: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -327,9 +321,7 @@ fn process_instruction<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>],
|
||||
}
|
||||
IX_UPDATE_USERS_ECONOMY_CONFIG => {
|
||||
let args = UpdateUsersEconomyConfigArgs {
|
||||
registration_fee_lamports: r.read_u64()?,
|
||||
lamports_per_limit_step: r.read_u64()?,
|
||||
start_bonus_limit: r.read_u64()?,
|
||||
update_fee_lamports: r.read_u64()?,
|
||||
};
|
||||
r.finish()?;
|
||||
process_update_users_economy_config(program_id, accounts, args)
|
||||
@@ -431,7 +423,6 @@ fn parse_create_args(r: &mut Reader<'_>) -> Result<CreateUserPdaArgs, ProgramErr
|
||||
login: r.read_string_u8()?,
|
||||
root_key: r.read_pubkey()?,
|
||||
created_at_ms: r.read_u64()?,
|
||||
additional_limit: r.read_u64()?,
|
||||
client_key: r.read_pubkey()?,
|
||||
blockchain_key: r.read_pubkey()?,
|
||||
server_addresses: parse_server_addresses(r)?,
|
||||
@@ -449,7 +440,6 @@ fn parse_update_args(r: &mut Reader<'_>) -> Result<UpdateUserPdaArgs, ProgramErr
|
||||
let login = r.read_string_u8()?;
|
||||
let root_key = r.read_pubkey()?;
|
||||
let updated_at_ms = r.read_u64()?;
|
||||
let additional_limit = r.read_u64()?;
|
||||
let client_key = r.read_pubkey()?;
|
||||
let auth_mode = r.read_u8()?;
|
||||
let new_blockchain_key = match r.read_u8()? {
|
||||
@@ -464,7 +454,6 @@ fn parse_update_args(r: &mut Reader<'_>) -> Result<UpdateUserPdaArgs, ProgramErr
|
||||
login,
|
||||
root_key,
|
||||
updated_at_ms,
|
||||
additional_limit,
|
||||
client_key,
|
||||
auth_mode,
|
||||
new_blockchain_key,
|
||||
@@ -496,10 +485,8 @@ fn process_init_users_economy_config(program_id: &Pubkey, accounts: &[AccountInf
|
||||
require!(users_economy_config_pda.data_is_empty(), ShineUsersError::SystemAlreadyInitialized);
|
||||
|
||||
let state = UsersEconomyConfigState {
|
||||
version: 1,
|
||||
registration_fee_lamports: settings::START_REGISTRATION_FEE_LAMPORTS,
|
||||
lamports_per_limit_step: settings::START_LAMPORTS_PER_LIMIT_STEP,
|
||||
start_bonus_limit: settings::START_BONUS_LIMIT,
|
||||
version: 2,
|
||||
update_fee_lamports: settings::UPDATE_FEE_LAMPORTS,
|
||||
};
|
||||
let data = serialize_users_economy_config(&state);
|
||||
create_pda_account(
|
||||
@@ -526,12 +513,10 @@ fn process_update_users_economy_config(program_id: &Pubkey, accounts: &[AccountI
|
||||
let (expected_pda, _) = find_users_economy_config_pda(program_id);
|
||||
require_keys_eq!(expected_pda, *users_economy_config_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||
require!(users_economy_config_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
|
||||
require!(args.lamports_per_limit_step > 0, ShineUsersError::InvalidRecordData);
|
||||
|
||||
let mut state = read_users_economy_config(users_economy_config_pda)?;
|
||||
state.registration_fee_lamports = args.registration_fee_lamports;
|
||||
state.lamports_per_limit_step = args.lamports_per_limit_step;
|
||||
state.start_bonus_limit = args.start_bonus_limit;
|
||||
state.version = 2;
|
||||
state.update_fee_lamports = args.update_fee_lamports;
|
||||
write_pda_exact(users_economy_config_pda, &serialize_users_economy_config(&state))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -639,10 +624,9 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
|
||||
validate_access_servers(&args.access_servers)?;
|
||||
for server in &args.access_servers { validate_full_login(server)?; }
|
||||
validate_inflow_vault(inflow_vault)?;
|
||||
require!(args.additional_limit % settings::LIMIT_STEP == 0, ShineUsersError::InvalidLimitIncrement);
|
||||
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
|
||||
require!(!users_economy_config_pda.is_writable, ShineUsersError::InvalidAccountData);
|
||||
let economy = read_users_economy_config(users_economy_config_pda)?;
|
||||
read_users_economy_config(users_economy_config_pda)?;
|
||||
let (expected_pda, bump) = find_user_pda(program_id, &args.login);
|
||||
require_keys_eq!(expected_pda, *user_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||
require!(user_pda.owner == &system_program::id(), ShineUsersError::UserAlreadyExists);
|
||||
@@ -653,13 +637,11 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
|
||||
let signature = args.registrar_signature.as_ref().ok_or(ShineUsersError::CertificateRequired)?;
|
||||
let registrar = namespace.registrar_pubkey.ok_or(ShineUsersError::InvalidNamespace)?;
|
||||
let message = certificate_inner_message(&args.login, &args.root_key, &args.blockchain_key, &args.client_key)?;
|
||||
verify_ed25519_signature_instruction(instructions_sysvar, -3, ®istrar, signature, &message)?;
|
||||
verify_ed25519_signature_instruction(instructions_sysvar, -2, ®istrar, signature, &message)?;
|
||||
},
|
||||
_ => return Err(ShineUsersError::InvalidNamespace.into()),
|
||||
}
|
||||
|
||||
let start_balance_u64 = economy.start_bonus_limit.checked_add(args.additional_limit).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
let start_balance = u32::try_from(start_balance_u64).map_err(|_| ProgramError::from(ShineUsersError::PaidLimitTooLarge))?;
|
||||
let now_ms = current_time_ms()?;
|
||||
validate_client_time_ms(args.created_at_ms, now_ms)?;
|
||||
let fork_created_at_ms = args.created_at_ms;
|
||||
@@ -675,7 +657,7 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
|
||||
forks: vec![ForkRecordV12 {
|
||||
blockchain_key: args.blockchain_key,
|
||||
created_at_ms: fork_created_at_ms,
|
||||
paid_limit_bytes: start_balance,
|
||||
paid_limit_bytes: 0,
|
||||
}],
|
||||
server_addresses: args.server_addresses,
|
||||
access_servers: args.access_servers,
|
||||
@@ -683,11 +665,11 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
|
||||
};
|
||||
|
||||
let unsigned = serialize_unsigned_record_v12(&record)?;
|
||||
let unsigned_hash = hashv(&[&unsigned]);
|
||||
// На create root доказывает владение recovery-ключом, а сама новая запись
|
||||
// подписывается активным blockchain-key (новым authority состояния).
|
||||
verify_ed25519_instruction_pubkey_message(instructions_sysvar, -2, &record.root_key, unsigned_hash.as_ref())?;
|
||||
record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &record.active_fork()?.blockchain_key, &args.signature, unsigned_hash.as_ref())?;
|
||||
let unsigned_hash = hashv(&[&signed_bytes_without_limits(&unsigned)?]);
|
||||
// PDA 1.3: only root signs the on-chain identity record. The blockchain
|
||||
// key signs content blocks but cannot authorize changes to this PDA.
|
||||
// For free namespaces registrar certificate is the previous ed25519 ix (-2).
|
||||
record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &record.root_key, &args.signature, unsigned_hash.as_ref())?;
|
||||
|
||||
let serialized = serialize_record_with_stats(&record, SupportStats::default())?;
|
||||
let serialized = pad_to_fixed_size(serialized, settings::USER_PDA_SPACE)?;
|
||||
@@ -702,9 +684,7 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
|
||||
let namespace_remainder = namespace.registration_fee
|
||||
.checked_sub(rent_paid_by_signer)
|
||||
.ok_or(ProgramError::from(ShineUsersError::RegistrationFeeBelowRent))?;
|
||||
let vault_fee = namespace_remainder
|
||||
.checked_add(limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?)
|
||||
.ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
let vault_fee = namespace_remainder;
|
||||
create_pda_account(
|
||||
signer,
|
||||
user_pda,
|
||||
@@ -738,7 +718,6 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
||||
validate_server_addresses(&args.server_addresses)?;
|
||||
validate_access_servers(&args.access_servers)?;
|
||||
validate_inflow_vault(inflow_vault)?;
|
||||
require!(args.additional_limit % settings::LIMIT_STEP == 0, ShineUsersError::InvalidLimitIncrement);
|
||||
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
|
||||
let economy = read_users_economy_config(users_economy_config_pda)?;
|
||||
|
||||
@@ -751,33 +730,25 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
||||
require!(user_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
|
||||
|
||||
let raw = read_pda_all(user_pda)?;
|
||||
require!(record_format_minor(&raw)? == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat);
|
||||
require!(matches!(record_format_minor(&raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat);
|
||||
let old_record = deserialize_record_v12_from_pda(&raw)?;
|
||||
require!(old_record.login == args.login, ShineUsersError::ImmutableFieldChanged);
|
||||
require!(args.updated_at_ms >= old_record.updated_at_ms, ShineUsersError::InvalidRecordData);
|
||||
let now_ms = current_time_ms()?;
|
||||
validate_client_time_ms(args.updated_at_ms, now_ms)?;
|
||||
require!(args.auth_mode == AUTH_MODE_BLOCKCHAIN || args.auth_mode == AUTH_MODE_ROOT, ShineUsersError::InvalidInstruction);
|
||||
require!(args.auth_mode == AUTH_MODE_ROOT, ShineUsersError::InvalidInstruction);
|
||||
|
||||
let root_changed = args.root_key != old_record.root_key;
|
||||
let client_changed = args.client_key != old_record.client_key;
|
||||
let full_key_rotation = root_changed && client_changed && args.new_blockchain_key.is_some();
|
||||
|
||||
// root/client меняются только вместе с созданием нового blockchain fork.
|
||||
// Обычные update и обычный fork всегда авторизуются текущим blockchain key.
|
||||
// Rotating root/client remains atomic with appending a fresh blockchain key.
|
||||
if root_changed || client_changed {
|
||||
require!(full_key_rotation, ShineUsersError::AmbiguousAuthorityRotation);
|
||||
require!(args.auth_mode == AUTH_MODE_ROOT, ShineUsersError::RootChangeRequiresRoot);
|
||||
} else {
|
||||
require!(args.auth_mode == AUTH_MODE_BLOCKCHAIN, ShineUsersError::RootModeRequiresFullRotation);
|
||||
}
|
||||
|
||||
let old_active_key = old_record.active_fork()?.blockchain_key;
|
||||
let old_authority = if full_key_rotation { old_record.root_key } else { old_active_key };
|
||||
let old_authority = old_record.root_key;
|
||||
let mut forks = old_record.forks.clone();
|
||||
|
||||
let additional_limit_u32 = u32::try_from(args.additional_limit).map_err(|_| ProgramError::from(ShineUsersError::PaidLimitTooLarge))?;
|
||||
let mut appended_key = None;
|
||||
if let Some(new_key) = args.new_blockchain_key {
|
||||
for fork in &forks {
|
||||
require!(fork.blockchain_key != new_key, ShineUsersError::DuplicateBlockchainKey);
|
||||
@@ -785,17 +756,20 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
||||
if !full_key_rotation {
|
||||
enforce_fork_cooldown(old_record.active_fork()?.created_at_ms, args.updated_at_ms)?;
|
||||
}
|
||||
|
||||
let current_limit = old_record.active_fork()?.paid_limit_bytes;
|
||||
let new_limit = current_limit.checked_add(additional_limit_u32).ok_or(ProgramError::from(ShineUsersError::PaidLimitTooLarge))?;
|
||||
forks.push(ForkRecordV12 { blockchain_key: new_key, created_at_ms: args.updated_at_ms, paid_limit_bytes: new_limit });
|
||||
appended_key = Some(new_key);
|
||||
} else if additional_limit_u32 > 0 {
|
||||
let active = forks.last_mut().ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?;
|
||||
active.paid_limit_bytes = active.paid_limit_bytes.checked_add(additional_limit_u32).ok_or(ProgramError::from(ShineUsersError::PaidLimitTooLarge))?;
|
||||
// Each new fork starts with its own unlimited quota (0).
|
||||
// Historical forks retain their existing system-owned limits.
|
||||
forks.push(ForkRecordV12 { blockchain_key: new_key, created_at_ms: args.updated_at_ms, paid_limit_bytes: 0 });
|
||||
}
|
||||
|
||||
let prev_hash = hash_unsigned_record_v12(&old_record)?;
|
||||
let old_record_len = u16::from_le_bytes([raw[7], raw[8]]) as usize;
|
||||
let old_unsigned = &raw[..old_record_len - 64];
|
||||
// Existing v1.2 links were hashed including limits. The first migration
|
||||
// link commits to the exact old bytes; v1.3 links omit quota bytes.
|
||||
let prev_hash = if raw[6] == PREVIOUS_FORMAT_MINOR {
|
||||
hash(old_unsigned).to_bytes()
|
||||
} else {
|
||||
hash(&signed_bytes_without_limits(old_unsigned)?).to_bytes()
|
||||
};
|
||||
let mut new_record = UserRecordV12 {
|
||||
created_at_ms: old_record.created_at_ms,
|
||||
updated_at_ms: args.updated_at_ms,
|
||||
@@ -810,27 +784,21 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
||||
signature: [0; 64],
|
||||
};
|
||||
|
||||
let record_signer = if let Some(new_key) = appended_key {
|
||||
new_key
|
||||
} else {
|
||||
new_record.active_fork()?.blockchain_key
|
||||
};
|
||||
|
||||
let unsigned = serialize_unsigned_record_v12(&new_record)?;
|
||||
let unsigned_hash = hashv(&[&unsigned]);
|
||||
// Первая подпись разрешает переход старым authority. Вторая подпись хранится
|
||||
// в PDA и принадлежит authority уже нового состояния.
|
||||
verify_ed25519_instruction_pubkey_message(instructions_sysvar, -2, &old_authority, unsigned_hash.as_ref())?;
|
||||
new_record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &record_signer, &args.signature, unsigned_hash.as_ref())?;
|
||||
let unsigned_hash = hashv(&[&signed_bytes_without_limits(&unsigned)?]);
|
||||
// Normal update: one root signature. Root rotation: both old and new root
|
||||
// authorize the same canonical hash (old at -2, new at -1).
|
||||
if root_changed {
|
||||
verify_ed25519_instruction_pubkey_message(instructions_sysvar, -2, &old_authority, unsigned_hash.as_ref())?;
|
||||
}
|
||||
new_record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &new_record.root_key, &args.signature, unsigned_hash.as_ref())?;
|
||||
|
||||
let stats = read_support_stats(&raw)?;
|
||||
let serialized = serialize_record_with_stats(&new_record, stats)?;
|
||||
ensure_pda_size_and_rent(user_pda, signer, system_program_ai, serialized.len())?;
|
||||
write_pda_exact(user_pda, &serialized)?;
|
||||
|
||||
let topup_fee = limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?;
|
||||
let total_fee = topup_fee.checked_add(settings::UPDATE_FEE_LAMPORTS).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
transfer_lamports(signer, inflow_vault, system_program_ai, total_fee)?;
|
||||
transfer_lamports(signer, inflow_vault, system_program_ai, economy.update_fee_lamports)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -912,7 +880,7 @@ fn process_support_user(program_id: &Pubkey, accounts: &[AccountInfo], args: Sup
|
||||
require!(sender_pda.owner == program_id && recipient_pda.owner == program_id, ShineUsersError::InvalidAccountOwner);
|
||||
let sender_raw = read_pda_all(sender_pda)?;
|
||||
let recipient_raw = read_pda_all(recipient_pda)?;
|
||||
require!(record_format_minor(&sender_raw)? == FORMAT_MINOR && record_format_minor(&recipient_raw)? == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat);
|
||||
require!(matches!(record_format_minor(&sender_raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR) && matches!(record_format_minor(&recipient_raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat);
|
||||
let sender_record = deserialize_record_v12_from_pda(&sender_raw)?;
|
||||
let recipient_record = deserialize_record_v12_from_pda(&recipient_raw)?;
|
||||
require!(sender_record.login == args.sender_login && recipient_record.login == args.recipient_login, ShineUsersError::InvalidRecordData);
|
||||
@@ -929,8 +897,8 @@ fn process_support_user(program_id: &Pubkey, accounts: &[AccountInfo], args: Sup
|
||||
let mut recipient_stats = read_support_stats(&recipient_raw)?;
|
||||
sender_stats.support_sent = sender_stats.support_sent.checked_add(args.amount_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
recipient_stats.support_received = recipient_stats.support_received.checked_add(author_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
let sender_data = serialize_record_with_stats(&sender_record, sender_stats)?;
|
||||
let recipient_data = serialize_record_with_stats(&recipient_record, recipient_stats)?;
|
||||
let sender_data = append_stats_to_existing_signed_record(&sender_raw, sender_stats)?;
|
||||
let recipient_data = append_stats_to_existing_signed_record(&recipient_raw, recipient_stats)?;
|
||||
ensure_pda_size_and_rent(sender_pda, sender, system_program_ai, sender_data.len())?;
|
||||
ensure_pda_size_and_rent(recipient_pda, sender, system_program_ai, recipient_data.len())?;
|
||||
transfer_lamports(sender, recipient, system_program_ai, recipient_amount)?;
|
||||
@@ -964,13 +932,13 @@ fn process_support_dao(program_id: &Pubkey, accounts: &[AccountInfo], args: Supp
|
||||
require_keys_eq!(find_user_pda(program_id, &args.sender_login).0, *sender_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||
require!(sender_pda.owner == program_id, ShineUsersError::InvalidAccountOwner);
|
||||
let raw = read_pda_all(sender_pda)?;
|
||||
require!(record_format_minor(&raw)? == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat);
|
||||
require!(matches!(record_format_minor(&raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat);
|
||||
let record = deserialize_record_v12_from_pda(&raw)?;
|
||||
require!(record.login == args.sender_login, ShineUsersError::InvalidRecordData);
|
||||
require_keys_eq!(record.active_fork()?.blockchain_key, *sender.key, ShineUsersError::InvalidSigner);
|
||||
let mut stats = read_support_stats(&raw)?;
|
||||
stats.dao_direct = stats.dao_direct.checked_add(args.amount_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
let data = serialize_record_with_stats(&record, stats)?;
|
||||
let data = append_stats_to_existing_signed_record(&raw, stats)?;
|
||||
ensure_pda_size_and_rent(sender_pda, sender, system_program_ai, data.len())?;
|
||||
transfer_lamports(sender, inflow_vault, system_program_ai, args.amount_lamports)?;
|
||||
write_pda_exact(sender_pda, &data)?;
|
||||
@@ -1009,11 +977,9 @@ fn process_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo],
|
||||
}
|
||||
|
||||
fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(1 + 8 + 8 + 8);
|
||||
let mut out = Vec::with_capacity(1 + 8);
|
||||
out.push(state.version);
|
||||
out.extend_from_slice(&state.registration_fee_lamports.to_le_bytes());
|
||||
out.extend_from_slice(&state.lamports_per_limit_step.to_le_bytes());
|
||||
out.extend_from_slice(&state.start_bonus_limit.to_le_bytes());
|
||||
out.extend_from_slice(&state.update_fee_lamports.to_le_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1027,13 +993,16 @@ fn validate_users_economy_config_pda(program_id: &Pubkey, pda: &AccountInfo) ->
|
||||
fn read_users_economy_config(pda: &AccountInfo) -> Result<UsersEconomyConfigState, ProgramError> {
|
||||
let raw = read_pda_all(pda)?;
|
||||
require!(!raw.is_empty(), ShineUsersError::EmptyPdaData);
|
||||
require!(raw.len() >= 25 && raw[0] == 1, ShineUsersError::InvalidAccountData);
|
||||
Ok(UsersEconomyConfigState {
|
||||
version: raw[0],
|
||||
registration_fee_lamports: u64::from_le_bytes(raw[1..9].try_into().unwrap()),
|
||||
lamports_per_limit_step: u64::from_le_bytes(raw[9..17].try_into().unwrap()),
|
||||
start_bonus_limit: u64::from_le_bytes(raw[17..25].try_into().unwrap()),
|
||||
})
|
||||
// Existing v1 config remains readable until an authority-signed update to v2.
|
||||
// Its update fee was previously hardcoded; do not reinterpret v1 bytes as fee.
|
||||
match raw[0] {
|
||||
1 if raw.len() >= 25 => Ok(UsersEconomyConfigState { version: 1, update_fee_lamports: settings::UPDATE_FEE_LAMPORTS }),
|
||||
2 if raw.len() >= 9 => Ok(UsersEconomyConfigState {
|
||||
version: 2,
|
||||
update_fee_lamports: u64::from_le_bytes(raw[1..9].try_into().unwrap()),
|
||||
}),
|
||||
_ => Err(ShineUsersError::InvalidAccountData.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_format_minor(raw: &[u8]) -> Result<u8, ProgramError> {
|
||||
@@ -1046,7 +1015,7 @@ fn record_format_minor(raw: &[u8]) -> Result<u8, ProgramError> {
|
||||
fn deserialize_record_v12_from_pda(raw: &[u8]) -> Result<UserRecordV12, ProgramError> {
|
||||
require!(raw.len() >= 9, ShineUsersError::InvalidRecordData);
|
||||
require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic);
|
||||
require!(raw[5] == FORMAT_MAJOR && raw[6] == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat);
|
||||
require!(raw[5] == FORMAT_MAJOR && matches!(raw[6], FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat);
|
||||
let record_len = u16::from_le_bytes([raw[7], raw[8]]) as usize;
|
||||
require!(record_len >= 9 + 64, ShineUsersError::InvalidRecordLength);
|
||||
require!(record_len <= raw.len(), ShineUsersError::InvalidRecordLength);
|
||||
@@ -1226,6 +1195,60 @@ fn serialize_unsigned_record_v12(record: &UserRecordV12) -> Result<Vec<u8>, Prog
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Canonical signing bytes of a physical PDA 1.3 unsigned record:
|
||||
/// all original headers, lengths and blocks, EXCEPT four limit bytes per fork.
|
||||
/// Works over raw bytes to preserve unknown future variable blocks verbatim.
|
||||
fn signed_bytes_without_limits(unsigned: &[u8]) -> Result<Vec<u8>, ProgramError> {
|
||||
require!(unsigned.len() >= 9 + 8 + 8 + 4 + 32 + 1 + 1, ShineUsersError::InvalidRecordLength);
|
||||
require!(&unsigned[..5] == MAGIC && unsigned[5] == FORMAT_MAJOR && unsigned[6] == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat);
|
||||
let expected = u16::from_le_bytes([unsigned[7], unsigned[8]]) as usize;
|
||||
require!(expected == unsigned.len() + 64, ShineUsersError::InvalidRecordLength);
|
||||
let mut c = 9 + 8 + 8 + 4 + 32;
|
||||
let login_len = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)? as usize;
|
||||
c = c.checked_add(1 + login_len).ok_or(ShineUsersError::MathOverflow)?;
|
||||
let blocks = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)? as usize;
|
||||
c += 1;
|
||||
let mut out = Vec::with_capacity(unsigned.len());
|
||||
out.extend_from_slice(&unsigned[..c]);
|
||||
let mut found_registry = false;
|
||||
for _ in 0..blocks {
|
||||
let start = c;
|
||||
let ty = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)?;
|
||||
let ver = *unsigned.get(c + 1).ok_or(ShineUsersError::InvalidRecordLength)?;
|
||||
c += 2;
|
||||
if ty == BLOCK_TYPE_ROOT_KEY || ty == BLOCK_TYPE_CLIENT_KEY {
|
||||
c = c.checked_add(32).ok_or(ShineUsersError::MathOverflow)?;
|
||||
require!(c <= unsigned.len(), ShineUsersError::InvalidRecordLength);
|
||||
out.extend_from_slice(&unsigned[start..c]);
|
||||
continue;
|
||||
}
|
||||
let len_slice = unsigned.get(c..c + 2).ok_or(ShineUsersError::InvalidRecordLength)?;
|
||||
let len = u16::from_le_bytes([len_slice[0], len_slice[1]]) as usize;
|
||||
c += 2;
|
||||
let end = c.checked_add(len).ok_or(ShineUsersError::MathOverflow)?;
|
||||
require!(end <= unsigned.len(), ShineUsersError::InvalidRecordLength);
|
||||
if ty == BLOCK_TYPE_BLOCKCHAIN_REGISTRY && ver == BLOCK_VERSION_0 {
|
||||
require!(!found_registry, ShineUsersError::InvalidRecordData);
|
||||
found_registry = true;
|
||||
let count_slice = unsigned.get(c..c + 2).ok_or(ShineUsersError::InvalidRecordLength)?;
|
||||
let count = u16::from_le_bytes([count_slice[0], count_slice[1]]) as usize;
|
||||
require!(count > 0 && len == 2 + count * 44, ShineUsersError::InvalidRecordLength);
|
||||
out.extend_from_slice(&unsigned[start..c + 2]);
|
||||
c += 2;
|
||||
for _ in 0..count {
|
||||
out.extend_from_slice(&unsigned[c..c + 40]);
|
||||
c += 44;
|
||||
}
|
||||
require!(c == end, ShineUsersError::InvalidRecordLength);
|
||||
} else {
|
||||
out.extend_from_slice(&unsigned[start..end]);
|
||||
}
|
||||
c = end;
|
||||
}
|
||||
require!(found_registry && c == unsigned.len(), ShineUsersError::InvalidRecordLength);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn serialize_full_record_v12(record: &UserRecordV12) -> Result<Vec<u8>, ProgramError> {
|
||||
let mut out = serialize_unsigned_record_v12(record)?;
|
||||
out.extend_from_slice(&record.signature);
|
||||
@@ -1259,11 +1282,18 @@ fn serialize_record_with_stats(record: &UserRecordV12, stats: SupportStats) -> R
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn hash_unsigned_record_v12(record: &UserRecordV12) -> Result<[u8; 32], ProgramError> {
|
||||
let unsigned = serialize_unsigned_record_v12(record)?;
|
||||
let digest = hashv(&[&unsigned]);
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(digest.as_ref());
|
||||
/// Update only the program-owned Stars stats tail; never alter the signed
|
||||
/// PDA record (particularly v1.2 signatures during transition to 1.3).
|
||||
fn append_stats_to_existing_signed_record(raw: &[u8], stats: SupportStats) -> Result<Vec<u8>, ProgramError> {
|
||||
require!(raw.len() >= 9, ShineUsersError::InvalidRecordLength);
|
||||
let signed_len = u16::from_le_bytes([raw[7], raw[8]]) as usize;
|
||||
require!(signed_len >= 9 + 64 && signed_len <= raw.len(), ShineUsersError::InvalidRecordLength);
|
||||
let mut out = Vec::with_capacity(signed_len + SUPPORT_STATS_LEN);
|
||||
out.extend_from_slice(&raw[..signed_len]);
|
||||
out.push(SUPPORT_STATS_VERSION);
|
||||
out.extend_from_slice(&stats.support_sent.to_le_bytes());
|
||||
out.extend_from_slice(&stats.support_received.to_le_bytes());
|
||||
out.extend_from_slice(&stats.dao_direct.to_le_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1549,7 +1579,6 @@ pub fn find_namespace_pda(program_id: &Pubkey, name: &str) -> (Pubkey, u8) {
|
||||
Pubkey::find_program_address(&[&seed], program_id)
|
||||
}
|
||||
fn find_users_economy_config_pda(program_id: &Pubkey) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USERS_ECONOMY_CONFIG_SEED], program_id) }
|
||||
fn limit_fee_lamports(limit_delta: u64, lamports_per_limit_step: u64) -> Result<u64, ProgramError> { (limit_delta / settings::LIMIT_STEP).checked_mul(lamports_per_limit_step).ok_or(ProgramError::from(ShineUsersError::MathOverflow)) }
|
||||
fn pad_to_fixed_size(mut bytes: Vec<u8>, target_size: usize) -> Result<Vec<u8>, ProgramError> { require!(bytes.len() <= target_size, ShineUsersError::RecordTooLarge); bytes.resize(target_size, 0); Ok(bytes) }
|
||||
|
||||
fn read_pda_all(pda: &AccountInfo) -> Result<Vec<u8>, ProgramError> { Ok(pda.try_borrow_data().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?.to_vec()) }
|
||||
|
||||
@@ -13,13 +13,5 @@ pub const USERS_ECONOMY_CONFIG_SPACE: usize = 32;
|
||||
pub const SHINE_PAYMENTS_PROGRAM_ID: &str = "SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v";
|
||||
/// Seed inflow-вольта в программе `shine_payments`.
|
||||
pub const SHINE_PAYMENTS_INFLOW_VAULT_SEED: &[u8] = b"shine_payments_inflow_vault";
|
||||
/// Стартовая комиссия регистрации (0.01 SOL) для initial economy-конфига.
|
||||
pub const START_REGISTRATION_FEE_LAMPORTS: u64 = 10_000_000;
|
||||
/// Шаг пополнения лимита.
|
||||
pub const LIMIT_STEP: u64 = 10_000;
|
||||
/// Стартовая цена одного шага лимита.
|
||||
pub const START_LAMPORTS_PER_LIMIT_STEP: u64 = 100_000;
|
||||
/// Стартовый бонус лимита.
|
||||
pub const START_BONUS_LIMIT: u64 = 100_000;
|
||||
/// Обязательная комиссия за каждое успешно завершённое обновление user PDA.
|
||||
pub const UPDATE_FEE_LAMPORTS: u64 = 20_000;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
/** Upgrade economy state v1 -> v2 or change the PDA-update fee.
|
||||
* Safe default: dry-run. Restricted to localnet/devnet. Never sends without --send.
|
||||
*
|
||||
* node scripts/registration-v2/update-economy-fee.mjs \
|
||||
* --rpc https://api.devnet.solana.com --keypair ~/.config/solana/id.json \
|
||||
* --fee-lamports 20000
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { Connection, PublicKey, Keypair, Transaction, TransactionInstruction, sendAndConfirmTransaction } = require('@solana/web3.js');
|
||||
const PROGRAM_ID = new PublicKey('SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6');
|
||||
const LOADER = new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111');
|
||||
const [ECONOMY] = PublicKey.findProgramAddressSync([Buffer.from('shine_users_economy_config')], PROGRAM_ID);
|
||||
function argsOf(argv) {
|
||||
const o = {};
|
||||
for (let i=0;i<argv.length;i++) {
|
||||
const s = argv[i];
|
||||
if (!s.startsWith('--')) throw Error('Unknown argument: ' + s);
|
||||
const k = s.slice(2);
|
||||
if (k === 'send') { if (o.send) throw Error('Repeated --send'); o.send = true; continue; }
|
||||
if (!argv[i+1] || argv[i+1].startsWith('--') || o[k] !== undefined) throw Error('Missing/repeated --' + k);
|
||||
o[k] = argv[++i];
|
||||
}
|
||||
return o;
|
||||
}
|
||||
async function main() {
|
||||
const a = argsOf(process.argv.slice(2));
|
||||
if (!a.rpc || !a.keypair || !/^(0|[1-9]\d*)$/.test(a['fee-lamports'] || ''))
|
||||
throw Error('Specify --rpc, --keypair and nonnegative decimal --fee-lamports');
|
||||
const fee = BigInt(a['fee-lamports']);
|
||||
if (fee > 0xffff_ffff_ffff_ffffn) throw Error('Fee does not fit in u64');
|
||||
const url = new URL(a.rpc);
|
||||
if (!(['http:', 'https:'].includes(url.protocol) &&
|
||||
(['127.0.0.1', 'localhost'].includes(url.hostname) || url.hostname.endsWith('.devnet.solana.com'))))
|
||||
throw Error('For safety this script accepts only localhost/devnet RPC');
|
||||
const path = a.keypair.replace(/^~\//, process.env.HOME + '/');
|
||||
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(path, 'utf8'))));
|
||||
const conn = new Connection(a.rpc, 'confirmed');
|
||||
const executable = await conn.getAccountInfo(PROGRAM_ID, 'confirmed');
|
||||
if (!executable?.executable || !executable.owner.equals(LOADER) || executable.data.length < 36 || executable.data.readUInt32LE(0) !== 2)
|
||||
throw Error('Program is not an upgradeable shine_users program');
|
||||
const programdata = new PublicKey(executable.data.subarray(4, 36));
|
||||
const pd = await conn.getAccountInfo(programdata, 'confirmed');
|
||||
if (!pd || !pd.owner.equals(LOADER) || pd.data.length < 45 || pd.data.readUInt32LE(0) !== 3 || pd.data[12] !== 1 ||
|
||||
!new PublicKey(pd.data.subarray(13, 45)).equals(wallet.publicKey))
|
||||
throw Error('Wallet is not current shine_users upgrade authority');
|
||||
const economy = await conn.getAccountInfo(ECONOMY, 'confirmed');
|
||||
if (!economy || !economy.owner.equals(PROGRAM_ID)) throw Error('Economy PDA is missing');
|
||||
const old = economy.data;
|
||||
const oldVersion = old[0];
|
||||
if (oldVersion !== 1 && oldVersion !== 2) throw Error('Unsupported economy version ' + oldVersion);
|
||||
const previousFee = oldVersion === 2 ? old.readBigUInt64LE(1).toString() : '20000 (legacy fallback)';
|
||||
const data = Buffer.alloc(9);
|
||||
data[0] = 2; // IX_UPDATE_USERS_ECONOMY_CONFIG
|
||||
data.writeBigUInt64LE(fee, 1);
|
||||
const ix = new TransactionInstruction({programId: PROGRAM_ID, keys: [
|
||||
{pubkey: wallet.publicKey, isSigner: true, isWritable: true},
|
||||
{pubkey: ECONOMY, isSigner: false, isWritable: true},
|
||||
{pubkey: PROGRAM_ID, isSigner: false, isWritable: false},
|
||||
{pubkey: programdata, isSigner: false, isWritable: false},
|
||||
], data});
|
||||
console.log(JSON.stringify({mode: a.send ? 'SEND' : 'DRY RUN', economyPda: ECONOMY.toBase58(),
|
||||
previousVersion: oldVersion, previousFeeLamports: previousFee, newFeeLamports: fee.toString()}, null, 2));
|
||||
if (!a.send) return;
|
||||
const sig = await sendAndConfirmTransaction(conn, new Transaction().add(ix), [wallet], {commitment:'confirmed'});
|
||||
const after = await conn.getAccountInfo(ECONOMY, 'confirmed');
|
||||
if (!after || after.data[0] !== 2 || after.data.readBigUInt64LE(1) !== fee)
|
||||
throw Error('On-chain economy fee update was not confirmed');
|
||||
console.log('Updated economy PDA. Solana signature: ' + sig);
|
||||
}
|
||||
main().catch(e => { console.error('Error:', e.message); process.exitCode = 1; });
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
parseShineUserPda,
|
||||
serializeUnsignedRecordFromState,
|
||||
canonicalPdaSigningBytes,
|
||||
} from '../../../shine-UI/js/services/shine-user-pda-service.js';
|
||||
|
||||
const bytes = (len, seed) => Uint8Array.from({ length: len }, (_, i) => (seed + i) & 0xff);
|
||||
@@ -30,7 +31,7 @@ full.set(bytes(64, 200), unsigned.length);
|
||||
const parsed = parseShineUserPda(full);
|
||||
|
||||
assert.equal(parsed.formatMajor, 1);
|
||||
assert.equal(parsed.formatMinor, 2);
|
||||
assert.equal(parsed.formatMinor, 3);
|
||||
assert.equal(parsed.isLegacy, false);
|
||||
assert.equal(parsed.recordNumber, 4);
|
||||
assert.equal(parsed.forks.length, 2);
|
||||
@@ -39,4 +40,12 @@ assert.equal(parsed.forks[1].paidLimitBytes, 200_000n);
|
||||
assert.equal(parsed.serverAddresses.length, 1);
|
||||
assert.deepEqual(parsed.accessServers, ['access1']);
|
||||
assert.equal(parsed.blockchain.blockchainName, 'codec_test-002');
|
||||
console.log(`PDA 1.2 codec smoke test OK (${full.length} bytes)`);
|
||||
const alternate = serializeUnsignedRecordFromState({
|
||||
...state,
|
||||
forks: state.forks.map((fork, i) => ({ ...fork, paidLimitBytes: i === 0 ? 0n : 4_000_000n })),
|
||||
});
|
||||
assert.notDeepEqual(unsigned, alternate, 'stored bytes must preserve actual quotas');
|
||||
assert.deepEqual(canonicalPdaSigningBytes(unsigned), canonicalPdaSigningBytes(alternate),
|
||||
'changing only a system-owned limit must not affect root signature hash');
|
||||
assert.equal(canonicalPdaSigningBytes(unsigned).length, unsigned.length - state.forks.length * 4);
|
||||
console.log(`PDA 1.3 codec/canonical hash smoke test OK (${full.length} bytes)`);
|
||||
|
||||
Reference in New Issue
Block a user