import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* v0.1 DRAFT. Borrou collateral-address verification, JDK only (Java 17+, whose Ed25519 is
* built in).
*
*
Every deposit and top-up address comes with {@code address_attestation}: Borrou's Ed25519
* signature over a short statement of the address. Verify it before your app shows the address,
* and show the verification code beside it; the borrower's loan page shows the same code with the
* same address.
*
*
* - Find the key: GET /v1/address-keys lists the public keys by {@code key_id} (no credential
* needed). Cache the list; fetch it again when an attestation names a key id you do not hold.
*
- Verify the signature over the statement's UTF-8 bytes exactly as received.
*
- Read the statement: eight {@code name=value} lines in a fixed order, LF-separated, no
* trailing newline, for purpose BORROU_COLLATERAL_ADDRESS_V1, asset BTC, network bitcoin, and
* the same key id as the attestation.
*
- Check its address and loan reference against what you are about to show.
*
- Work out the verification code from the signature and check it is the one you were given.
*
*
* Anything else: show no address, and contact TFG.
*/
public final class BorrouAddresses {
private static final String[] FIELDS = {"purpose", "asset", "network", "address", "loan_reference", "wallet", "key_id", "signed_at"};
private static final Pattern VALUE = Pattern.compile("[\\x21-\\x7e]+");
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
public enum Reason {
UNKNOWN_KEY,
BAD_SIGNATURE,
MALFORMED_STATEMENT,
ADDRESS_MISMATCH,
LOAN_MISMATCH,
CODE_MISMATCH
}
/** Either the verification code to show beside the address, or why the address must not be shown. */
public record Check(boolean ok, String verificationCode, Reason reason) {}
private BorrouAddresses() {}
/** The statement's fields, or null for anything Borrou would not sign. */
public static Map readStatement(String statement) {
String[] lines = statement.split("\n", -1);
if (lines.length != FIELDS.length) return null;
Map fields = new LinkedHashMap<>();
for (int i = 0; i < lines.length; i++) {
int eq = lines[i].indexOf('=');
if (eq < 0 || !lines[i].substring(0, eq).equals(FIELDS[i])) return null;
String value = lines[i].substring(eq + 1);
// Every value is printable ASCII with no spaces: a CR, a space or anything else is not Borrou's.
if (!VALUE.matcher(value).matches()) return null;
fields.put(FIELDS[i], value);
}
if (!"BORROU_COLLATERAL_ADDRESS_V1".equals(fields.get("purpose")) || !"BTC".equals(fields.get("asset")) || !"bitcoin".equals(fields.get("network"))) {
return null;
}
return fields;
}
/** The first eight base32 characters of SHA-256(signature bytes), as XXXX-XXXX. */
public static String verificationCode(String signature) throws GeneralSecurityException {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(Base64.getUrlDecoder().decode(signature));
StringBuilder code = new StringBuilder();
int buffer = 0;
int bits = 0;
for (byte b : digest) {
buffer = (buffer << 8) | (b & 0xff);
bits += 8;
while (bits >= 5 && code.length() < 8) {
code.append(BASE32.charAt((buffer >>> (bits - 5)) & 31));
bits -= 5;
}
buffer &= (1 << bits) - 1;
if (code.length() == 8) break;
}
return code.substring(0, 4) + "-" + code.substring(4);
}
/** The key from its {@code public_key_pem}: an SPKI PEM, which the JDK reads as X.509. */
public static PublicKey publicKey(String pem) throws GeneralSecurityException {
String body = pem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
return KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(body)));
}
/**
* @param shownAddress the address your app is about to show
* @param shownLoanReference the loan it is for
* @param attestation the response's {@code address_attestation}
* @param keys {@code keys} from GET /v1/address-keys
*/
public static Check verify(String shownAddress, String shownLoanReference, Map attestation, List