use of com.amazon.ion.IonWriter 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.IonWriter in project amazon-qldb-dmv-sample-java by aws-samples.
the class QldbStringUtils method toUnredactedString.
/**
* Returns the string representation of a given {@link ValueHolder}.
* Adapted from the AWS SDK autogenerated {@code toString()} method, with sensitive values un-redacted.
* Additionally, this method pretty-prints any IonText included in the {@link ValueHolder}.
*
* @param valueHolder the {@link ValueHolder} to convert to a String.
* @return the String representation of the supplied {@link ValueHolder}.
*/
public static String toUnredactedString(ValueHolder valueHolder) {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (valueHolder.getIonText() != null) {
sb.append("IonText: ");
IonWriter prettyWriter = IonTextWriterBuilder.pretty().build(sb);
try {
prettyWriter.writeValues(IonReaderBuilder.standard().build(valueHolder.getIonText()));
} catch (IOException ioe) {
sb.append("**Exception while printing this IonText**");
}
}
sb.append("}");
return sb.toString();
}
use of com.amazon.ion.IonWriter in project ion-java by amzn.
the class BinaryWriterTest method testNoIVMWrittenWhenNoValuesWritten.
@Test
public void testNoIVMWrittenWhenNoValuesWritten() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
IonWriter writer = system().newBinaryWriter(out);
writer.close();
// no IVM written
assertEquals(0, out.size());
}
use of com.amazon.ion.IonWriter in project ion-java by amzn.
the class IonJavaCli method embeddedEventToIon.
private static int embeddedEventToIon(ProcessContext processContext, CommandArgs args, int count, IonType ionType) throws IOException {
processContext.getIonWriter().addTypeAnnotation(EMBEDDED_STREAM_ANNOTATION);
processContext.getIonWriter().stepIn(ionType);
List<Event> events = processContext.getEventStream();
int depth = 1;
boolean finish = false;
while (++count < events.size()) {
StringBuilder out = new StringBuilder();
ProcessContext embeddedContext = new ProcessContext(null, 0, null, null, ION_TEXT_WRITER_BUILDER.withImports(_Private_Utils.systemSymtab(1)).build(out));
embeddedContext.setEmbeddedOut(out);
try {
do {
Event event = events.get(count);
processContext.setEventIndex(processContext.getEventIndex() + 1);
processContext.setLastEventType(event.getEventType());
if (event.getEventType() == EventType.STREAM_END) {
break;
} else if (event.getEventType() == EventType.SCALAR) {
writeIonByType(event, embeddedContext.getIonWriter());
} else if (event.getEventType() == EventType.CONTAINER_START) {
depth++;
setFieldName(event, embeddedContext.getIonWriter());
setAnnotations(event, embeddedContext.getIonWriter());
embeddedContext.getIonWriter().stepIn(event.getIonType());
} else if (event.getEventType() == EventType.CONTAINER_END) {
depth--;
if (depth == 0) {
if (event.getIonType() == IonType.SEXP || event.getIonType() == IonType.LIST) {
finish = true;
break;
} else {
throw new IonException("invalid CONTAINER_END");
}
}
embeddedContext.getIonWriter().stepOut();
} else if (event.getEventType() == EventType.SYMBOL_TABLE) {
handleSymbolTableEvent(embeddedContext, event, args, true);
}
} while (++count < events.size());
if (!finish) {
embeddedContext.getIonWriter().finish();
processContext.getIonWriter().writeString(out.toString());
}
} finally {
IonWriter ionWriter = embeddedContext.getIonWriter();
if (ionWriter != null) {
try {
ionWriter.close();
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(IO_ERROR_EXIT_CODE);
}
}
}
if (finish) {
break;
}
}
processContext.getIonWriter().stepOut();
return count;
}
use of com.amazon.ion.IonWriter in project ion-java by amzn.
the class IonJavaCli method main.
public static void main(final String[] args) {
CommandArgs parsedArgs = new CommandArgs();
CmdLineParser parser = new CmdLineParser(parsedArgs);
parser.getProperties().withUsageWidth(CONSOLE_WIDTH);
ComparisonType comparisonType = null;
OutputFormat outputFormat = null;
CommandType commandType = null;
try {
// parse
parser.parseArgument(args);
validateArgs(parsedArgs);
// get value
comparisonType = parsedArgs.getComparisonType();
outputFormat = parsedArgs.getOutputFormat();
commandType = parsedArgs.getCommand();
} catch (CmdLineException | IllegalArgumentException e) {
printHelpText(e.getMessage(), parser, parsedArgs);
System.exit(USAGE_ERROR_EXIT_CODE);
}
if (commandType == CommandType.VERSION) {
System.err.println(VERSION);
System.exit(0);
}
ProcessContext processContext = commandType == CommandType.PROCESS ? new ProcessContext(null, -1, null, ErrorType.READ, null) : null;
try (// Initialize output stream, never return null. (default value: STDOUT)
OutputStream outputStream = initOutputStream(parsedArgs, SYSTEM_OUT_DEFAULT_VALUE, processContext);
// Initialize error report, never return null. (default value: STDERR)
OutputStream errorReportOutputStream = initOutputStream(parsedArgs, SYSTEM_ERR_DEFAULT_VALUE, processContext);
IonWriter ionWriterForErrorReport = outputFormat.createIonWriter(errorReportOutputStream);
IonWriter ionWriterForOutput = outputFormat.createIonWriter(outputStream)) {
if (commandType == CommandType.COMPARE) {
compareFiles(ionWriterForOutput, ionWriterForErrorReport, parsedArgs, comparisonType);
} else if (commandType == CommandType.PROCESS) {
processContext.setIonWriter(ionWriterForOutput);
processFiles(ionWriterForErrorReport, parsedArgs, processContext);
}
} catch (IOException e) {
System.err.println("Failed to close OutputStream: " + e.getMessage());
} finally {
if (processContext != null) {
IonWriter ionWriter = processContext.getIonWriter();
if (ionWriter != null) {
try {
ionWriter.close();
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(IO_ERROR_EXIT_CODE);
}
}
}
}
}
Aggregations