use of com.amazon.ion.IonReader in project amazon-qldb-dmv-sample-java by aws-samples.
the class GetRevision method verifyRegistration.
/**
* Verify each version of the registration for the given VIN.
*
* @param driver
* A QLDB driver.
* @param ledgerName
* The ledger to get digest from.
* @param vin
* VIN to query the revision history of a specific registration with.
* @throws Exception if failed to verify digests.
* @throws AssertionError if document revision verification failed.
*/
public static void verifyRegistration(final QldbDriver driver, final String ledgerName, final String vin) throws Exception {
log.info(String.format("Let's verify the registration with VIN=%s, in ledger=%s.", vin, ledgerName));
try {
log.info("First, let's get a digest.");
GetDigestResult digestResult = GetDigest.getDigest(ledgerName);
ValueHolder digestTipAddress = digestResult.getDigestTipAddress();
byte[] digestBytes = Verifier.convertByteBufferToByteArray(digestResult.getDigest());
log.info("Got a ledger digest. Digest end address={}, digest={}.", QldbStringUtils.toUnredactedString(digestTipAddress), Verifier.toBase64(digestBytes));
log.info(String.format("Next, let's query the registration with VIN=%s. " + "Then we can verify each version of the registration.", vin));
List<IonStruct> documentsWithMetadataList = new ArrayList<>();
driver.execute(txn -> {
documentsWithMetadataList.addAll(queryRegistrationsByVin(txn, vin));
});
log.info("Registrations queried successfully!");
log.info(String.format("Found %s revisions of the registration with VIN=%s.", documentsWithMetadataList.size(), vin));
for (IonStruct ionStruct : documentsWithMetadataList) {
QldbRevision document = QldbRevision.fromIon(ionStruct);
log.info(String.format("Let's verify the document: %s", document));
log.info("Let's get a proof for the document.");
GetRevisionResult proofResult = getRevision(ledgerName, document.getMetadata().getId(), digestTipAddress, document.getBlockAddress());
final IonValue proof = Constants.MAPPER.writeValueAsIonValue(proofResult.getProof());
final IonReader reader = IonReaderBuilder.standard().build(proof);
reader.next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IonWriter writer = SYSTEM.newBinaryWriter(baos);
writer.writeValue(reader);
writer.close();
baos.flush();
baos.close();
byte[] byteProof = baos.toByteArray();
log.info(String.format("Got back a proof: %s", Verifier.toBase64(byteProof)));
boolean verified = Verifier.verify(document.getHash(), digestBytes, proofResult.getProof().getIonText());
if (!verified) {
throw new AssertionError("Document revision is not verified!");
} else {
log.info("Success! The document is verified");
}
byte[] alteredDigest = Verifier.flipRandomBit(digestBytes);
log.info(String.format("Flipping one bit in the digest and assert that the document is NOT verified. " + "The altered digest is: %s", Verifier.toBase64(alteredDigest)));
verified = Verifier.verify(document.getHash(), alteredDigest, proofResult.getProof().getIonText());
if (verified) {
throw new AssertionError("Expected document to not be verified against altered digest.");
} else {
log.info("Success! As expected flipping a bit in the digest causes verification to fail.");
}
byte[] alteredDocumentHash = Verifier.flipRandomBit(document.getHash());
log.info(String.format("Flipping one bit in the document's hash and assert that it is NOT verified. " + "The altered document hash is: %s.", Verifier.toBase64(alteredDocumentHash)));
verified = Verifier.verify(alteredDocumentHash, digestBytes, proofResult.getProof().getIonText());
if (verified) {
throw new AssertionError("Expected altered document hash to not be verified against digest.");
} else {
log.info("Success! As expected flipping a bit in the document hash causes verification to fail.");
}
}
} catch (Exception e) {
log.error("Failed to verify digests.", e);
throw e;
}
log.info(String.format("Finished verifying the registration with VIN=%s in ledger=%s.", vin, ledgerName));
}
use of com.amazon.ion.IonReader in project amazon-qldb-dmv-sample-java by aws-samples.
the class JournalS3ExportReader method getDataFileKeysFromManifest.
/**
* Given the S3Object to the completed manifest file, return the keys
* which are part of this export request.
*
* @param s3Object
* A {@link S3Object}.
* @return a list of data file keys containing the chunk of {@link JournalBlock}.
*/
private static List<String> getDataFileKeysFromManifest(final S3Object s3Object) {
IonReader ionReader = IonReaderBuilder.standard().build(s3Object.getObjectContent());
// Read the data
ionReader.next();
List<String> keys = new ArrayList<>();
IonStruct ionStruct = (IonStruct) SYSTEM.newValue(ionReader);
IonList ionKeysList = (IonList) ionStruct.get("keys");
ionKeysList.forEach(key -> keys.add(((IonString) key).stringValue()));
return keys;
}
use of com.amazon.ion.IonReader in project amazon-qldb-dmv-sample-java by aws-samples.
the class TransferVehicleOwnership method findPrimaryOwnerForVehicle.
/**
* Find the primary owner for the given VIN.
*
* @param txn
* The {@link TransactionExecutor} for lambda execute.
* @param vin
* Unique VIN for a vehicle.
* @return a {@link Person} object.
* @throws IllegalStateException if failed to convert parameter into {@link IonValue}.
*/
public static Person findPrimaryOwnerForVehicle(final TransactionExecutor txn, final String vin) {
try {
log.info("Finding primary owner for vehicle with Vin: {}...", vin);
final String query = "SELECT Owners.PrimaryOwner.PersonId FROM VehicleRegistration AS v WHERE v.VIN = ?";
final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(vin));
Result result = txn.execute(query, parameters);
final List<IonStruct> documents = ScanTable.toIonStructs(result);
ScanTable.printDocuments(documents);
if (documents.isEmpty()) {
throw new IllegalStateException("Unable to find registrations with VIN: " + vin);
}
final IonReader reader = IonReaderBuilder.standard().build(documents.get(0));
final String personId = Constants.MAPPER.readValue(reader, LinkedHashMap.class).get("PersonId").toString();
return findPersonFromDocumentId(txn, personId);
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
use of com.amazon.ion.IonReader in project amazon-qldb-dmv-sample-java by aws-samples.
the class Proof method fromBlob.
/**
* Decodes a {@link Proof} from an ion text String. This ion text is returned in
* a {@link GetRevisionResult#getProof()}
*
* @param ionText
* The ion text representing a {@link Proof} object.
* @return {@link JournalBlock} parsed from the ion text.
* @throws IllegalStateException if failed to parse the {@link Proof} object from the given ion text.
*/
public static Proof fromBlob(final String ionText) {
try {
IonReader reader = SYSTEM.newReader(ionText);
List<byte[]> list = new ArrayList<>();
reader.next();
reader.stepIn();
while (reader.next() != null) {
list.add(reader.newBytes());
}
return new Proof(list);
} catch (Exception e) {
throw new IllegalStateException("Failed to parse a Proof from byte array");
}
}
use of com.amazon.ion.IonReader in project amazon-qldb-dmv-sample-java by aws-samples.
the class QldbIonUtils method hashIonValue.
/**
* Builds a hash value from the given {@link IonValue}.
*
* @param ionValue
* The {@link IonValue} to hash.
* @return a byte array representing the hash value.
*/
public static byte[] hashIonValue(final IonValue ionValue) {
IonReader reader = Constants.SYSTEM.newReader(ionValue);
IonHashReader hashReader = IonHashReaderBuilder.standard().withHasherProvider(ionHasherProvider).withReader(reader).build();
while (hashReader.next() != null) {
}
return hashReader.digest();
}
Aggregations