Merge pull request 'Rebuild kit atelier with native netherite, lore, trims and banners' (#333) from dev/kit-atelier-v3 into main
All checks were successful
DuneRealms Kit Delivery CI / kits (push) Successful in 1m10s
DuneRealms Web CI / web (push) Successful in 3m26s

This commit is contained in:
Dev 2026-11-16 02:26:59 +00:00
commit 0f07319d5b
143 changed files with 3326 additions and 33 deletions

View file

@ -0,0 +1,41 @@
name: DuneRealms Kit Delivery CI
on:
push:
branches: [main, dev/kit-atelier-v3]
paths:
- 'DuneKits/**'
- 'network/server-control/kit*'
- 'network/server-control/player_kits.py'
- '.forgejo/workflows/kit-delivery.yml'
workflow_dispatch:
jobs:
kits:
runs-on: dune-ci
steps:
- name: Checkout
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git init .
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA"
git checkout --detach FETCH_HEAD
- name: Install Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Install Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '9.2.1'
- name: Verify bridge and build native kit items
run: |
python3 -m unittest discover -s network/server-control -p 'test_kit_equipment.py' -v
gradle --no-daemon -p DuneKits test jar
- name: Upload verified kit plugin
uses: actions/upload-artifact@v3
with:
name: DuneKits
path: DuneKits/build/libs/DuneKits-3.0.0.jar
if-no-files-found: error

2
DuneKits/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/.gradle/
/build/

14
DuneKits/build.gradle.kts Normal file
View file

@ -0,0 +1,14 @@
plugins { java }
group = "com.example"
version = "3.0.0"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") }
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<JavaCompile> { options.encoding = "UTF-8"; options.release.set(21) }
tasks.processResources { from("../network/server-control/kit-equipment-contract.json") }
tasks.test { useJUnitPlatform() }
tasks.jar { archiveFileName.set("DuneKits-3.0.0.jar") }

View file

@ -0,0 +1 @@
rootProject.name = "DuneKits"

View file

@ -0,0 +1,214 @@
package com.example.dunekits;
import com.google.gson.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.sql.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
/** Receipt delivery commits with DuneCore's authoritative inventory checkpoint. */
public final class DuneKits extends JavaPlugin implements CommandExecutor, org.bukkit.event.Listener {
private JavaPlugin core;
private Method transaction, factionOf, baseFactory;
private final Set<UUID> inflight = new HashSet<>();
private final Map<UUID, Long> notices = new HashMap<>();
@Override public void onEnable() {
Objects.requireNonNull(getCommand("kitclaim")).setExecutor(this);
Objects.requireNonNull(getCommand("dunekit")).setExecutor(this);
Plugin dependency = getServer().getPluginManager().getPlugin("DuneCore");
if (!(dependency instanceof JavaPlugin candidate) || !dependency.isEnabled()) {
getLogger().info("Verification mode: DuneCore is unavailable; no deliveries will run.");
return;
}
try {
core = candidate;
transaction = core.getClass().getMethod("transactNetworkInventory", Player.class, Consumer.class);
factionOf = core.getClass().getMethod("factionOf", Player.class);
baseFactory = core.getClass().getMethod("createFactionKit", String.class);
} catch (ReflectiveOperationException ex) {
core = null;
getLogger().severe("DuneCore lacks atomic inventory delivery support; claims remain queued.");
return;
}
getServer().getPluginManager().registerEvents(this, this);
getServer().getScheduler().runTaskTimer(this, () -> {
for (Player player : getServer().getOnlinePlayers()) { upgradeFactionIssues(player); request(player); }
}, 100L, 200L);
getServer().getScheduler().runTaskAsynchronously(this, () -> {
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(KitDeliverySQL.pending(mysql(connection)))) {
identity(query, 1, new UUID(0, 0), mysql(connection));
try (ResultSet ignored = query.executeQuery()) {
getLogger().info("Paid kit delivery ready (" + connection.getMetaData().getDatabaseProductName() + " inventory).");
}
} catch (Exception ex) { getLogger().severe("Paid kit delivery database unavailable; claims will remain queued: " + ex.getClass().getSimpleName()); }
});
}
@Override public void onDisable() { inflight.clear(); notices.clear(); }
private static boolean mysql(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName().equalsIgnoreCase("MySQL"); }
private static void identity(PreparedStatement statement, int index, UUID value, boolean mysql) throws SQLException {
if (mysql) statement.setString(index, value.toString()); else statement.setObject(index, value);
}
private Connection connect() throws Exception {
String url = core.getConfig().getString("database.jdbc-url", "");
if (!url.startsWith("jdbc:postgresql://") && !url.startsWith("jdbc:mysql://")) throw new SQLException("Private shared inventory database required");
Properties settings = new Properties();
settings.setProperty("user", core.getConfig().getString("database.username", ""));
settings.setProperty("password", core.getConfig().getString("database.password", ""));
settings.setProperty("connectTimeout", "3"); settings.setProperty("socketTimeout", "5");
settings.setProperty("ApplicationName", "DuneKits");
// The running DuneCore already contains its matching PostgreSQL driver.
Driver driver = (Driver) Class.forName(url.startsWith("jdbc:mysql://") ? "com.mysql.cj.jdbc.Driver" : "org.postgresql.Driver", true, core.getClass().getClassLoader())
.getDeclaredConstructor().newInstance();
Connection connection = driver.connect(url, settings);
if (connection == null) throw new SQLException("Private inventory connection unavailable");
return connection;
}
private void request(Player player) {
if (core == null || !core.isEnabled() || !inflight.add(player.getUniqueId())) return;
UUID buyer = player.getUniqueId();
getServer().getScheduler().runTaskAsynchronously(this, () -> {
List<UUID> pending = new ArrayList<>();
try (Connection connection = connect(); PreparedStatement q = connection.prepareStatement(
KitDeliverySQL.pending(mysql(connection)))) {
identity(q, 1, buyer, mysql(connection));
try (ResultSet rows = q.executeQuery()) { while (rows.next()) pending.add(UUID.fromString(rows.getString(1))); }
} catch (Exception ex) {
// Never log credentials, snapshot contents or private item codes.
getLogger().fine("Pending kit read unavailable: " + ex.getClass().getSimpleName());
}
if (!isEnabled()) return;
getServer().getScheduler().runTask(this, () -> {
try {
Player current = getServer().getPlayer(buyer);
if (current != null && current.isOnline()) for (UUID id : pending) if (!deliver(current, id)) break;
} finally { inflight.remove(buyer); }
});
});
}
// Older DuneCore versions accept only leather in their existing wing-upgrade command.
// Reuse that exact executor and its price/consent checks, restoring the suit on refusal.
@org.bukkit.event.EventHandler(priority=org.bukkit.event.EventPriority.HIGHEST, ignoreCancelled=true)
public void onWingCommand(org.bukkit.event.player.PlayerCommandPreprocessEvent event) {
String[] words = event.getMessage().trim().split("\\s+");
if (core == null || words.length != 2 || !words[1].equalsIgnoreCase("elytra")
|| !Set.of("/dune", "/dunecore:dune").contains(words[0].toLowerCase(Locale.ROOT))) return;
PluginCommand command = getServer().getPluginCommand("dune");
Player player = event.getPlayer(); ItemStack current = player.getInventory().getChestplate();
if (command == null || command.getPlugin() != core || current == null || current.getType() != Material.NETHERITE_CHESTPLATE
|| !"stillsuit".equals(current.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms", "item"), org.bukkit.persistence.PersistentDataType.STRING))) return;
event.setCancelled(true);
ItemStack original = current.clone(), compatible = current.clone(); compatible.setType(Material.LEATHER_CHESTPLATE);
player.getInventory().setChestplate(compatible);
try { command.execute(player, "dune", new String[]{"elytra"}); }
finally { ItemStack after = player.getInventory().getChestplate(); if (after != null && after.isSimilar(compatible)) player.getInventory().setChestplate(original); }
}
private void upgradeFactionIssues(Player player) {
if (Arrays.stream(player.getInventory().getContents()).noneMatch(FactionSuitUpgrade::candidate)) return;
try {
String faction = (String) factionOf.invoke(core, player);
transaction.invoke(core, player, (Consumer<Connection>) connection -> {
ItemStack[] inventory = player.getInventory().getContents();
for (int i = 0; i < inventory.length; i++) if (FactionSuitUpgrade.candidate(inventory[i]))
player.getInventory().setItem(i, FactionSuitUpgrade.upgrade(inventory[i], faction));
});
} catch (Exception ex) { getLogger().fine("Faction suit conversion retained for retry: " + ex.getClass().getSimpleName()); }
}
private boolean deliver(Player player, UUID id) {
final boolean[] delivered = {false};
try {
Consumer<Connection> operation = connection -> {
try (PreparedStatement q = connection.prepareStatement(
KitDeliverySQL.lock(mysql(connection)))) {
identity(q, 1, id, mysql(connection)); identity(q, 2, player.getUniqueId(), mysql(connection));
String raw, hash;
try (ResultSet rows = q.executeQuery()) {
if (!rows.next()) return;
raw = rows.getString(1); hash = rows.getString(2);
}
if (raw == null || raw.getBytes(StandardCharsets.UTF_8).length > 65536 || !digest(raw).equals(hash)) throw KitSpec.invalid();
JsonObject snapshot = JsonParser.parseString(raw).getAsJsonObject();
Map<String, ItemStack> base = factionBase(player);
List<ItemStack> items = KitItemFactory.create(snapshot, base);
if (!player.getInventory().addItem(items.toArray(ItemStack[]::new)).isEmpty())
throw new NoRoom();
try (PreparedStatement update = connection.prepareStatement(
KitDeliverySQL.acknowledge(mysql(connection)))) {
identity(update, 1, id, mysql(connection)); identity(update, 2, player.getUniqueId(), mysql(connection));
if (update.executeUpdate() != 1) throw new SQLException("Delivery changed");
}
delivered[0] = true;
} catch (Exception ex) { throw new DeliveryFailure(ex); }
};
transaction.invoke(core, player, operation);
if (delivered[0]) player.sendMessage(ChatColor.GOLD + "Your redeemed DuneRealms kit has arrived.");
return true;
} catch (Exception ex) {
Throwable cause = ex instanceof InvocationTargetException invocation ? invocation.getCause() : ex;
while (cause.getCause() != null && cause instanceof DeliveryFailure) cause = cause.getCause();
long now = System.currentTimeMillis();
if (now - notices.getOrDefault(player.getUniqueId(), 0L) > 60000) {
player.sendMessage(ChatColor.YELLOW + (cause instanceof NoRoom
? "Make room for the complete kit. Your claim is still queued."
: "Kit delivery is pending. Your claim has been retained."));
notices.put(player.getUniqueId(), now);
}
getLogger().log(Level.FINE, "Kit delivery retained: " + cause.getClass().getSimpleName());
return false;
}
}
private Map<String, ItemStack> factionBase(Player player) throws ReflectiveOperationException {
String faction = (String) factionOf.invoke(core, player);
if (faction == null || faction.isBlank()) throw KitSpec.invalid();
Object result = baseFactory.invoke(core, faction);
if (!(result instanceof List<?> items)) throw KitSpec.invalid();
Map<String, ItemStack> base = new HashMap<>();
for (Object value : items) if (value instanceof ItemStack item)
for (String slot : KitSpec.SLOTS) if (item.getType().name().endsWith("_" + slot.toUpperCase(Locale.ROOT))) base.put(slot, item);
if (base.size() != 4) throw KitSpec.invalid();
return base;
}
static String digest(String raw) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8)));
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("kitclaim")) {
if (!(sender instanceof Player player)) { sender.sendMessage("Use this command in Minecraft."); return true; }
if (core == null) player.sendMessage("Kit delivery is unavailable. Your claim is retained.");
else { request(player); player.sendMessage("Checking your redeemed kits. Keep room for the complete set."); }
return true;
}
if (!sender.hasPermission("dunekits.verify")) return true;
if (args.length != 1 || !args[0].equals("verify")) return false;
try {
int checked = KitVerification.verify();
sender.sendMessage("DUNEKITS_VERIFY_OK: " + checked + " item metadata checks; no items issued.");
} catch (Exception ex) {
sender.sendMessage("DUNEKITS_VERIFY_FAILED: " + ex.getClass().getSimpleName());
getLogger().log(Level.WARNING, "Kit metadata verification failed", ex);
}
return true;
}
private static final class NoRoom extends RuntimeException {}
private static final class DeliveryFailure extends RuntimeException { DeliveryFailure(Throwable cause) { super(cause); } }
}

View file

@ -0,0 +1,52 @@
package com.example.dunekits;
import java.util.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ArmorMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.trim.*;
import org.bukkit.persistence.PersistentDataType;
/** Upgrade only native faction issues, never a purchased historical contract. */
final class FactionSuitUpgrade {
static final NamespacedKey CONTRACT = new NamespacedKey("dunekits", "contract_version");
private static final NamespacedKey ITEM = new NamespacedKey("dunerealms", "item");
private static final NamespacedKey FACTION = new NamespacedKey("dunerealms", "armor_faction");
static boolean candidate(ItemStack item) {
if (item == null || !item.getType().name().startsWith("LEATHER_") || !KitSpec.SLOTS.contains(item.getType().name().substring(8).toLowerCase(Locale.ROOT))) return false;
ItemMeta meta = item.getItemMeta();
return meta instanceof ArmorMeta && "stillsuit".equals(meta.getPersistentDataContainer().get(ITEM, PersistentDataType.STRING))
&& !meta.getPersistentDataContainer().has(CONTRACT, PersistentDataType.INTEGER);
}
static ItemStack upgrade(ItemStack original, String fallbackFaction) {
if (!candidate(original)) return original;
ItemStack item = original.clone();
item.setType(Material.valueOf("NETHERITE_" + original.getType().name().substring(8)));
ArmorMeta meta = (ArmorMeta) item.getItemMeta();
String faction = meta.getPersistentDataContainer().get(FACTION, PersistentDataType.STRING);
faction = (faction == null ? Objects.requireNonNullElse(fallbackFaction, "fremen") : faction).toLowerCase(Locale.ROOT);
TrimPattern pattern; TrimMaterial material; String story; NamedTextColor color;
switch (faction) {
case "harkonnen" -> { pattern = TrimPattern.RIB; material = TrimMaterial.REDSTONE; story = "Strength leaves its mark."; color = NamedTextColor.RED; }
case "atreides" -> { pattern = TrimPattern.COAST; material = TrimMaterial.EMERALD; story = "Honor above ambition."; color = NamedTextColor.GREEN; }
case "corrino" -> { pattern = TrimPattern.SPIRE; material = TrimMaterial.GOLD; story = "By imperial decree. The Golden Lion endures."; color = NamedTextColor.GOLD; }
case "ordos" -> { pattern = TrimPattern.SENTRY; material = TrimMaterial.AMETHYST; story = "Every secret has its price."; color = NamedTextColor.LIGHT_PURPLE; }
case "guild", "spacing_guild" -> { pattern = TrimPattern.EYE; material = TrimMaterial.QUARTZ; story = "The spice must flow."; color = NamedTextColor.AQUA; }
default -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; story = "Your water belongs to the tribe."; color = NamedTextColor.BLUE; }
}
if (!meta.hasTrim()) meta.setTrim(new ArmorTrim(material, pattern));
if (!meta.hasLore()) meta.lore(List.of(
Component.text(story, color).decoration(TextDecoration.ITALIC, false),
Component.empty().decoration(TextDecoration.ITALIC, false),
Component.text("Faction issue · Netherite stillsuit", NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, false)));
meta.getPersistentDataContainer().set(CONTRACT, PersistentDataType.INTEGER, 3);
item.setItemMeta(meta);
return item;
}
}

View file

@ -0,0 +1,18 @@
package com.example.dunekits;
/** MySQL receipts commit directly with the active network inventory checkpoint. */
final class KitDeliverySQL {
static final String PAID = "delivered_at IS NULL AND redeem_requested_at IS NOT NULL AND redeem_requested_at>0 AND quantity=1 AND gross_cents>0 AND completed_at>0";
static String pending(boolean mysql) {
return mysql ? "SELECT id FROM dune_kit_sales WHERE buyer_uuid=? AND " + PAID + " ORDER BY redeem_requested_at,id LIMIT 5"
: "SELECT id FROM dune_kit_deliveries WHERE buyer_uuid=? AND delivered_at IS NULL ORDER BY created_at,id LIMIT 5";
}
static String lock(boolean mysql) {
return mysql ? "SELECT snapshot_json,SHA2(snapshot_json,256) FROM dune_kit_sales WHERE id=? AND buyer_uuid=? AND " + PAID + " FOR UPDATE"
: "SELECT snapshot_json,snapshot_hash FROM dune_kit_deliveries WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL FOR UPDATE";
}
static String acknowledge(boolean mysql) {
return mysql ? "UPDATE dune_kit_sales SET delivered_at=CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) WHERE id=? AND buyer_uuid=? AND " + PAID
: "UPDATE dune_kit_deliveries SET delivered_at=(EXTRACT(EPOCH FROM clock_timestamp())*1000)::bigint WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL";
}
}

View file

@ -0,0 +1,105 @@
package com.example.dunekits;
import com.google.gson.JsonObject;
import java.util.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.inventory.meta.trim.ArmorTrim;
import org.bukkit.inventory.meta.trim.TrimMaterial;
import org.bukkit.inventory.meta.trim.TrimPattern;
final class KitItemFactory {
private KitItemFactory() {}
/** Base items come from DuneCore's buyer-faction factory, preserving its tags and attributes. */
static List<ItemStack> create(JsonObject snapshot, Map<String, ItemStack> base) {
KitSpec kit = new KitSpec(snapshot);
List<ItemStack> items = new ArrayList<>();
for (String slot : KitSpec.SLOTS) {
KitSpec.Piece piece = kit.armor.get(slot);
Material material = Material.valueOf((kit.modern ? "NETHERITE_" : "LEATHER_") + slot.toUpperCase(Locale.ROOT));
ItemStack item = base.containsKey(slot) ? base.get(slot).clone() : new ItemStack(material);
item.setType(material);
item.setAmount(1);
ItemMeta meta = item.getItemMeta();
if (!(meta instanceof ArmorMeta armor)) throw KitSpec.invalid();
if (kit.modern) {
TrimPattern pattern = Registry.TRIM_PATTERN.get(NamespacedKey.minecraft(piece.trim().pattern()));
TrimMaterial trimMaterial = Registry.TRIM_MATERIAL.get(NamespacedKey.minecraft(piece.trim().material()));
if (pattern == null || trimMaterial == null) throw KitSpec.invalid();
armor.setTrim(new ArmorTrim(trimMaterial, pattern));
} else if (meta instanceof LeatherArmorMeta leather) {
leather.setColor(Color.fromRGB(Integer.parseInt(kit.legacyColor.substring(1), 16)));
}
meta.getPersistentDataContainer().set(FactionSuitUpgrade.CONTRACT, org.bukkit.persistence.PersistentDataType.INTEGER, kit.modern ? 3 : 1);
meta.displayName(name(piece.name().isBlank() ? kit.name + " " + title(slot) : piece.name()));
meta.lore(piece.lore().stream().map(KitSpec.Lore::component).toList());
if (!kit.kind.equals("faction_sale")) {
// Rarity remains authoritative. Designers cannot supply enchantment or attribute data.
for (Enchantment enchantment : Set.copyOf(meta.getEnchants().keySet())) meta.removeEnchant(enchantment);
enchantments(meta, slot, kit.quality);
}
for (KitSpec.Bonus bonus : kit.bonuses) if (bonus.piece().equals(slot)) {
Enchantment enchantment = Registry.ENCHANTMENT.get(NamespacedKey.minecraft(bonus.enchantment()));
if (enchantment == null) throw KitSpec.invalid();
meta.addEnchant(enchantment, meta.getEnchantLevel(enchantment) + bonus.levels(), true);
}
item.setItemMeta(meta);
items.add(item);
}
if (kit.banner.enabled()) {
ItemStack item = new ItemStack(Material.valueOf(kit.banner.base().toUpperCase(Locale.ROOT) + "_BANNER"));
BannerMeta meta = (BannerMeta) item.getItemMeta();
List<Pattern> layers = new ArrayList<>();
for (KitSpec.Layer layer : kit.banner.patterns()) {
PatternType pattern = Registry.BANNER_PATTERN.get(NamespacedKey.minecraft(layer.pattern()));
if (pattern == null) throw KitSpec.invalid();
layers.add(new Pattern(DyeColor.valueOf(layer.color().toUpperCase(Locale.ROOT)), pattern));
}
meta.setPatterns(layers);
meta.displayName(name(kit.banner.name().isBlank() ? kit.name + " Standard" : kit.banner.name()));
meta.lore(kit.banner.lore().stream().map(KitSpec.Lore::component).toList());
item.setItemMeta(meta);
items.add(item);
}
return List.copyOf(items);
}
private static Component name(String text) {
return Component.text(text, NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false);
}
private static String title(String text) {
return Character.toUpperCase(text.charAt(0)) + text.substring(1);
}
private static void enchantments(ItemMeta meta, String slot, String quality) {
int tier = List.of("common", "uncommon", "rare", "very_rare", "legendary").indexOf(quality);
if (tier == 0) return;
add(meta, Enchantment.PROTECTION, tier);
add(meta, Enchantment.UNBREAKING, Math.min(tier, 3));
if (tier >= 3) add(meta, Enchantment.MENDING, 1);
if (tier == 4) add(meta, Enchantment.THORNS, 3);
if (slot.equals("helmet") && tier >= 2) {
add(meta, Enchantment.RESPIRATION, tier - 1);
add(meta, Enchantment.AQUA_AFFINITY, 1);
}
if (slot.equals("leggings") && tier >= 3) add(meta, Enchantment.SWIFT_SNEAK, tier - 1);
if (slot.equals("boots")) {
add(meta, Enchantment.FEATHER_FALLING, tier);
if (tier >= 2) add(meta, Enchantment.DEPTH_STRIDER, tier - 1);
if (tier == 4) add(meta, Enchantment.SOUL_SPEED, 3);
}
}
private static void add(ItemMeta meta, Enchantment enchantment, int level) {
meta.addEnchant(enchantment, level, true);
}
}

View file

@ -0,0 +1,149 @@
package com.example.dunekits;
import com.google.gson.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
/** Literal metadata only. No command, MiniMessage or arbitrary component parser. */
final class KitSpec {
static final List<String> SLOTS = List.of("helmet", "chestplate", "leggings", "boots");
static final Set<String> QUALITIES = Set.of("common", "uncommon", "rare", "very_rare", "legendary");
static final Set<String> KINDS = Set.of("personal_sale", "official_sale", "faction_sale", "server_sale");
private static final JsonObject CONTRACT;
static {
try (InputStream input = KitSpec.class.getResourceAsStream("/kit-equipment-contract.json")) {
if (input == null) throw new IOException("Missing kit contract");
CONTRACT = JsonParser.parseReader(new InputStreamReader(input, StandardCharsets.UTF_8)).getAsJsonObject();
} catch (IOException ex) { throw new ExceptionInInitializerError(ex); }
}
record Lore(String text, String color, boolean bold, boolean italic) {
Component component() {
return Component.text(text, Objects.requireNonNull(TextColor.fromHexString(color)))
.decoration(TextDecoration.BOLD, bold).decoration(TextDecoration.ITALIC, italic);
}
}
record Trim(String pattern, String material) {}
record Piece(String name, List<Lore> lore, Trim trim) {}
record Layer(String pattern, String color) {}
record Bonus(String piece, String enchantment, int levels) {}
record Banner(boolean enabled, String name, String base, List<Layer> patterns, List<Lore> lore) {}
final String name, quality, kind, legacyColor;
final boolean modern;
final Map<String, Piece> armor;
final Banner banner;
final List<Bonus> bonuses;
KitSpec(JsonObject snapshot) {
name = text(snapshot.get("name"), 64);
if (name.isBlank()) throw invalid();
quality = text(snapshot.get("quality"), 16);
kind = snapshot.has("commerceKind") ? text(snapshot.get("commerceKind"), 16) : "personal_sale";
if (!QUALITIES.contains(quality) || !KINDS.contains(kind)) throw invalid();
modern = snapshot.has("equipment");
legacyColor = snapshot.has("color") ? text(snapshot.get("color"), 7) : "#385B49";
if (!legacyColor.matches("#[A-Fa-f0-9]{6}")) throw invalid();
Map<String, Piece> pieces = new LinkedHashMap<>();
if (modern) {
JsonObject equipment = object(snapshot.get("equipment"), "version", "armor", "banner");
if (integer(equipment.get("version")) != 3) throw invalid();
JsonObject items = object(equipment.get("armor"), SLOTS.toArray(String[]::new));
for (String slot : SLOTS) {
JsonObject item = object(items.get(slot), "material", "name", "lore", "trim");
if (!text(item.get("material"), 16).equals("netherite")) throw invalid();
JsonObject trim = object(item.get("trim"), "pattern", "material");
pieces.put(slot, new Piece(text(item.get("name"), 64), lore(item.get("lore")),
new Trim(choice(trim.get("pattern"), "trimPatterns"), choice(trim.get("material"), "trimMaterials"))));
}
JsonObject standard = object(equipment.get("banner"), "enabled", "name", "base", "patterns", "lore");
List<Layer> layers = new ArrayList<>();
for (JsonElement value : array(standard.get("patterns"), 6)) {
JsonObject layer = object(value, "pattern", "color");
layers.add(new Layer(choice(layer.get("pattern"), "bannerPatterns"), choice(layer.get("color"), "bannerColors")));
}
banner = new Banner(bool(standard.get("enabled")), text(standard.get("name"), 64),
choice(standard.get("base"), "bannerColors"), List.copyOf(layers), lore(standard.get("lore")));
} else {
// Paid historical snapshots keep their original leather material and plain lore.
List<Lore> lines = new ArrayList<>();
if (snapshot.has("lore")) for (JsonElement line : array(snapshot.get("lore"), 6))
lines.add(new Lore(text(line, 120), "#AAAAAA", false, false));
JsonObject names = snapshot.has("itemNames") && snapshot.get("itemNames").isJsonObject()
? snapshot.getAsJsonObject("itemNames") : new JsonObject();
for (String slot : SLOTS) pieces.put(slot, new Piece(names.has(slot) ? text(names.get(slot), 64) : "", List.copyOf(lines), null));
banner = new Banner(false, "", "black", List.of(), List.of());
}
armor = Collections.unmodifiableMap(pieces);
List<Bonus> upgrade = new ArrayList<>();
if (snapshot.has("upgrade")) {
if (!quality.equals("legendary") || !kind.equals("personal_sale")) throw invalid();
JsonObject value = object(snapshot.get("upgrade"), "policy", "points", "bonuses");
if (!text(value.get("policy"), 40).equals("legendary-player-v1")) throw invalid();
int points = integer(value.get("points")), total = 0;
Set<String> selected = new HashSet<>();
for (JsonElement entry : array(value.get("bonuses"), 3)) {
JsonObject bonus = object(entry, "piece", "enchantment", "levels");
String slot = text(bonus.get("piece"), 16), enchantment = text(bonus.get("enchantment"), 32);
Set<String> allowed = new HashSet<>(Set.of("protection", "unbreaking", "mending", "thorns"));
if (slot.equals("helmet")) allowed.addAll(Set.of("respiration", "aqua_affinity"));
if (slot.equals("leggings")) allowed.add("swift_sneak");
if (slot.equals("boots")) allowed.addAll(Set.of("feather_falling", "depth_strider", "soul_speed"));
int levels = integer(bonus.get("levels"));
if (!SLOTS.contains(slot) || !allowed.contains(enchantment) || levels < 1 || levels > 3 || !selected.add(slot + ":" + enchantment)) throw invalid();
total += levels; upgrade.add(new Bonus(slot, enchantment, levels));
}
if (points < 1 || points > 3 || total != points || upgrade.isEmpty()) throw invalid();
}
bonuses = List.copyOf(upgrade);
}
static JsonObject object(JsonElement value, String... keys) {
if (value == null || !value.isJsonObject()) throw invalid();
JsonObject object = value.getAsJsonObject();
if (!object.keySet().equals(Set.of(keys))) throw invalid();
return object;
}
static String text(JsonElement value, int max) {
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) throw invalid();
String text = value.getAsString();
if (text.length() > max) throw invalid();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch < 32 || ch == 127 || ch == '<' || ch == '>' || ch == '§') throw invalid();
if (Character.isHighSurrogate(ch)) {
if (++i >= text.length() || !Character.isLowSurrogate(text.charAt(i))) throw invalid();
} else if (Character.isLowSurrogate(ch)) throw invalid();
}
return text;
}
static int integer(JsonElement value) {
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber()) throw invalid();
try { return value.getAsBigDecimal().intValueExact(); } catch (ArithmeticException ex) { throw invalid(); }
}
static boolean bool(JsonElement value) {
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isBoolean()) throw invalid();
return value.getAsBoolean();
}
static JsonArray array(JsonElement value, int max) {
if (value == null || !value.isJsonArray() || value.getAsJsonArray().size() > max) throw invalid();
return value.getAsJsonArray();
}
static String choice(JsonElement value, String set) {
String result = text(value, 40);
if (!CONTRACT.getAsJsonArray(set).contains(new JsonPrimitive(result))) throw invalid();
return result;
}
static List<Lore> lore(JsonElement value) {
List<Lore> result = new ArrayList<>();
for (JsonElement entry : array(value, 6)) {
JsonObject line = object(entry, "text", "color", "bold", "italic");
String color = text(line.get("color"), 7);
if (!color.matches("#[A-Fa-f0-9]{6}")) throw invalid();
result.add(new Lore(text(line.get("text"), 120), color.toUpperCase(Locale.ROOT), bool(line.get("bold")), bool(line.get("italic"))));
}
return List.copyOf(result);
}
static IllegalArgumentException invalid() { return new IllegalArgumentException("Invalid bounded kit item metadata"); }
}

View file

@ -0,0 +1,98 @@
package com.example.dunekits;
import com.google.gson.*;
import java.io.*;
import java.util.*;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
/** Runs on a real Paper server, without adding anything to a player inventory. */
final class KitVerification {
static JsonObject example(String quality, String pattern, String material) {
JsonObject snapshot = new JsonObject();
snapshot.addProperty("name", "Imperial Sentinel"); snapshot.addProperty("quality", quality);
snapshot.addProperty("commerceKind", "personal_sale"); snapshot.addProperty("color", "#BCA05B");
JsonObject equipment = new JsonObject(), armor = new JsonObject(); equipment.addProperty("version", 3);
for (String slot : KitSpec.SLOTS) {
JsonObject piece = new JsonObject(), trim = new JsonObject();
piece.addProperty("material", "netherite"); piece.addProperty("name", "Sentinel " + slot);
JsonArray lore = new JsonArray();
for (String text : List.of("By imperial decree.", "", "Duty endures beyond the dunes.")) {
JsonObject line = new JsonObject(); line.addProperty("text", text); line.addProperty("color", "#BCA05B");
line.addProperty("bold", false); line.addProperty("italic", false); lore.add(line);
}
piece.add("lore", lore); trim.addProperty("pattern", pattern); trim.addProperty("material", material);
piece.add("trim", trim); armor.add(slot, piece);
}
JsonObject banner = new JsonObject(); banner.addProperty("enabled", true);
banner.addProperty("name", "Imperial Standard"); banner.addProperty("base", "purple");
JsonArray layers = new JsonArray();
for (String[] values : List.of(new String[]{"border", "yellow"}, new String[]{"rhombus", "red"})) {
JsonObject layer = new JsonObject(); layer.addProperty("pattern", values[0]); layer.addProperty("color", values[1]); layers.add(layer);
}
banner.add("patterns", layers); banner.add("lore", new JsonArray());
equipment.add("armor", armor); equipment.add("banner", banner); snapshot.add("equipment", equipment);
return snapshot;
}
static int verify() throws Exception {
int checked = 0;
for (String quality : KitSpec.QUALITIES) {
List<ItemStack> items = KitItemFactory.create(example(quality, "dune", "gold"), Map.of());
if (items.size() != 5) throw new IllegalStateException("Missing armour or banner");
for (int i = 0; i < 4; i++) {
ItemStack item = items.get(i); ItemMeta meta = item.getItemMeta();
if (!item.getType().name().startsWith("NETHERITE_") || !(meta instanceof ArmorMeta armor) || !armor.hasTrim()) throw new IllegalStateException("Missing netherite trim");
if (meta.lore() == null || meta.lore().size() != 3 || !PlainTextComponentSerializer.plainText().serialize(meta.lore().get(1)).isEmpty()
|| meta.lore().get(0).decoration(TextDecoration.ITALIC) != TextDecoration.State.FALSE) throw new IllegalStateException("Lore formatting lost");
if (!item.isSimilar(roundTrip(item))) throw new IllegalStateException("Inventory serialization lost armour metadata");
checked++;
}
BannerMeta banner = (BannerMeta) items.get(4).getItemMeta();
if (banner.numberOfPatterns() != 2 || banner.getPattern(0).getColor() != DyeColor.YELLOW || banner.getPattern(1).getColor() != DyeColor.RED)
throw new IllegalStateException("Banner layer order lost");
if (!items.get(4).isSimilar(roundTrip(items.get(4)))) throw new IllegalStateException("Inventory serialization lost banner metadata");
checked++;
}
try (InputStream input = KitVerification.class.getResourceAsStream("/kit-equipment-contract.json")) {
JsonObject contract = JsonParser.parseReader(new InputStreamReader(Objects.requireNonNull(input), java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();
for (JsonElement pattern : contract.getAsJsonArray("trimPatterns")) for (JsonElement material : contract.getAsJsonArray("trimMaterials")) {
KitItemFactory.create(example("common", pattern.getAsString(), material.getAsString()), Map.of()); checked++;
}
for (JsonElement pattern : contract.getAsJsonArray("bannerPatterns")) {
JsonObject snapshot = example("common", "dune", "gold");
snapshot.getAsJsonObject("equipment").getAsJsonObject("banner").getAsJsonArray("patterns").get(0).getAsJsonObject().addProperty("pattern", pattern.getAsString());
KitItemFactory.create(snapshot, Map.of()); checked++;
}
}
JsonObject upgraded = example("legendary", "silence", "gold");
upgraded.add("upgrade", JsonParser.parseString("{\"policy\":\"legendary-player-v1\",\"points\":3,\"bonuses\":[{\"piece\":\"helmet\",\"enchantment\":\"protection\",\"levels\":2},{\"piece\":\"boots\",\"enchantment\":\"soul_speed\",\"levels\":1}]}"));
List<ItemStack> upgradedItems = KitItemFactory.create(upgraded, Map.of());
if (upgradedItems.get(0).getEnchantmentLevel(org.bukkit.enchantments.Enchantment.PROTECTION) != 6 || upgradedItems.get(3).getEnchantmentLevel(org.bukkit.enchantments.Enchantment.SOUL_SPEED) != 4)
throw new IllegalStateException("Saved Legendary upgrade was not applied exactly");
checked++;
ItemStack nativeSuit = new ItemStack(Material.LEATHER_CHESTPLATE);
ItemMeta nativeMeta = nativeSuit.getItemMeta();
nativeMeta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "item"), org.bukkit.persistence.PersistentDataType.STRING, "stillsuit");
nativeMeta.addEnchant(org.bukkit.enchantments.Enchantment.MENDING, 1, true); nativeSuit.setItemMeta(nativeMeta);
ItemStack converted = FactionSuitUpgrade.upgrade(nativeSuit, "corrino");
if (converted.getType() != Material.NETHERITE_CHESTPLATE || converted.getEnchantmentLevel(org.bukkit.enchantments.Enchantment.MENDING) != 1 || nativeSuit.getType() != Material.LEATHER_CHESTPLATE)
throw new IllegalStateException("Faction conversion changed source or enchantments");
if (!converted.isSimilar(roundTrip(converted))) throw new IllegalStateException("Faction conversion metadata was not durable");
nativeMeta.getPersistentDataContainer().set(FactionSuitUpgrade.CONTRACT, org.bukkit.persistence.PersistentDataType.INTEGER, 1); nativeSuit.setItemMeta(nativeMeta);
if (FactionSuitUpgrade.candidate(nativeSuit)) throw new IllegalStateException("Historical purchased armour must remain unchanged");
checked += 3;
return checked;
}
private static ItemStack roundTrip(ItemStack item) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (BukkitObjectOutputStream output = new BukkitObjectOutputStream(bytes)) { output.writeObject(item); }
try (BukkitObjectInputStream input = new BukkitObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { return (ItemStack) input.readObject(); }
}
}

View file

@ -0,0 +1,17 @@
name: DuneKits
version: 3.0.0
main: com.example.dunekits.DuneKits
api-version: '1.21.4'
softdepend: [DuneCore]
description: Versioned kit item metadata and receipt-bound delivery
commands:
kitclaim:
description: Check for redeemed kits awaiting delivery
usage: /kitclaim
dunekit:
description: Verify the kit item format without issuing items
usage: /dunekit verify
permission: dunekits.verify
permissions:
dunekits.verify:
default: op

View file

@ -0,0 +1,22 @@
package com.example.dunekits;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class KitDeliverySQLTest {
@Test void mysqlRequiresPaidRequestedBuyerBoundReceiptsThroughoutTheTransaction() {
for (String sql : new String[]{KitDeliverySQL.pending(true), KitDeliverySQL.lock(true), KitDeliverySQL.acknowledge(true)}) {
assertTrue(sql.contains("dune_kit_sales"));assertTrue(sql.contains("buyer_uuid=?"));
assertTrue(sql.contains("quantity=1"));assertTrue(sql.contains("gross_cents>0"));
assertTrue(sql.contains("completed_at>0"));assertTrue(sql.contains("redeem_requested_at>0"));
assertTrue(sql.contains("delivered_at IS NULL"));
}
assertTrue(KitDeliverySQL.lock(true).endsWith("FOR UPDATE"));
assertTrue(KitDeliverySQL.lock(true).contains("SHA2(snapshot_json,256)"));
assertFalse(KitDeliverySQL.acknowledge(true).contains("dune_kit_deliveries"));
}
@Test void postgresKeepsItsBuyerBoundInventoryOutboxSeparate() {
assertTrue(KitDeliverySQL.lock(false).endsWith("FOR UPDATE"));
assertTrue(KitDeliverySQL.acknowledge(false).contains("buyer_uuid=? AND delivered_at IS NULL"));
assertFalse(KitDeliverySQL.pending(false).contains("dune_kit_sales"));
}
}

View file

@ -0,0 +1,37 @@
package com.example.dunekits;
import com.google.gson.*;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class KitSpecTest {
@Test void loreIsLiteralAndPreservesBlankLines() {
KitSpec spec = new KitSpec(KitVerification.example("legendary", "silence", "gold"));
assertEquals("netherite", KitVerification.example("legendary", "silence", "gold").getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("helmet").get("material").getAsString());
assertEquals(3, spec.armor.get("helmet").lore().size());
assertEquals("", PlainTextComponentSerializer.plainText().serialize(spec.armor.get("helmet").lore().get(1).component()));
assertEquals(TextDecoration.State.FALSE, spec.armor.get("helmet").lore().get(0).component().decoration(TextDecoration.ITALIC));
assertEquals("#bca05b", spec.armor.get("helmet").lore().get(0).component().color().asHexString());
assertEquals("border", spec.banner.patterns().get(0).pattern());
assertEquals("rhombus", spec.banner.patterns().get(1).pattern());
}
@Test void arbitraryComponentsAndOversizedLoreAreRejected() {
JsonObject value = KitVerification.example("rare", "dune", "gold");
value.getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("helmet").getAsJsonArray("lore").get(0).getAsJsonObject().add("clickEvent", new JsonObject());
assertThrows(IllegalArgumentException.class, () -> new KitSpec(value));
JsonObject oversized = KitVerification.example("rare", "dune", "gold");
oversized.getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("boots").getAsJsonArray("lore").get(0).getAsJsonObject().addProperty("text", "😀".repeat(61));
assertThrows(IllegalArgumentException.class, () -> new KitSpec(oversized));
}
@Test void historicalReceiptsStayLegacyAndDoNotGainBanners() {
JsonObject value = JsonParser.parseString("{\"name\":\"Original suit\",\"quality\":\"uncommon\",\"color\":\"#385B49\",\"lore\":[\"Original story\",\"\"]}").getAsJsonObject();
KitSpec spec = new KitSpec(value);
assertFalse(spec.modern); assertFalse(spec.banner.enabled());
assertEquals("Original story", spec.armor.get("chestplate").lore().get(0).text());
assertEquals("", spec.armor.get("chestplate").lore().get(1).text());
}
}

View file

@ -0,0 +1,79 @@
"""Install only the reviewed kit bridge modules; refuse unrelated source changes."""
import ast
import hashlib
import os
from pathlib import Path
import py_compile
import sys
BASELINES = {
'player_kits.py': 'fa76420423941189ba08b94382274e40762121e30b008ec0d08e35aa1a00fda3',
'kit_commerce.py': '29395a483fdb3f6d94b36fa57587e3a1391d6e4ed8a44159cbb488dd47d960e6',
}
FILES = ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py', 'kit-equipment-contract.json']
def kit_body_limit(source):
tree = ast.parse(source)
candidates = [node for node in tree.body if isinstance(node, ast.FunctionDef)
and any(isinstance(value, ast.Constant) and value.value == '/kits/player/definition' for value in ast.walk(node))]
if len(candidates) != 1:
raise RuntimeError('Native office kit handler changed')
node = candidates[0]
lines = source.splitlines(keepends=True)
section = ''.join(lines[node.lineno - 1:node.end_lineno])
old, new = 'if not 0 < length <= 8192:', 'if not 0 < length <= 32768:'
if section.count(new) == 1 and old not in section:
return source
if section.count(old) != 1:
raise RuntimeError('Native office body limit changed')
lines[node.lineno - 1:node.end_lineno] = [section.replace(old, new)]
return ''.join(lines)
def install(apply=False):
source = Path(__file__).resolve().parent
target = Path('/opt/dunerealms/server-control')
plans = {}
for name in FILES:
content = (source / name).read_bytes()
destination = target / name
before = destination.read_bytes() if destination.exists() else None
if before == content:
continue
if before is not None and hashlib.sha256(before).hexdigest() != BASELINES.get(name):
raise RuntimeError('Concurrent native change detected in ' + name)
plans[destination] = content
agent = target / 'agent.py'
before = agent.read_text()
after = kit_body_limit(before)
if after != before:
plans[agent] = after.encode()
for name in ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py']:
py_compile.compile(str(source / name), doraise=True)
if not apply:
print('Plan: install', len(plans), 'exact kit module/body-limit changes; no files changed')
return
originals = {path: path.read_bytes() if path.exists() else None for path in plans}
changed = []
try:
for path, content in plans.items():
temporary = path.with_name(path.name + '.kit-v3-new')
temporary.write_bytes(content)
temporary.chmod(path.stat().st_mode & 0o777 if path.exists() else 0o644)
if path.suffix == '.py':
py_compile.compile(str(temporary), doraise=True)
os.replace(temporary, path)
changed.append(path)
except Exception:
for path in reversed(changed):
if originals[path] is None:
path.unlink()
else:
path.write_bytes(originals[path])
raise
print('Installed reviewed kit metadata modules; restart the private control service to activate')
if __name__ == '__main__':
install('--apply' in sys.argv)

View file

@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS dune_kit_deliveries (
id UUID PRIMARY KEY,
buyer_uuid UUID NOT NULL,
snapshot_json TEXT NOT NULL CHECK (octet_length(snapshot_json) <= 65536),
snapshot_hash CHAR(64) NOT NULL CHECK (snapshot_hash ~ '^[a-f0-9]{64}$'),
created_at BIGINT NOT NULL CHECK (created_at > 0),
delivered_at BIGINT NULL CHECK (delivered_at IS NULL OR delivered_at > 0)
);
CREATE INDEX IF NOT EXISTS dune_kit_deliveries_pending ON dune_kit_deliveries(buyer_uuid,created_at,id) WHERE delivered_at IS NULL;

View file

@ -0,0 +1,104 @@
{
"version": 3,
"slots": [
"helmet",
"chestplate",
"leggings",
"boots"
],
"trimPatterns": [
"sentry",
"dune",
"coast",
"wild",
"ward",
"eye",
"vex",
"tide",
"snout",
"rib",
"spire",
"wayfinder",
"shaper",
"silence",
"raiser",
"host",
"flow",
"bolt"
],
"trimMaterials": [
"quartz",
"iron",
"netherite",
"redstone",
"copper",
"gold",
"emerald",
"diamond",
"lapis",
"amethyst",
"resin"
],
"bannerColors": [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black"
],
"bannerPatterns": [
"square_bottom_left",
"square_bottom_right",
"square_top_left",
"square_top_right",
"stripe_bottom",
"stripe_top",
"stripe_left",
"stripe_right",
"stripe_center",
"stripe_middle",
"stripe_downright",
"stripe_downleft",
"small_stripes",
"cross",
"straight_cross",
"triangle_bottom",
"triangle_top",
"triangles_bottom",
"triangles_top",
"diagonal_left",
"diagonal_up_right",
"diagonal_up_left",
"diagonal_right",
"circle",
"rhombus",
"half_vertical",
"half_horizontal",
"half_vertical_right",
"half_horizontal_bottom",
"border",
"curly_border",
"gradient",
"gradient_up",
"bricks",
"globe",
"creeper",
"skull",
"flower",
"mojang",
"piglin",
"flow",
"guster"
]
}

View file

@ -0,0 +1,968 @@
{
"valid": {
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
"normalized": {
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#BCA05B",
"bold": true,
"italic": false
}
]
}
},
"invalid": [
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "Text",
"color": "#AAAAAA",
"bold": false,
"italic": false,
"clickEvent": {
"action": "run_command",
"value": "/op"
}
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
},
{
"pattern": "invalid",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "command_block"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": true,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
}
]
}

View file

@ -0,0 +1,553 @@
"""Private Dunemarks kit commerce; paid orders become bound, one-use deliveries."""
import base64
import hashlib
import hmac
import json
from pathlib import Path
from functools import lru_cache
from decimal import Decimal
from player_bank import identity
from kit_equipment import validate_equipment, validate_upgrade
TIERS = ('common', 'uncommon', 'rare', 'very_rare', 'legendary')
KINDS = ('personal_sale', 'official_sale', 'faction_sale', 'server_sale')
FACTIONS = {'fremen': 'Fremen', 'atreides': 'Atreides', 'harkonnen': 'Harkonnen', 'corrino': 'Corrino', 'ordos': 'Ordos'}
MINIMUM_CENTS = (10000, 20000, 40000, 80000, 160000)
TARGETS = (3, 5, 10, 15, 25)
REWARDS_CENTS = (1000, 2500, 5000, 10000, 20000)
TITLES = ('A Stitch in the Sand', 'Colours of the Caravan', "The Caravan’s Trust", 'Patterns of Influence', 'A Legacy in Gold')
@lru_cache(maxsize=1)
def arc_definition():
path=Path(__file__).with_name('kit-quest-arc-v1.json')
if not path.is_file():
path=Path(__file__).resolve().parents[2]/'website'/'content'/'kit-quest-arc-v1.json'
data=json.loads(path.read_text(encoding='utf-8'))
if len(data.get('chapters',[]))!=5:raise RuntimeError('Invalid canonical quest arc')
for i,row in enumerate(data['chapters']):
if (row['index'],row['quality'],row['targetSales'],row['minimumPriceDunemarks']*100,row['rewardDunemarks']*100)!=(i,TIERS[i],TARGETS[i],MINIMUM_CENTS[i],REWARDS_CENTS[i]):
raise RuntimeError('Quest economy differs from the canonical arc')
return data
class Conflict(Exception):
pass
class InsufficientFunds(Exception):
pass
def allocation_cents(gross, kind='personal_sale'):
if type(gross) is not int or not 1 <= gross <= 100000000:
raise ValueError('Invalid kit price')
if kind not in KINDS:
raise ValueError('Invalid kit commerce kind')
faction = gross * 25 // 100 if kind == 'faction_sale' else 0
server = gross if kind == 'server_sale' else gross * (15 if kind == 'faction_sale' else 20 if kind == 'official_sale' else 25) // 100
return faction, server, gross - faction - server
def split_cents(gross, kind='personal_sale'):
faction, server, seller = allocation_cents(gross, kind)
if kind == 'faction_sale':
raise ValueError('Faction sales require the three-way allocation')
return server, seller
def receipt_code(key, line_id):
identity(line_id)
if not isinstance(key, bytes) or len(key) < 32:
raise RuntimeError('Private item-code key unavailable')
digest = hmac.new(key, b'dunerealms-kit-v1:' + line_id.encode('ascii'), hashlib.sha256).digest()[:20]
return 'DRK-' + base64.b32encode(digest).decode('ascii').rstrip('=')
def code_hash(code):
if not isinstance(code, str) or len(code) != 36 or not code.startswith('DRK-') or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' for c in code[4:]):
raise ValueError('Invalid item code')
return hashlib.sha256(code.encode('ascii')).hexdigest()
def initialize(cur):
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_carts (
id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,payload_hash CHAR(64) NOT NULL,
lines_json TEXT NOT NULL,paid_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_sales (
id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,seller_uuid VARCHAR(36) NOT NULL,
kit_id VARCHAR(36) NOT NULL,kit_version BIGINT NOT NULL,listing_id VARCHAR(36) NOT NULL,
listing_version BIGINT NOT NULL,rarity VARCHAR(16) NOT NULL,shop_type VARCHAR(8) NOT NULL,
commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale',
quantity INT NOT NULL,gross_cents BIGINT NOT NULL,server_tax_cents BIGINT NOT NULL,
faction_tax_cents BIGINT NOT NULL DEFAULT 0,seller_net_cents BIGINT NOT NULL,
snapshot_json TEXT NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,
completed_at BIGINT NOT NULL,redeem_requested_at BIGINT NULL,delivered_at BIGINT NULL,
INDEX dune_kit_sales_progress(seller_uuid,rarity,delivered_at),
INDEX dune_kit_sales_pending(buyer_uuid,redeem_requested_at,delivered_at),
CHECK(quantity=1),CHECK(gross_cents>0),CHECK(server_tax_cents>=0),
CONSTRAINT dune_kit_sales_faction_nonnegative CHECK(faction_tax_cents>=0),CHECK(seller_net_cents>=0),
CONSTRAINT dune_kit_sales_conservation CHECK(gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents),
CONSTRAINT dune_kit_sales_kind CHECK(commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_arc_claims (
player_uuid VARCHAR(36) NOT NULL,stage_index INT NOT NULL,
reward_cents BIGINT NOT NULL,claimed_at BIGINT NOT NULL,
PRIMARY KEY(player_uuid,stage_index),CHECK(stage_index BETWEEN 0 AND 4),CHECK(reward_cents>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
def sales_constraint_migration(cur):
"""Return one atomic MySQL8 ALTER; caller must stop checkout and back up before applying it."""
import re
cur.execute('''SELECT tc.CONSTRAINT_NAME AS name,cc.CHECK_CLAUSE AS clause
FROM information_schema.TABLE_CONSTRAINTS tc
JOIN information_schema.CHECK_CONSTRAINTS cc
ON cc.CONSTRAINT_SCHEMA=tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME=tc.CONSTRAINT_NAME
WHERE tc.TABLE_SCHEMA=DATABASE() AND tc.TABLE_NAME='dune_kit_sales' AND tc.CONSTRAINT_TYPE='CHECK' ''')
checks = cur.fetchall()
def normalize(value):
# MySQL's metadata adds character-set introducers to string CHECK literals.
value = value.replace("\\'", "'")
value = re.sub(r'_(?:utf8mb4|utf8mb3|utf8|ascii|latin1|binary)(?=\')', '', value, flags=re.I)
return re.sub(r'[\s`()]+', '', value).lower()
legacy = {'faction_tax_cents=0', 'gross_cents=server_tax_cents+seller_net_cents'}
desired = {'faction_tax_cents>=0': ('dune_kit_sales_faction_nonnegative', 'faction_tax_cents>=0'),
'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents':
('dune_kit_sales_conservation', 'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents'),
"commerce_kindin'personal_sale','official_sale','faction_sale','server_sale'":
('dune_kit_sales_kind', "commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale')")}
clauses = {normalize(row['clause']) for row in checks}
changes = []
cur.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_kit_sales' AND COLUMN_NAME='commerce_kind'")
count = cur.fetchone()
if not count or type(count['n']) is not int or count['n'] not in (0, 1):
raise RuntimeError('Kit classification schema unavailable')
if count['n'] == 0:
changes.append("ADD COLUMN commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale' AFTER shop_type")
for row in checks:
if normalize(row['clause']) in legacy:
if not re.fullmatch(r'[A-Za-z0-9_]{1,64}', row['name']):
raise RuntimeError('Unexpected kit constraint identity')
changes.append('DROP CHECK `' + row['name'] + '`')
names = {row['name'] for row in checks if normalize(row['clause']) not in legacy}
for normalized, (name, expression) in desired.items():
if normalized not in clauses:
if name in names:
raise RuntimeError('Conflicting kit constraint identity')
changes.append('ADD CONSTRAINT `' + name + '` CHECK(' + expression + ')')
return 'ALTER TABLE dune_kit_sales ' + ', '.join(changes) if changes else None
def listing_context(cur, buyer, listing):
cur.execute('CALL dune_kit_listing_lock(%s,%s)', (buyer,listing))
rows = cur.fetchall()
while cur.nextset():
pass
if len(rows) != 1:
raise PermissionError('Published kit listing unavailable')
return rows[0]
def listing_snapshot(row):
import re
def plain(value, limit):
if not isinstance(value,str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]',value):
raise ValueError('Invalid kit cosmetic text')
return value.strip()
quality = str(row.get('quality','')).lower()
kind = row.get('commerce_kind')
if quality not in TIERS or kind not in KINDS or row.get('shop_type') not in ('player','clan','official','faction','server'):
raise ValueError('Invalid listing type or quality')
shop_types = {'personal_sale': ('player','clan'), 'official_sale': ('official',), 'faction_sale': ('faction',), 'server_sale': ('server',)}
if row['shop_type'] not in shop_types[kind]:
raise ValueError('The listing category does not match its authoritative commerce kind')
color = row.get('kit_color')
if not isinstance(color,str) or not re.fullmatch(r'#[0-9a-fA-F]{6}',color):
raise ValueError('Invalid kit colour')
lore = json.loads(row.get('kit_lore_json',''))
if not isinstance(lore,list) or len(lore)>6:
raise ValueError('Invalid kit lore')
for field in ('listing_version','blueprint_version','price_cents'):
if type(row.get(field)) is not int or row[field]<1:
raise ValueError('Invalid listing revision or price')
if kind == 'personal_sale' and row['price_cents'] < MINIMUM_CENTS[TIERS.index(quality)]:
raise ValueError('Listing is below the tier minimum')
allocation_cents(row['price_cents'], kind)
seller = identity(row['seller_uuid'])
import uuid
if uuid.UUID(seller).int == 0:
raise ValueError('A real verified designer or publisher is required')
item = {'listingId':identity(row['listing_id']),'listingVersion':row['listing_version'],
'blueprintId':identity(row['blueprint_id']),'blueprintVersion':row['blueprint_version'],
'sellerUuid':seller,'clanId':identity(row['clan_id']) if row.get('clan_id') else None,
'shopType':row['shop_type'],'commerceKind':kind,'quality':quality,
'priceCents':row['price_cents'],'name':plain(row['kit_name'],64),'color':color.upper(),
'lore':[plain(line,120) for line in lore]}
equipment = row.get('kit_equipment_json')
if equipment is not None:
item['equipment'] = validate_equipment(json.loads(equipment) if isinstance(equipment, str) else equipment)
names = row.get('kit_item_names_json')
if names is not None:
names = json.loads(names) if isinstance(names, str) else names
if not isinstance(names, dict) or set(names) - {'helmet', 'chestplate', 'leggings', 'boots'} or any(not isinstance(value, str) or len(value) > 64 or re.search(r'[<>§\x00-\x1f\x7f]', value) for value in names.values()):
raise ValueError('Invalid individual item names')
item['itemNames'] = names
upgrade = row.get('kit_upgrade_json')
if upgrade is not None:
item['upgrade'] = validate_upgrade(json.loads(upgrade) if isinstance(upgrade, str) else upgrade, quality, kind)
override = row.get('seller_tier_override', 0)
if type(override) is not int or override not in (0, 1) or (kind != 'personal_sale' and override != 0):
raise ValueError('Invalid authoritative designer tier override')
item['sellerTierOverride'] = override
if kind in ('official_sale', 'faction_sale'):
office, term = row.get('office_key'), row.get('office_term')
if not isinstance(office, str) or not re.fullmatch(r'emperor|(?:house-leader|water-steward|spice-steward):(Fremen|Atreides|Harkonnen|Corrino|Ordos)', office):
raise ValueError('Canonical elected office required')
if not isinstance(term, str) or not 1 <= len(term) <= 190 or not re.fullmatch(r'[A-Za-z0-9:._-]+',term):
raise ValueError('Canonical elected term required')
item.update(officeKey=office, officeTerm=term)
if kind == 'faction_sale':
faction = row.get('faction_id')
if faction not in FACTIONS or item['officeKey'] != 'house-leader:' + FACTIONS[faction]:
raise ValueError('The owning faction and leader office must match')
item['factionId'] = faction
if kind == 'server_sale' and (type(row.get('server_authorized')) is not int or row['server_authorized'] != 1):
raise PermissionError('Current protected publisher authority required')
return item
def current_listing_authority(cur, item, locking=True, cache=None):
if item['commerceKind'] in ('official_sale', 'faction_sale'):
from player_kits import authority
owner = item['sellerUuid']
if cache is None:
offices = authority(cur, owner, locking=locking)
else:
if owner not in cache:
cache[owner] = authority(cur, owner, locking=locking)
offices = cache[owner]
if offices.get(item['officeKey']) != item['officeTerm']:
raise PermissionError('The listing belongs to an expired elected term')
def credit_sale_bank(cur, kind, owner, amount, actor, stamp, reference):
"""Fixed destinations only. Uses the enclosing checkout transaction and unique sale reference."""
import uuid
if amount == 0:
return
if kind == 'personal':
table, key, ledger = 'dune_player_banks', 'player_uuid', 'dune_player_bank_ledger'
elif kind == 'faction' and owner in FACTIONS:
table, key, ledger = 'dune_faction_bank_wallet', 'faction_id', 'dune_faction_bank_ledger'
else:
raise ValueError('Invalid sale bank destination')
cur.execute('INSERT INTO '+table+'('+key+',balance,updated_at) VALUES(%s,0,%s) ON DUPLICATE KEY UPDATE '+key+'='+key,(owner,stamp))
cur.execute('SELECT balance FROM '+table+' WHERE '+key+'=%s FOR UPDATE',(owner,))
row=cur.fetchone()
if row is None:
raise RuntimeError('Sale bank unavailable')
before=Decimal(row['balance']);after=before+amount
if before<0 or after>Decimal('1000000000000'):
raise ValueError('A sale bank limit was reached')
cur.execute('UPDATE '+table+' SET balance=%s,updated_at=%s WHERE '+key+'=%s',(after,stamp,owner))
if kind == 'personal':
cur.execute('INSERT INTO '+ledger+'(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,'faction-kit-sale',amount,after,stamp,reference))
else:
cur.execute('INSERT INTO '+ledger+'(id,faction_id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,actor,'faction-kit-sale',amount,after,stamp,reference))
def checkout(connect, key, payload, context=listing_context):
fields={'buyerUuid','listingId','orderLineId','listingVersion','blueprintVersion','priceCents'}
if not isinstance(payload,dict) or set(payload)!=fields:
raise ValueError('Invalid checkout fields')
buyer=identity(payload['buyerUuid']);listing=identity(payload['listingId']);line=identity(payload['orderLineId'])
for field in ('listingVersion','blueprintVersion','priceCents'):
if type(payload[field]) is not int or payload[field]<1:
raise ValueError('Review the current listing before purchasing')
code=receipt_code(key,line);digest=code_hash(code)
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT buyer_uuid,listing_id,listing_version,kit_version,gross_cents,code_hash FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line,))
old=cur.fetchone()
if old:
if (old['buyer_uuid'],old['listing_id'],old['listing_version'],old['kit_version'],old['gross_cents']) != (buyer,listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']):
raise Conflict('Order line already belongs to a different purchase')
if not hmac.compare_digest(old['code_hash'],digest):
raise RuntimeError('Item-code key differs from the original receipt')
con.rollback()
return {'ok':True,'alreadyPaid':True,'orderLineId':line,'code':code,'delivery':'redeem-code'}
authority=context(cur,buyer,listing)
if authority.get('buyer_uuid') != buyer or authority.get('commerce_kind') not in KINDS:
raise PermissionError('Current verified buyer and supported listing required')
item=listing_snapshot(authority)
current_listing_authority(cur,item)
if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']):
raise Conflict('The listing changed; review its current price and design')
seller=item['sellerUuid'];tier=TIERS.index(item['quality'])
kind=item['commerceKind']
if kind == 'personal_sale' and not item['sellerTierOverride'] and tier > len(claimed(cur,seller)):
raise PermissionError('Designer has not unlocked this kit tier')
wallets={}
for player in sorted({buyer,seller} if kind in ('personal_sale','official_sale') else {buyer}):
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,))
row=cur.fetchone()
if row is None:
raise PermissionError('Existing buyer and designer Minecraft wallets are required')
wallets[player]=Decimal(row['balance'])
gross=Decimal(item['priceCents'])/100
if wallets[buyer]<gross:
raise InsufficientFunds('Insufficient Dunemarks')
faction_cents,tax_cents,net_cents=allocation_cents(item['priceCents'],kind);tax=Decimal(tax_cents)/100
cur.execute("INSERT INTO dune_staff_bank_wallet(account_key,balance,updated_at) VALUES('network',0,0) ON DUPLICATE KEY UPDATE account_key=account_key")
cur.execute("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE")
treasury=Decimal(cur.fetchone()['balance'])+tax
wallets[buyer]-=gross
if kind in ('personal_sale','official_sale'):
wallets[seller]+=Decimal(net_cents)/100
if treasury>Decimal('1000000000000') or any(v>Decimal('1000000000000') for v in wallets.values()):
raise ValueError('A wallet or treasury limit was reached')
stamp=now(cur)
if kind == 'faction_sale':
credit_sale_bank(cur,'personal',seller,Decimal(net_cents)/100,buyer,stamp,'kit-sale:'+line)
credit_sale_bank(cur,'faction',item['factionId'],Decimal(faction_cents)/100,buyer,stamp,'kit-sale:'+line)
cur.execute('''INSERT INTO dune_kit_sales(id,buyer_uuid,seller_uuid,kit_id,kit_version,listing_id,listing_version,rarity,shop_type,commerce_kind,quantity,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents,snapshot_json,code_hash,completed_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,1,%s,%s,%s,%s,%s,%s,%s)''',
(line,buyer,seller,item['blueprintId'],item['blueprintVersion'],listing,item['listingVersion'],item['quality'],item['shopType'],kind,item['priceCents'],tax_cents,faction_cents,net_cents,json.dumps(item),digest,stamp))
for player,balance in wallets.items():
cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s',(balance,player))
cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'",(treasury,stamp))
import uuid
cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),buyer,'kit-sale-tax',tax,treasury,stamp,'kit-sale:'+line))
con.commit()
return {'ok':True,'alreadyPaid':False,'orderLineId':line,'code':code,'delivery':'redeem-code'}
except Exception:
con.rollback();raise
def now(cur):
cur.execute('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED) AS now')
return int(cur.fetchone()['now'])
def cart_input(payload):
if not isinstance(payload,dict) or set(payload)!={'buyerUuid','cartId','lines'}:
raise ValueError('Invalid cart fields')
buyer=identity(payload['buyerUuid']);cart=identity(payload['cartId'])
if not isinstance(payload['lines'],list) or not 1<=len(payload['lines'])<=20:
raise ValueError('A cart must contain one to twenty kit lines')
lines=[]
for row in payload['lines']:
if not isinstance(row,dict) or set(row)!={'listingId','orderLineId','listingVersion','blueprintVersion','priceCents'}:
raise ValueError('Invalid cart line')
for field in ('listingVersion','blueprintVersion','priceCents'):
if type(row[field]) is not int or row[field]<1:raise ValueError('Invalid cart revision or price')
split_cents(row['priceCents'])
lines.append({**row,'buyerUuid':buyer,'listingId':identity(row['listingId']),'orderLineId':identity(row['orderLineId'])})
if len({row['orderLineId'] for row in lines})!=len(lines):raise ValueError('Duplicate order line')
lines.sort(key=lambda row:row['orderLineId'])
canonical=json.dumps({'buyerUuid':buyer,'cartId':cart,'lines':lines},sort_keys=True,separators=(',',':'))
return buyer,cart,lines,hashlib.sha256(canonical.encode()).hexdigest()
def checkout_cart(connect,key,payload,context=listing_context):
buyer,cart,lines,fingerprint=cart_input(payload)
with connect() as con:
# Reuse the single-line engine inside ONE outer transaction. Inner boundaries cannot commit partial carts.
class SharedTransaction:
def __enter__(self):return self
def __exit__(self,*args):pass
def cursor(self):return con.cursor()
def begin(self):pass
def commit(self):pass
def rollback(self):pass
def shared():return SharedTransaction()
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT buyer_uuid,payload_hash FROM dune_kit_carts WHERE id=%s FOR UPDATE',(cart,))
old=cur.fetchone()
if old:
if old['buyer_uuid']!=buyer or not hmac.compare_digest(old['payload_hash'],fingerprint):
raise Conflict('This cart was already paid with different contents')
result=[checkout(shared,key,line,context) for line in lines]
if not all(row['alreadyPaid'] for row in result):
raise RuntimeError('Paid cart has an incomplete order receipt')
con.rollback()
return {'ok':True,'alreadyPaid':True,'cartId':cart,'lines':result,'delivery':'redeem-code'}
for line in lines:
cur.execute('SELECT id FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line['orderLineId'],))
if cur.fetchone():raise Conflict('An order line already belongs to another purchase')
authorities={}
for listing in sorted({line['listingId'] for line in lines}):
row=context(cur,buyer,listing)
if row.get('buyer_uuid')!=buyer or row.get('commerce_kind') not in KINDS:
raise PermissionError('Current verified buyer required')
authorities[listing]=row
sellers=set();total=Decimal(0)
for line in lines:
item=listing_snapshot(authorities[line['listingId']])
current_listing_authority(cur,item)
if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (line['listingId'],line['listingVersion'],line['blueprintVersion'],line['priceCents']):
raise Conflict('A cart listing changed; review the entire cart')
if item['commerceKind']=='personal_sale' and not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(claimed(cur,item['sellerUuid'])):
raise PermissionError('Designer has not unlocked this kit tier')
if item['commerceKind'] in ('personal_sale','official_sale'):
sellers.add(item['sellerUuid'])
total+=Decimal(item['priceCents'])/100
# Lock every participant in a stable global order before any line is charged.
balance=None
for player in sorted(sellers|{buyer}):
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,))
row=cur.fetchone()
if not row:raise PermissionError('Existing Minecraft wallets required')
if player==buyer:balance=Decimal(row['balance'])
if balance is None or balance<total:raise InsufficientFunds('Insufficient Dunemarks for the entire cart')
result=[checkout(shared,key,line,lambda cursor,owner,listing:authorities[listing]) for line in lines]
cur.execute('INSERT INTO dune_kit_carts(id,buyer_uuid,payload_hash,lines_json,paid_at) VALUES(%s,%s,%s,%s,%s)',(cart,buyer,fingerprint,json.dumps(lines),now(cur)))
con.commit()
return {'ok':True,'alreadyPaid':False,'cartId':cart,'lines':result,'delivery':'redeem-code'}
except Exception:
con.rollback();raise
def stage(value):
if type(value) is not int or value not in range(5):
raise ValueError('Invalid kit tier')
return value
def claimed(cur, player):
cur.execute('SELECT stage_index FROM dune_kit_arc_claims WHERE player_uuid=%s ORDER BY stage_index', (player,))
stages = [int(row['stage_index']) for row in cur.fetchall()]
if stages != list(range(len(stages))) or len(stages) > 5:
raise RuntimeError('Invalid quest claim sequence')
return stages
def progress(cur, player, index):
# One buyer/tier/UTC delivery day. Quantity, self-sales and unpaid/unredeemed codes cannot inflate progress.
cur.execute('''SELECT COUNT(*) AS n FROM (
SELECT buyer_uuid,FLOOR(delivered_at/86400000) AS utc_day FROM dune_kit_sales
WHERE seller_uuid=%s AND rarity=%s AND buyer_uuid<>seller_uuid AND commerce_kind='personal_sale'
AND delivered_at IS NOT NULL AND quantity=1 AND gross_cents>=%s
GROUP BY buyer_uuid,FLOOR(delivered_at/86400000)
) AS qualifying''', (player, TIERS[index], MINIMUM_CENTS[index]))
return int(cur.fetchone()['n'])
def read_arc(connect, player):
player = identity(player)
definition=arc_definition()
with connect() as con:
with con.cursor() as cur:
done = claimed(cur, player)
chapters = []
for index in range(5):
count = progress(cur, player, index)
story=definition['chapters'][index]
chapters.append({'index': index, 'key': story['key'], 'quality':TIERS[index], 'title': story['title'],
'description':story['description'],'kitTemplate':story['kitTemplate'],'sales': count,
'target': TARGETS[index], 'minimumPriceDunemarks': format(Decimal(MINIMUM_CENTS[index])/100, '.2f'),
'rewardDunemarks': format(Decimal(REWARDS_CENTS[index])/100, '.2f'),
'claimed': index in done, 'unlocked': index <= len(done),
'canClaim': index == len(done) and count >= TARGETS[index]})
return {'playerUuid': player, 'title': 'The Loom of the Desert', 'chapters': chapters,
'rewardSource': 'server-bank', 'salesRule': 'Paid, delivered sales of your own designs; one external buyer per tier per UTC day.'}
def read_orders(connect, key, player):
player=identity(player)
with connect() as con:
with con.cursor() as cur:
cur.execute('''SELECT id,buyer_uuid,seller_uuid,kit_id,rarity,shop_type,commerce_kind,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents,
snapshot_json,code_hash,completed_at,redeem_requested_at,delivered_at FROM dune_kit_sales
WHERE buyer_uuid=%s OR seller_uuid=%s ORDER BY completed_at DESC,id DESC LIMIT 100''',(player,player))
orders=[]
for row in cur.fetchall():
item=json.loads(row['snapshot_json'])
entry={'orderLineId':row['id'],'side':'purchase' if row['buyer_uuid']==player else 'sale',
'name':item['name'],'quality':row['rarity'],'shopType':row['shop_type'],'commerceKind':row['commerce_kind'],
'grossDunemarks':format(Decimal(row['gross_cents'])/100,'.2f'),
'serverTaxDunemarks':format(Decimal(row['server_tax_cents'])/100,'.2f'),
'factionTaxDunemarks':format(Decimal(row['faction_tax_cents'])/100,'.2f'),
'sellerNetDunemarks':format(Decimal(row['seller_net_cents'])/100,'.2f'),
'sellerPayoutDestination':'personal-bank' if row['commerce_kind']=='faction_sale' else 'none' if row['commerce_kind']=='server_sale' else 'wallet',
'completedAt':row['completed_at'],'deliveredAt':row['delivered_at'],
'status':'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery' if row['redeem_requested_at'] is not None else 'code-ready'}
if row['buyer_uuid']==player:
code=receipt_code(key,row['id'])
if not hmac.compare_digest(code_hash(code),row['code_hash']):
raise RuntimeError('Item-code key differs from receipt')
entry['code']=code
orders.append(entry)
return {'playerUuid':player,'currency':'dunemarks','orders':orders}
def catalogue(connect):
with connect() as con:
with con.cursor() as cur:
cur.execute('CALL dune_kit_catalogue()');rows=cur.fetchall()
while cur.nextset():pass
cur.execute('SELECT listing_id,COUNT(*) AS sales FROM dune_kit_sales WHERE delivered_at IS NOT NULL AND buyer_uuid<>seller_uuid GROUP BY listing_id')
popularity={row['listing_id']:int(row['sales']) for row in cur.fetchall()}
owners=sorted({identity(row['seller_uuid']) for row in rows if row.get('commerce_kind')=='personal_sale'})
unlocked={owner:set() for owner in owners}
if owners:
cur.execute('SELECT player_uuid,stage_index FROM dune_kit_arc_claims WHERE player_uuid IN ('+','.join(['%s']*len(owners))+')',tuple(owners))
for row in cur.fetchall():unlocked[row['player_uuid']].add(int(row['stage_index']))
listings=[];office_cache={}
for row in rows:
item=listing_snapshot(row)
try:
current_listing_authority(cur,item,locking=False,cache=office_cache)
except PermissionError:
continue
if item['commerceKind']=='personal_sale':
stages=sorted(unlocked[item['sellerUuid']])
if stages!=list(range(len(stages))) or (not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(stages)):continue
item['completedSales']=popularity.get(item['listingId'],0)
item['sellerName']=str(row['seller_name'])[:64]
item['priceDunemarks']=format(Decimal(item['priceCents'])/100,'.2f')
listings.append(item)
return {'currency':'dunemarks','listings':listings}
def queue_redemption(connect, player, code):
player = identity(player); digest = code_hash(code)
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT id,buyer_uuid,delivered_at,redeem_requested_at FROM dune_kit_sales WHERE code_hash=%s FOR UPDATE', (digest,))
row = cur.fetchone()
if not row or row['buyer_uuid'] != player:
raise PermissionError('Item code is unavailable for this account')
if row['delivered_at'] is None and row['redeem_requested_at'] is None:
cur.execute('UPDATE dune_kit_sales SET redeem_requested_at=%s WHERE id=%s AND redeem_requested_at IS NULL', (now(cur), row['id']))
result = {'ok': True, 'orderLineId': row['id'], 'status': 'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery'}
con.commit()
return result
except Exception:
con.rollback();raise
def claim_arc(connect, player, index):
player = identity(player); index = stage(index)
arc_definition()
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
# Central treasury lock serializes rewards across servers and makes insufficient funding retryable.
cur.execute("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE")
treasury = cur.fetchone()
done = claimed(cur, player)
if index in done:
con.rollback();return {'ok': True, 'alreadyClaimed': True, 'stage': index}
if index != len(done) or progress(cur, player, index) < TARGETS[index]:
raise PermissionError('Complete the current sales chapter first')
reward = Decimal(REWARDS_CENTS[index])/100
if not treasury or Decimal(treasury['balance']) < reward:
con.rollback();return {'ok': False, 'pending': True, 'reason': 'server-bank-funding', 'stage': index}
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE', (player,))
wallet = cur.fetchone()
if wallet is None:
raise PermissionError('An existing Minecraft wallet is required')
amount = Decimal(wallet['balance']) + reward
if amount > Decimal('1000000000000'):
raise ValueError('Wallet limit reached')
stamp = now(cur)
cur.execute('INSERT INTO dune_kit_arc_claims(player_uuid,stage_index,reward_cents,claimed_at) VALUES(%s,%s,%s,%s)', (player,index,REWARDS_CENTS[index],stamp))
balance = Decimal(treasury['balance'])-reward
cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'", (balance,stamp))
cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s', (amount,player))
import uuid
reference = 'kit-arc:'+player+':'+str(index)
cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)', (str(uuid.uuid4()),player,'kit-arc-reward',-reward,balance,stamp,reference))
con.commit()
return {'ok': True, 'alreadyClaimed': False, 'stage': index, 'rewardDunemarks': format(reward,'.2f')}
except Exception:
con.rollback();raise

View file

@ -0,0 +1,73 @@
"""Versioned kit cosmetics; only bounded literal text and vanilla item metadata."""
import copy
import json
import re
from pathlib import Path
CONTRACT = json.loads(Path(__file__).with_name('kit-equipment-contract.json').read_text())
def exact(value, fields):
return isinstance(value, dict) and set(value) == set(fields)
def text(value, maximum):
return isinstance(value, str) and len(value.encode('utf-16-le')) // 2 <= maximum and not re.search(r'[\x00-\x1f\x7f<>§]', value)
def validate_lore(value):
if not isinstance(value, list) or len(value) > 6:
raise ValueError('Use at most six item lore lines')
result = []
for line in value:
if (not exact(line, ['text', 'color', 'bold', 'italic']) or not text(line['text'], 120)
or not isinstance(line['color'], str) or not re.fullmatch(r'#[a-f0-9]{6}', line['color'], re.I)
or type(line['bold']) is not bool or type(line['italic']) is not bool):
raise ValueError('Invalid literal item lore')
result.append({**line, 'color': line['color'].upper()})
return result
def validate_equipment(value):
if not exact(value, ['version', 'armor', 'banner']) or type(value['version']) is not int or value['version'] != 3 or not exact(value['armor'], CONTRACT['slots']):
raise ValueError('Complete version 3 kit required')
armor = {}
for slot in CONTRACT['slots']:
piece = value['armor'][slot]
if (not exact(piece, ['material', 'name', 'lore', 'trim']) or piece['material'] != 'netherite'
or not text(piece['name'], 64) or not exact(piece['trim'], ['pattern', 'material'])
or piece['trim']['pattern'] not in CONTRACT['trimPatterns'] or piece['trim']['material'] not in CONTRACT['trimMaterials']):
raise ValueError('Invalid armour piece or trim')
armor[slot] = {**piece, 'name': piece['name'].strip(), 'lore': validate_lore(piece['lore']), 'trim': dict(piece['trim'])}
banner = value['banner']
if (not exact(banner, ['enabled', 'name', 'base', 'patterns', 'lore']) or type(banner['enabled']) is not bool
or not text(banner['name'], 64) or banner['base'] not in CONTRACT['bannerColors']
or not isinstance(banner['patterns'], list) or len(banner['patterns']) > 6):
raise ValueError('Invalid banner')
for layer in banner['patterns']:
if not exact(layer, ['pattern', 'color']) or layer['pattern'] not in CONTRACT['bannerPatterns'] or layer['color'] not in CONTRACT['bannerColors']:
raise ValueError('Invalid banner layer')
return {'version': 3, 'armor': armor, 'banner': {**banner, 'name': banner['name'].strip(), 'patterns': copy.deepcopy(banner['patterns']), 'lore': validate_lore(banner['lore'])}}
def default_equipment(legacy):
lore = [{'text': line, 'color': '#AAAAAA', 'bold': False, 'italic': False} for line in legacy.get('lore', [])[:6]]
return validate_equipment({'version': 3, 'armor': {slot: {'material': 'netherite', 'name': legacy.get('itemNames', {}).get(slot, ''), 'lore': copy.deepcopy(lore), 'trim': {'pattern': 'dune', 'material': 'gold'}} for slot in CONTRACT['slots']}, 'banner': {'enabled': False, 'name': '', 'base': 'black', 'patterns': [], 'lore': []}})
def validate_upgrade(value, quality, kind):
if quality != 'legendary' or kind != 'personal_sale' or not exact(value, ['policy', 'points', 'bonuses']) or value['policy'] != 'legendary-player-v1' or type(value['points']) is not int or not 1 <= value['points'] <= 3 or not isinstance(value['bonuses'], list) or not 1 <= len(value['bonuses']) <= 3:
raise ValueError('Invalid Legendary Player Kit upgrade')
selected, total = set(), 0
for bonus in value['bonuses']:
if not exact(bonus, ['piece', 'enchantment', 'levels']) or bonus['piece'] not in CONTRACT['slots']:
raise ValueError('Invalid upgrade piece')
allowed = {'protection', 'unbreaking', 'mending', 'thorns'}
allowed.update({'helmet': ['respiration', 'aqua_affinity'], 'leggings': ['swift_sneak'], 'boots': ['feather_falling', 'depth_strider', 'soul_speed']}.get(bonus['piece'], []))
if bonus['enchantment'] not in allowed or type(bonus['levels']) is not int or not 1 <= bonus['levels'] <= 3 or (bonus['piece'], bonus['enchantment']) in selected:
raise ValueError('Invalid upgrade distribution')
selected.add((bonus['piece'], bonus['enchantment']))
total += bonus['levels']
if total != value['points']:
raise ValueError('Upgrade points do not balance')
return copy.deepcopy(value)

View file

@ -0,0 +1,152 @@
"""Term-bound office blueprints. Private bridge only; authority comes from game SQL."""
import json
import re
import uuid
import time
from kit_equipment import validate_equipment, default_equipment
HOUSES = ('Fremen', 'Harkonnen', 'Corrino', 'Atreides', 'Ordos')
class Conflict(Exception):
pass
def identity(value):
if not isinstance(value, str) or not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', value):
raise ValueError('Verified Minecraft UUID required')
return str(uuid.UUID(value))
def winner(election):
tally = election.get('tally', {}) if isinstance(election, dict) else {}
valid = []
for key, count in tally.items():
try:
player = identity(key)
except (ValueError, TypeError):
continue
if type(count) is int and count > 0:
valid.append((player, count))
return sorted(valid, key=lambda row: (-row[1], row[0]))[0][0] if valid else ''
def at(record, *keys):
for key in keys:
if not isinstance(record, dict):
return {}
record = record.get(key, record.get(str(key), {}))
return record
def interim_winner(record, kind, faction=None, now=None):
now = int(time.time() * 1000) if now is None else now
entry = at(record, 'interim', kind) if kind == 'emperor' else at(record, 'interim', 'house', faction)
try:
player = identity(entry.get('uuid'))
start, end = entry.get('startsAt'), entry.get('expiresAt')
return player if type(start) is int and type(end) is int and start <= now < end else ''
except (ValueError, TypeError, AttributeError):
return ''
def offices(record, week, player, faction):
result = {}
emperor = interim_winner(record, 'emperor') or winner(at(record, 'votes', 'emperor', week))
if player == emperor:
result['emperor'] = f'emperor:{week}:{player}'
if faction in HOUSES and player == (interim_winner(record, 'house', faction) or winner(at(record, 'votes', 'house', week, faction))):
result['house-leader:' + faction] = f'house-leader:{faction}:{week}:{player}'
for appointment, office in (('water', 'water-steward'), ('steward', 'spice-steward')):
entry = at(record, 'appointments', appointment)
if emperor and at(entry, 'week') == week and at(entry, 'emperor') == emperor and at(entry, 'house') == faction:
result[office + ':' + faction] = f'{office}:{faction}:{week}:{player}:{emperor}'
return result
def initialize(cursor):
cursor.execute('''CREATE TABLE IF NOT EXISTS dune_office_kit_definitions (
owner_uuid VARCHAR(36) NOT NULL,office_key VARCHAR(96) NOT NULL,
term_id VARCHAR(190) NOT NULL,version INTEGER NOT NULL,
kit_name VARCHAR(64) NOT NULL,color VARCHAR(7) NOT NULL,lore_json TEXT NOT NULL,
updated_at BIGINT NOT NULL,PRIMARY KEY(owner_uuid,office_key,term_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cursor.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_office_kit_definitions' AND COLUMN_NAME='equipment_json'")
if cursor.fetchone()['n'] == 0:
cursor.execute('ALTER TABLE dune_office_kit_definitions ADD COLUMN equipment_json JSON NULL')
def authority(cursor, player, locking=False):
import yaml
suffix = ' FOR SHARE' if locking else ''
cursor.execute('SELECT yaml FROM dune_politics WHERE id=1' + suffix)
row = cursor.fetchone()
if not row or not isinstance(row['yaml'], str) or len(row['yaml']) > 2097152:
raise RuntimeError('Political authority unavailable')
record = yaml.safe_load(row['yaml']) or {}
cursor.execute('SELECT faction FROM dune_players WHERE uuid=%s' + suffix, (player,))
row = cursor.fetchone()
faction = row['faction'] if row else ''
cursor.execute('SELECT FLOOR(UNIX_TIMESTAMP(CURRENT_TIMESTAMP)/604800) AS week')
week = int(cursor.fetchone()['week'])
return offices(record, week, player, faction)
def validate(data):
if not isinstance(data, dict) or set(data) != ({'uuid', 'office', 'term', 'version', 'name', 'color', 'lore'} | ({'equipment'} if 'equipment' in data else set())):
raise ValueError('Invalid blueprint fields')
if 'equipment' in data:
data = {**data, 'equipment': validate_equipment(data['equipment'])}
player = identity(data['uuid'])
if data['office'] != 'emperor' and not (isinstance(data['office'], str) and re.fullmatch(r'(house-leader|water-steward|spice-steward):(Fremen|Harkonnen|Corrino|Atreides|Ordos)', data['office'])):
raise ValueError('Invalid office')
if not isinstance(data['term'], str) or not 1 <= len(data['term']) <= 190:
raise ValueError('Invalid elected term')
if type(data['version']) is not int or not 0 <= data['version'] < 2147483647:
raise ValueError('Invalid blueprint version')
def text(value, limit):
if not isinstance(value, str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]', value):
raise ValueError('Use plain text for kit names and lore')
return value.strip()
name = text(data['name'], 64)
if not isinstance(data['color'], str) or not re.fullmatch(r'#[0-9A-Fa-f]{6}', data['color']):
raise ValueError('Use a six-digit colour')
if not isinstance(data['lore'], list) or len(data['lore']) > 6:
raise ValueError('Use at most six lore lines')
return {**data, 'uuid': player, 'name': name, 'color': data['color'].upper(), 'lore': [text(line, 120) for line in data['lore']]}
def read(connect, player):
player = identity(player)
with connect() as con:
with con.cursor() as cursor:
current = authority(cursor, player)
cursor.execute('SELECT office_key,term_id,version,kit_name,color,lore_json,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s', (player,))
definitions = {row['office_key']: row for row in cursor.fetchall() if current.get(row['office_key']) == row['term_id']}
rows = []
for office, term in current.items():
row = definitions.get(office)
rows.append({'office': office, 'term': term, 'version': row['version'] if row else 0, 'name': row['kit_name'] if row else 'Imperial Stillsuit', 'color': row['color'] if row else '#571F82', 'lore': json.loads(row['lore_json']) if row else [], 'quality': 'uncommon', 'equipment': validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else None})
return {'playerUuid': player, 'canDesign': bool(rows), 'offices': rows}
def save(connect, payload):
data = validate(payload)
with connect() as con:
try:
con.begin()
with con.cursor() as cursor:
if authority(cursor, data['uuid'], True).get(data['office']) != data['term']:
raise PermissionError('Current elected office required')
args = (data['uuid'], data['office'], data['term'])
cursor.execute('SELECT version,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s AND office_key=%s AND term_id=%s FOR UPDATE', args)
row = cursor.fetchone()
if (row['version'] if row else 0) != data['version']:
raise Conflict('Blueprint changed; reload before saving')
equipment = data.get('equipment') or (validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else default_equipment(data))
if row:
cursor.execute('''UPDATE dune_office_kit_definitions SET version=%s,kit_name=%s,color=%s,lore_json=%s,equipment_json=%s,
updated_at=CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED)
WHERE owner_uuid=%s AND office_key=%s AND term_id=%s AND version=%s''',
(data['version'] + 1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment)) + args + (data['version'],))
if cursor.rowcount != 1:
raise Conflict('Blueprint changed; reload before saving')
else:
cursor.execute('''INSERT INTO dune_office_kit_definitions(owner_uuid,office_key,term_id,version,kit_name,color,lore_json,equipment_json,updated_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED))''',
args + (1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment)))
con.commit()
except Exception:
con.rollback()
raise
return {'ok': True, 'uuid': data['uuid'], 'office': data['office'], 'term': data['term'], 'version': data['version'] + 1}

Some files were not shown because too many files have changed in this diff Show more