SHA256
107 lines
5.2 KiB
Java
107 lines
5.2 KiB
Java
package server.archive;
|
|
|
|
import blockchain.Ans104DataItem;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
import java.io.IOException;
|
|
import java.net.URI;
|
|
import java.net.http.HttpClient;
|
|
import java.net.http.HttpRequest;
|
|
import java.net.http.HttpResponse;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.security.MessageDigest;
|
|
import java.time.Duration;
|
|
import java.util.Arrays;
|
|
import java.util.Base64;
|
|
import java.util.Objects;
|
|
|
|
/** Uploads an already user-signed ANS-104 DataItem to Turbo without modifying it. */
|
|
public final class TurboDataItemUploader {
|
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
|
private static final Base64.Encoder B64URL = Base64.getUrlEncoder().withoutPadding();
|
|
private static final Base64.Decoder B64URL_DECODER = Base64.getUrlDecoder();
|
|
|
|
public record UploadResult(String dataItemId, String owner) {}
|
|
|
|
private final ArweaveBlocksConfig cfg;
|
|
private final HttpClient http = HttpClient.newBuilder()
|
|
.connectTimeout(Duration.ofSeconds(20))
|
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
|
.build();
|
|
private volatile String resolvedPaidByAddress;
|
|
|
|
public TurboDataItemUploader(ArweaveBlocksConfig cfg) {
|
|
this.cfg = Objects.requireNonNull(cfg);
|
|
}
|
|
|
|
public UploadResult upload(byte[] rawDataItem, byte[] expectedId32) throws Exception {
|
|
if (rawDataItem == null || rawDataItem.length == 0) throw new IllegalArgumentException("Turbo DataItem is empty");
|
|
Ans104DataItem item = new Ans104DataItem(rawDataItem);
|
|
if (!item.verifySignature()) throw new IllegalArgumentException("Turbo DataItem has bad ANS-104 signature");
|
|
if (expectedId32 != null && !Arrays.equals(item.id32(), expectedId32)) {
|
|
throw new IllegalArgumentException("Turbo DataItem id does not match blocks.data_item_id");
|
|
}
|
|
|
|
String expectedId = B64URL.encodeToString(item.id32());
|
|
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(cfg.turboUploadUrl()))
|
|
.timeout(Duration.ofMinutes(2))
|
|
.header("Content-Type", "application/octet-stream")
|
|
.header("Accept", "application/json")
|
|
.POST(HttpRequest.BodyPublishers.ofByteArray(rawDataItem));
|
|
String paidBy = paidByAddress();
|
|
if (paidBy != null) request.header("x-paid-by", paidBy);
|
|
|
|
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
|
String body = response.body() == null ? "" : response.body().trim();
|
|
if (response.statusCode() == 409 && body.toLowerCase().contains("data item exists")) {
|
|
return new UploadResult(expectedId, B64URL.encodeToString(item.owner32()));
|
|
}
|
|
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
|
String hint = response.statusCode() == 402
|
|
? " (Turbo payment required: check server credits / Credit Share Approval / x-paid-by)"
|
|
: "";
|
|
throw new IOException("Turbo HTTP " + response.statusCode() + hint + ": " + safe(body));
|
|
}
|
|
|
|
if (body.isBlank()) return new UploadResult(expectedId, B64URL.encodeToString(item.owner32()));
|
|
JsonNode json;
|
|
try { json = MAPPER.readTree(body); }
|
|
catch (Exception ignored) { return new UploadResult(expectedId, B64URL.encodeToString(item.owner32())); }
|
|
String returnedId = json.path("id").asText("").trim();
|
|
if (!returnedId.isBlank() && !returnedId.equals(expectedId)) {
|
|
throw new IOException("Turbo returned another DataItem id: expected=" + expectedId + " got=" + returnedId);
|
|
}
|
|
return new UploadResult(expectedId, json.path("owner").asText(""));
|
|
}
|
|
|
|
/**
|
|
* x-paid-by contains the payer's public native address, never the private key.
|
|
* A configured Arweave JWK is used only to derive that public address.
|
|
*/
|
|
private String paidByAddress() throws Exception {
|
|
if (resolvedPaidByAddress != null) return resolvedPaidByAddress.isBlank() ? null : resolvedPaidByAddress;
|
|
synchronized (this) {
|
|
if (resolvedPaidByAddress != null) return resolvedPaidByAddress.isBlank() ? null : resolvedPaidByAddress;
|
|
String explicit = cfg.turboPaidByAddress();
|
|
if (explicit != null && !explicit.isBlank()) return resolvedPaidByAddress = explicit.trim();
|
|
if (cfg.turboWalletJwkPath() == null) {
|
|
resolvedPaidByAddress = "";
|
|
return null;
|
|
}
|
|
JsonNode jwk = MAPPER.readTree(Files.readString(cfg.turboWalletJwkPath(), StandardCharsets.UTF_8));
|
|
String modulus = jwk.path("n").asText("").trim();
|
|
if (modulus.isBlank()) throw new IllegalStateException("Turbo payer JWK missing n");
|
|
byte[] owner = B64URL_DECODER.decode(modulus);
|
|
resolvedPaidByAddress = B64URL.encodeToString(MessageDigest.getInstance("SHA-256").digest(owner));
|
|
return resolvedPaidByAddress;
|
|
}
|
|
}
|
|
|
|
private static String safe(String value) {
|
|
String v = value == null ? "" : value.replace('\n',' ').replace('\r',' ').trim();
|
|
return v.length() <= 500 ? v : v.substring(0, 500);
|
|
}
|
|
}
|