Compare commits

...
8 Commits
7 changed files with 1236 additions and 128 deletions
+3
View File
@@ -218,6 +218,7 @@
<Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
@@ -246,7 +247,9 @@
<Compile Include="BaseConfigParser.cs" />
<Compile Include="Client.cs" />
<Compile Include="ClientApp.cs" />
<Compile Include="TransactionStreaming.cs" />
<Compile Include="ConfigFileParser.cs" />
<Compile Include="ErrorLogger.cs" />
<Compile Include="ExtraParameter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
+55 -38
View File
@@ -5,6 +5,7 @@ using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
namespace Creditcall.ChipDna.Client
{
@@ -24,6 +25,8 @@ namespace Creditcall.ChipDna.Client
public TaskCompletionSource<Dictionary<string, string>> TransactionCompletionSource { get; set; }
internal readonly TransactionProgressTap Progress = new TransactionProgressTap();
private volatile bool voiceReferralRequired;
private volatile bool voiceReferralDone;
private readonly bool saveReceipt;
@@ -249,7 +252,6 @@ namespace Creditcall.ChipDna.Client
{
{ ParameterKeys.Errors, errors },
{ ParameterKeys.Reference, reference },
{ ParameterKeys.TransactionResult, "ERROR" }
};
if (TransactionCompletionSource != null && !TransactionCompletionSource.Task.IsCompleted)
@@ -318,13 +320,13 @@ namespace Creditcall.ChipDna.Client
PerformStartTransaction("250", "");
break;
case "C":
PerformConfirmTransaction("", out TransactionConfirmation confirmation);
PerformConfirmTransaction("", "");
break;
case "V":
PerformVoidTransaction();
PerformVoidTransaction("");
break;
case "I":
PerformGetTransactionInformation();
PerformGetTransactionInformation("");
break;
case "K":
PerformReleaseCard();
@@ -471,14 +473,14 @@ namespace Creditcall.ChipDna.Client
}
}
private void GetStatus()
public Dictionary<string, string> GetStatus()
{
Console.WriteLine(ParameterKeys.VersionInformation + "\n" + ParameterKeys.ChipDnaStatus + "\n" + ParameterKeys.PaymentDeviceStatus + "\n" + ParameterKeys.RequestQueueStatus + "\n" + ParameterKeys.TmsStatus + "\n" + ParameterKeys.PaymentPlatformStatus);
var transactionResult = new Dictionary<string, string>();
var parameterSet = new ParameterSet();
var responseParameter = new List<Parameter>();
parameterSet.Add(GetExtraParams("GetStatus"));
Response response = chipDnaClientLib.GetStatus(GetRequestedParameterSet(parameterSet));
Response response = chipDnaClientLib.GetStatus(parameterSet);
string errors;
var serverStatus = (ChipDnaStatus) null;
@@ -495,6 +497,13 @@ namespace Creditcall.ChipDna.Client
{
Console.WriteLine(serverStatus);
}
responseParameter = response.ToList();
responseParameter.ForEach(parameter =>
{
transactionResult.Add(parameter.Key, parameter.Value);
});
return transactionResult;
}
private void GetMerchantData()
@@ -635,19 +644,23 @@ namespace Creditcall.ChipDna.Client
}
}
public void PerformConfirmTransaction(string reference, out TransactionConfirmation confirmation)
public Dictionary<string, string> PerformConfirmTransaction(string reference, string amount)
{
confirmation = new TransactionConfirmation();
var confirmationResult = new Dictionary<string, string>();
var parameters = new ParameterSet();
parameters.Add(ParameterKeys.Reference, reference);
parameters.Add(ParameterKeys.Amount, amount);
parameters.Add(GetExtraParams("ConfirmTransaction"));
var response = chipDnaClientLib.ConfirmTransaction(parameters);
var responseParameter = response.ToList();
responseParameter.ForEach(parameter =>
{
confirmationResult.Add(parameter.Key, parameter.Value);
});
string receipt, result;
if (response.GetValue(ParameterKeys.TransactionResult, out result))
{
Console.WriteLine("Confirmed Transaction Result: {0}", result);
confirmation.Result = result;
}
if (response.GetValue(ParameterKeys.ReceiptDataMerchant, out receipt))
{
@@ -656,21 +669,19 @@ namespace Creditcall.ChipDna.Client
if (response.GetValue(ParameterKeys.ReceiptDataCardholder, out receipt))
{
PrintReceiptData(ReceiptData.GetReceiptDataFromXml(receipt));
confirmation.ReceiptDataCardholder = receipt;
}
string errors;
if (response.GetValue(ParameterKeys.Errors, out errors))
{
Console.WriteLine(ErrorsString("ConfirmTransaction Errors", errors));
confirmation.Errors = errors;
}
string errorDescription;
if (response.GetValue(ParameterKeys.ErrorDescription, out errorDescription))
{
Console.WriteLine("ErrorDescription: {0}", errorDescription);
confirmation.ErrorDescription = errorDescription;
}
return confirmationResult;
}
private void DoUpdateTransaction()
@@ -739,18 +750,13 @@ namespace Creditcall.ChipDna.Client
}
}
private void PerformVoidTransaction()
public Dictionary<string, string> PerformVoidTransaction(string referenceValue)
{
var reference = GetReference(true, "");
var voidReason = GetUserInput("\r\nPlease Enter Void Reason (Optional)");
var transactionResult = new Dictionary<string, string>();
var parameters = new ParameterSet();
if (!string.IsNullOrEmpty(reference))
if (!string.IsNullOrEmpty(referenceValue))
{
parameters.Add(ParameterKeys.Reference, reference);
}
if (!String.IsNullOrEmpty(voidReason))
{
parameters.Add(ParameterKeys.VoidReason, voidReason);
parameters.Add(ParameterKeys.Reference, referenceValue);
}
parameters.Add(GetExtraParams("VoidTransaction"));
@@ -778,12 +784,18 @@ namespace Creditcall.ChipDna.Client
{
Console.WriteLine("ErrorDescription: {0}", errorDescription);
}
var responseParameter = response.ToList();
responseParameter.ForEach(parameter =>
{
transactionResult.Add(parameter.Key, parameter.Value);
});
return transactionResult;
}
private void PerformGetTransactionInformation()
public Dictionary<string, string> PerformGetTransactionInformation(string referenceValue)
{
var referenceValue = GetReference(true, "");
var result = new Dictionary<string, string>();
var parameters = new ParameterSet();
if (!string.IsNullOrEmpty(referenceValue))
{
@@ -794,18 +806,11 @@ namespace Creditcall.ChipDna.Client
var response = chipDnaClientLib.GetTransactionInformation(parameters);
var responseParameter = response.ToList();
responseParameter.ForEach(parameter =>
{
if (parameter.Key == ParameterKeys.Errors)
{
Console.WriteLine(ErrorsString("GetTransactionInformation Errors", parameter.Value));
}
else
{
Console.WriteLine("{0} {1}", parameter.Key, parameter.Value);
}
});
result.Add(parameter.Key, parameter.Value);
});
return result;
}
private static string GetUserInput(string prompt)
@@ -1368,6 +1373,7 @@ namespace Creditcall.ChipDna.Client
private void ChipDnaClientLibOnSignatureVerificationRequested(object sender, EventParameters signatureVerificationRequestedEventArgs)
{
Progress.Report("SIGNATURE", signatureVerificationRequestedEventArgs);
var transactionFinishedStringBuilder = new StringBuilder();
transactionFinishedStringBuilder.Append("Signature Verification Requested Event Parameters: ");
string reference = null;
@@ -1423,17 +1429,20 @@ namespace Creditcall.ChipDna.Client
private void ChipDnaClientLibOnTransactionPause(object sender, EventParameters transactionPauseEventArgs)
{
Progress.Report("PAUSE", transactionPauseEventArgs);
Console.WriteLine("Transaction Pause Event Parameters: {0}{1} *Waiting For Continue Command --> Press 'L' To Continue*",
transactionPauseEventArgs, "\n");
}
private void ChipDnaClientLibOnTransactionUpdate(object sender, EventParameters transactionUpdateEventArgs)
{
Progress.Report("UPDATE", transactionUpdateEventArgs);
Console.WriteLine("Transaction Update Event Parameters: {0}", transactionUpdateEventArgs);
}
private void ChipDnaClientLibOnCardNotification(object sender, EventParameters cardNotificationEventArgs)
{
Progress.Report("CARD_STATUS", cardNotificationEventArgs);
Console.WriteLine("Card Notification Event Parameters: {0}", cardNotificationEventArgs);
}
@@ -1458,6 +1467,7 @@ namespace Creditcall.ChipDna.Client
private void ChipDnaClientLibOnPaymentDeviceAvailabilityChangeEvent(object sender, EventParameters connectionEventArgs)
{
var transactionResult = new Dictionary<string, string>();
var stringBuilder = new StringBuilder();
connectionEventArgs.ToList().ForEach(param =>
{
@@ -1474,8 +1484,10 @@ namespace Creditcall.ChipDna.Client
else
{
stringBuilder.Append(string.Format("[{0}]", param.ToString()));
}
}
transactionResult.Add(param.Key, param.Value);
});
_ = ErrorLogger.SendLogErrorAsync(transactionResult);
Console.WriteLine("{0}: {1}", "Payment Device Availability Change Event", stringBuilder);
}
@@ -1501,6 +1513,11 @@ namespace Creditcall.ChipDna.Client
private void ChipDnaClientLibOnErrorEvent(object sender, ClientHelperErrorEventArgs errorEventArgs)
{
var result = new Dictionary<string, string>
{
{ ParameterKeys.Errors, errorEventArgs.RaisedException.Message}
};
_ = ErrorLogger.SendLogErrorAsync(result);
PrintErrorEvent(errorEventArgs.RaisedException);
}
+207 -90
View File
@@ -19,6 +19,7 @@ namespace Creditcall.ChipDna.Client
private const int DefaultPort = 1869;
private const string DefaultIpAddress = "127.0.0.1";
private const bool DefaultSaveReceipt = false;
private const int transactionTimeoutSeconds = 300;
private static Client client;
@@ -71,11 +72,21 @@ namespace Creditcall.ChipDna.Client
private static void StartHttpServer()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1:18181/start-transaction-stream/");
listener.Prefixes.Add("http://127.0.0.1:18181/start-transaction/");
listener.Prefixes.Add("http://127.0.0.1:18181/confirm-transaction/");
listener.Prefixes.Add("http://127.0.0.1:18181/transaction-information/");
listener.Prefixes.Add("http://127.0.0.1:18181/void-transaction/");
listener.Prefixes.Add("http://127.0.0.1:18181/chipdna-status/");
listener.Start();
Console.WriteLine("Listening on:");
Console.WriteLine(" http://127.0.0.1:18181/start-transaction-stream/");
Console.WriteLine(" http://127.0.0.1:18181/start-transaction/");
Console.WriteLine(" http://127.0.0.1:18181/confirm-transaction/");
Console.WriteLine(" http://127.0.0.1:18181/transaction-information/");
Console.WriteLine(" http://127.0.0.1:18181/void-transaction/");
Console.WriteLine(" http://127.0.0.1:18181/chipdna-status/");
while (true)
{
@@ -92,10 +103,30 @@ namespace Creditcall.ChipDna.Client
continue;
}
if (rawUrl.StartsWith("/start-transaction", StringComparison.OrdinalIgnoreCase))
if (rawUrl.StartsWith("/start-transaction-stream", StringComparison.OrdinalIgnoreCase))
{
HandleStartTransactionStream(context);
}
else if (rawUrl.StartsWith("/start-transaction", StringComparison.OrdinalIgnoreCase))
{
HandleStartTransaction(context);
} else if (rawUrl.StartsWith("/confirm-transaction", StringComparison.OrdinalIgnoreCase))
{
HandleConfirmTransaction(context);
}
else if (rawUrl.StartsWith("/transaction-information", StringComparison.OrdinalIgnoreCase))
{
HandleTransactionInformation(context);
}
else if (rawUrl.StartsWith("/void-transaction", StringComparison.OrdinalIgnoreCase))
{
HandleVoidTransaction(context);
}
else if (rawUrl.StartsWith("/chipdna-status", StringComparison.OrdinalIgnoreCase))
{
HandleGetStatus(context);
}
else
{
context.Response.StatusCode = 404;
@@ -115,98 +146,125 @@ namespace Creditcall.ChipDna.Client
}
}
private static void HandleGetStatus(HttpListenerContext context)
{
try
{
var statusResult = client.GetStatus();
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(statusResult);
responseSerializer.Serialize(context.Response.OutputStream, wrappedResult);
}
catch (Exception ex)
{
Console.WriteLine("Error in -status: " + ex.Message);
context.Response.StatusCode = 500;
}
finally
{
context.Response.OutputStream.Close();
}
}
private static void HandleTransactionInformation(HttpListenerContext context)
{
try
{
var serializer = new XmlSerializer(typeof(TransactionReferenceRequest));
TransactionReferenceRequest req = (TransactionReferenceRequest)serializer.Deserialize(context.Request.InputStream);
var transactionResult = client.PerformGetTransactionInformation(req.TransactionReference);
// Return the final key/value list
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(transactionResult);
responseSerializer.Serialize(context.Response.OutputStream, wrappedResult);
}
catch (Exception ex)
{
Console.WriteLine("Error in transaction-information: " + ex.Message);
context.Response.StatusCode = 500;
}
finally
{
context.Response.OutputStream.Close();
}
}
private static void HandleVoidTransaction(HttpListenerContext context)
{
try
{
var serializer = new XmlSerializer(typeof(TransactionReferenceRequest));
TransactionReferenceRequest req = (TransactionReferenceRequest)serializer.Deserialize(context.Request.InputStream);
var transactionResult = client.PerformVoidTransaction(req.TransactionReference);
// Return the final key/value list
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(transactionResult);
responseSerializer.Serialize(context.Response.OutputStream, wrappedResult);
}
catch (Exception ex)
{
Console.WriteLine("Error in transaction-information: " + ex.Message);
context.Response.StatusCode = 500;
}
finally
{
context.Response.OutputStream.Close();
}
}
private static void HandleConfirmTransaction(HttpListenerContext context)
{
try
{
var serializer = new XmlSerializer(typeof(ConfirmTransactionRequest));
ConfirmTransactionRequest payload = (ConfirmTransactionRequest)serializer.Deserialize(context.Request.InputStream);
Console.WriteLine($"Received confirm transaction: Amount={payload.Amount}, TransactionReference={payload.TransactionReference}");
var confirmationResult = client.PerformConfirmTransaction(payload.TransactionReference, payload.Amount);
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(confirmationResult);
responseSerializer.Serialize(context.Response.OutputStream, wrappedResult);
}
catch (Exception ex)
{
var errorMap = new Dictionary<string, string>
{
{ ParameterKeys.TransactionResult, "ERROR" },
{ ParameterKeys.Errors, $"ConfirmTransaction failed: {ex.Message}" }
};
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(errorMap);
responseSerializer.Serialize(context.Response.OutputStream, wrappedResult);
}
finally
{
context.Response.OutputStream.Close();
}
}
private static void HandleStartTransaction(HttpListenerContext context)
{
const int transactionTimeoutSeconds = 300;
try
{
var serializer = new XmlSerializer(typeof(TransactionPayload));
TransactionPayload payload = (TransactionPayload)serializer.Deserialize(context.Request.InputStream);
Console.WriteLine($"Received start transaction: Amount={payload.amount}, Type={payload.transactionType}");
Console.WriteLine($"Received transaction request: Amount={payload.Amount}, Type={payload.TransactionType}");
client.TransactionCompletionSource = new TaskCompletionSource<Dictionary<string, string>>();
var transactionResult = ExecuteTransaction(payload);
// start transaction (non-blocking)
client.PerformStartTransaction(payload.amount, payload.transactionType);
// Wait for completion with timeout
var task = client.TransactionCompletionSource.Task;
if (!task.Wait(TimeSpan.FromSeconds(transactionTimeoutSeconds)))
{
// timeout
var errorMap = new Dictionary<string, string>
{
{ ParameterKeys.TransactionResult, "TIMEOUT" },
{ ParameterKeys.Errors, "Transaction timed out waiting for device response" }
};
var wrappedTimeout = new SerializableKeyValueList(errorMap);
context.Response.ContentType = "application/xml";
new XmlSerializer(typeof(SerializableKeyValueList)).Serialize(context.Response.OutputStream, wrappedTimeout);
return;
}
// Task completed — handle possible exception
Dictionary<string, string> transactionResult;
try
{
transactionResult = task.Result; // safe now, Wait returned
}
catch (AggregateException agg)
{
var first = agg.Flatten().InnerExceptions[0];
var errMap = new Dictionary<string, string>
{
{ ParameterKeys.TransactionResult, "ERROR" },
{ ParameterKeys.Errors, $"Transaction task faulted: {first.Message}" }
};
var wrapped = new SerializableKeyValueList(errMap);
context.Response.ContentType = "application/xml";
new XmlSerializer(typeof(SerializableKeyValueList)).Serialize(context.Response.OutputStream, wrapped);
return;
}
// If it's a SALE and approved, call ConfirmTransaction and attach its XML
transactionResult.TryGetValue(ParameterKeys.TransactionType, out string txType);
transactionResult.TryGetValue(ParameterKeys.TransactionResult, out string txResult);
transactionResult.TryGetValue(ParameterKeys.Reference, out string txReference);
if (!string.IsNullOrEmpty(txType) && txType.Equals("SALE", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(txResult) && txResult.Equals("APPROVED", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(txReference))
{
try
{
TransactionConfirmation confirmation;
client.PerformConfirmTransaction(txReference, out confirmation);
// Keep original fields, but also add confirmation-prefixed fields
transactionResult["CONFIRM_RESULT"] = confirmation?.Result ?? "";
transactionResult["CONFIRM_ERRORS"] = confirmation?.Errors ?? "";
if (!string.IsNullOrEmpty(confirmation.ErrorDescription))
{
transactionResult["CONFIRM_ERRORS"] = $"{confirmation.Errors} {confirmation.ErrorDescription}";
}
if (!string.IsNullOrEmpty(confirmation?.ReceiptDataCardholder))
{
transactionResult[ParameterKeys.ReceiptDataCardholder] = confirmation.ReceiptDataCardholder;
}
// XML (omit declaration so it can be embedded)
var xml = SerializeToXml(confirmation, omitXmlDeclaration: true);
transactionResult["TRANSACTION_CONFIRMATION"] = xml;
}
catch (Exception ex)
{
// preserve original transaction result but add an error key
transactionResult["CONFIRM_RESULT"] = "ERROR";
transactionResult["CONFIRM_ERRORS"] = $"ConfirmTransaction failed: {ex.Message}";
}
}
// Return the final key/value list as before
var responseSerializer = new XmlSerializer(typeof(SerializableKeyValueList));
context.Response.ContentType = "application/xml";
var wrappedResult = new SerializableKeyValueList(transactionResult);
@@ -221,6 +279,54 @@ namespace Creditcall.ChipDna.Client
{
context.Response.OutputStream.Close();
}
}
private static Dictionary<string, string> ExecuteTransaction(TransactionPayload payload)
{
client.TransactionCompletionSource = new TaskCompletionSource<Dictionary<string, string>>();
return TransactionExecution.Run(
() => client.PerformStartTransaction(payload.Amount, payload.TransactionType),
() => client.TransactionCompletionSource.Task,
TimeSpan.FromSeconds(transactionTimeoutSeconds));
}
private static void HandleStartTransactionStream(HttpListenerContext context)
{
context.Response.ContentType = "application/x-ndjson; charset=utf-8";
context.Response.SendChunked = true;
var writer = new TransactionStreamWriter(context.Response.OutputStream);
var delivery = Task.Run(() => writer.Deliver());
Action<string, string> progress = writer.Progress;
try
{
TransactionPayload payload;
using (var reader = new StreamReader(context.Request.InputStream))
using (var json = new Newtonsoft.Json.JsonTextReader(reader))
{
payload = new Newtonsoft.Json.JsonSerializer().Deserialize<TransactionPayload>(json);
}
if (payload == null)
throw new InvalidDataException("Missing transaction payload");
var result = client.Progress.Observe(progress, () => ExecuteTransaction(payload));
writer.Complete(new { type = "result", result = TransactionStreamFields.Required(result) });
}
catch (Exception)
{
writer.Complete(new { type = "error", error = "Transaction stream failed" });
}
finally
{
// Retain serial response completion, as with the XML endpoint.
// Hardlink's existing per-call timeout bounds its connection;
// no new delivery timer may truncate an approved final result.
try { delivery.GetAwaiter().GetResult(); }
finally
{
try { context.Response.Close(); } catch (HttpListenerException) { }
}
}
}
private static string GetAbsolutePath(string fileName)
@@ -308,11 +414,8 @@ namespace Creditcall.ChipDna.Client
[XmlRoot("TransactionPayload")]
public class TransactionPayload
{
public string amount { get; set; }
public string transactionType { get; set; }
// For confirm transaction
public string transactionReference { get; set; }
public string Amount { get; set; }
public string TransactionType { get; set; }
}
[XmlRoot("TransactionConfirmation")]
@@ -322,6 +425,20 @@ namespace Creditcall.ChipDna.Client
public string Errors { get; set; }
public string ErrorDescription { get; set; }
public string ReceiptDataCardholder { get; set; }
}
[XmlRoot("TransactionReferenceRequest")]
public class TransactionReferenceRequest
{
[XmlElement("TransactionReference")]
public string TransactionReference { get; set; }
}
[XmlRoot("ConfirmTransactionRequest")]
public class ConfirmTransactionRequest
{
public string Amount { get; set; }
public string TransactionReference { get; set; }
}
}
+61
View File
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace Creditcall.ChipDna.Client
{
public static class ErrorLogger
{
private static readonly HttpClient httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(10)
};
public static async Task SendLogErrorAsync(Dictionary<string, string> statusResult)
{
try
{
if (statusResult == null || statusResult.Count == 0)
return;
var url = "http://127.0.0.1:9091/logerror";
var wrappedResult = new SerializableKeyValueList(statusResult);
var serializer = new XmlSerializer(typeof(SerializableKeyValueList));
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = false,
Indent = false,
Encoding = new UTF8Encoding(false)
};
using (var ms = new MemoryStream())
{
using (var xw = XmlWriter.Create(ms, settings))
{
serializer.Serialize(xw, wrappedResult, ns);
}
var content = new ByteArrayContent(ms.ToArray());
content.Headers.ContentType =
new MediaTypeHeaderValue("application/xml");
await httpClient.PostAsync(url, content);
}
}
catch (Exception ex)
{
Console.WriteLine("SendLogErrorAsync failed: " + ex.Message);
}
}
}
}
+678
View File
@@ -0,0 +1,678 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Creditcall.ChipDna.Client
{
internal static class StreamingTests
{
private static int Main()
{
var tests = new Action[] {
SharedExecutionReturnsAuthoritativeResultOnce,
TimeoutDoesNotCancelCompletion,
StartAndTaskErrorsKeepExceptionBehavior,
SubscriptionIsRemovedOnSuccessAndException,
ActiveStreamAcceptsProgressRegardlessOfReference,
RepeatedReferencesKeepSequentialStreamsFresh,
NativeMiuraSequenceKeepsFinalAuthoritative,
NativeMiuraRecoveryCyclesKeepFinalAuthoritative,
NativeNotificationUsesNotificationKey,
ActiveStreamOwnsRemovalUntilExecutionReturns,
SequentialResultsKeepProgressAndFinancialResults,
SdkErrorResultsDoNotSilenceNextStream,
ExecutionFailuresDoNotSilenceNextStream,
TimeoutDoesNotSilenceNextStream,
QueueCapacityCannotDropFinal,
ConcurrentCallbacksKeepValidLinesAndOneFinal,
DisconnectDoesNotInterruptExecution,
SlowConsumerDoesNotBlockCallbacksOrCompletion,
PreauthFieldsAreOptionalProviderValues,
FinalFieldsExcludeSensitiveParameters
};
int failed = 0;
foreach (var test in tests)
{
try { test(); Console.WriteLine("PASS " + test.Method.Name); }
catch (Exception ex) { failed++; Console.WriteLine("FAIL " + test.Method.Name + ": " + ex); }
}
Console.WriteLine($"{tests.Length - failed}/{tests.Length} tests passed");
return failed == 0 ? 0 : 1;
}
private static void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
}
private static EventParameters Native(string key, string value, string reference = null)
{
var fields = new Dictionary<string, string>();
if (key != null) fields[key] = value;
if (reference != null) fields["REFERENCE"] = reference;
// SDK event construction is internal; no ClientHelper or terminal is started.
return (EventParameters)Activator.CreateInstance(typeof(EventParameters),
BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { fields }, null);
}
private static void CheckUnsubscribed(TransactionProgressTap tap)
{
var listener = typeof(TransactionProgressTap).GetField("listener", BindingFlags.Instance | BindingFlags.NonPublic);
Check(listener.GetValue(tap) == null, "progress subscription survived execution");
}
private static void SharedExecutionReturnsAuthoritativeResultOnce()
{
foreach (var outcome in new[] { "Approved", "Declined", "Cancelled" })
{
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", outcome }, { "REFERENCE", "existing-ref" } };
var source = new TaskCompletionSource<Dictionary<string, string>>();
int starts = 0;
var result = TransactionExecution.Run(() => { starts++; source.SetResult(expected); },
() => source.Task, TimeSpan.FromSeconds(1));
Check(ReferenceEquals(expected, result) && starts == 1,
"shared execution changed result or start count for " + outcome);
}
}
private static void TimeoutDoesNotCancelCompletion()
{
var source = new TaskCompletionSource<Dictionary<string, string>>();
int starts = 0;
var result = TransactionExecution.Run(() => starts++, () => source.Task, TimeSpan.Zero);
Check(result["TRANSACTION_RESULT"] == "TIMEOUT" &&
result["ERRORS"] == "Transaction timed out waiting for device response", "timeout fields changed");
Check(starts == 1 && !source.Task.IsCompleted, "timeout cancelled or restarted the transaction");
source.SetResult(new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" } });
Check(source.Task.Result["TRANSACTION_RESULT"] == "Approved", "late SDK completion was disabled");
}
private static void StartAndTaskErrorsKeepExceptionBehavior()
{
var startError = new InvalidOperationException("start");
try
{
TransactionExecution.Run(() => { throw startError; },
() => Task.FromResult(new Dictionary<string, string>()), TimeSpan.Zero);
throw new Exception("expected original start exception");
}
catch (InvalidOperationException ex) { Check(ReferenceEquals(ex, startError), "start exception was replaced"); }
var fault = new TaskCompletionSource<Dictionary<string, string>>();
fault.SetException(new IOException("SDK fault"));
try
{
TransactionExecution.Run(() => { }, () => fault.Task, TimeSpan.FromSeconds(1));
throw new Exception("expected original Task.Wait AggregateException");
}
catch (AggregateException ex) { Check(ex.InnerException is IOException, "Task.Wait exception behavior changed"); }
}
private static void SubscriptionIsRemovedOnSuccessAndException()
{
var tap = new TransactionProgressTap();
int first = 0, second = 0;
tap.Observe((s,v) => first++, () => {
tap.Report("UPDATE", Native("UPDATE", "CardRequested", "first"));
return new Dictionary<string, string>();
});
CheckUnsubscribed(tap);
tap.Report("UPDATE", Native("UPDATE", "CardRequested", "after-first"));
try
{
tap.Observe((s,v) => second++, () => {
tap.Report("UPDATE", Native("UPDATE", "CardRequested", "second"));
throw new IOException("test");
});
}
catch (IOException) { }
tap.Report("UPDATE", Native("UPDATE", "CardRequested", "second"));
Check(first == 1 && second == 1, $"subscriptions leaked: {first}/{second}");
CheckUnsubscribed(tap);
}
private static void ActiveStreamAcceptsProgressRegardlessOfReference()
{
var tap = new TransactionProgressTap();
var delivered = new List<string>();
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted"));
tap.Observe((source, value) => delivered.Add(value), () => {
foreach (var reference in new[] { null, "", "current", "previous" })
tap.Report("UPDATE", Native("UPDATE", "CardRequested", reference));
return new Dictionary<string, string>();
});
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted"));
Check(delivered.SequenceEqual(Enumerable.Repeat("CardRequested", 4)),
"active progress was reference-filtered or delivered outside Observe");
CheckUnsubscribed(tap);
}
private static void RepeatedReferencesKeepSequentialStreamsFresh()
{
var tap = new TransactionProgressTap();
int starts = 0;
for (int i = 0; i < 100; i++)
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" }, { "REFERENCE", "same-second-reference" } };
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
var listener = (Delegate)typeof(TransactionProgressTap).GetField("listener", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tap);
Check(listener.GetInvocationList().Length == 1, "sequential transactions accumulated listeners");
tap.Report("UPDATE", Native("UPDATE", "CardRequested", "same-second-reference"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
Check(frames.Length == 3 && frames[0]["value"].Value<string>() == "CardRequested" &&
frames[1]["value"].Value<string>() == "PinEntryStarted" && ReferenceEquals(result, expected),
"repeated reference silenced progress, reused a buffer or changed the result at transaction " + i);
CheckUnsubscribed(tap);
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
}
Check(starts == 100, "sequential progress changed the transaction dispatch count");
}
private static void NativeMiuraSequenceKeepsFinalAuthoritative()
{
foreach (var outcome in new[] { "Approved", "Declined" })
using (var output = new MemoryStream())
{
var tap = new TransactionProgressTap();
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", outcome }, { "REFERENCE", "miura-ref" } };
int starts = 0;
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Inserted"));
foreach (var update in new[] { "TransactionStarted", "PinEntryStarted", "OnlineAuthRequested", "OnlineAuthCompleted" })
tap.Report("UPDATE", Native("UPDATE", update));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Removed"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
var values = frames.Take(frames.Length - 1).Select(f => f["value"].Value<string>());
Check(values.SequenceEqual(new[] { "CardRequested", "CardRequested", "Inserted", "TransactionStarted", "PinEntryStarted", "OnlineAuthRequested", "OnlineAuthCompleted" }),
"SDK 3.17 Miura sequence lost or changed normal reference-less progress");
Check(starts == 1 && ReferenceEquals(result, expected) && frames.Length == 8 &&
frames.Last()["result"]["TRANSACTION_RESULT"].Value<string>() == outcome,
"progress changed start count or authoritative " + outcome + " result");
CheckUnsubscribed(tap);
}
}
private static void NativeMiuraRecoveryCyclesKeepFinalAuthoritative()
{
foreach (var cycles in new[] { 1, 3 })
foreach (var outcome in new[] { "Approved", "Declined" })
using (var output = new MemoryStream())
{
var tap = new TransactionProgressTap();
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", outcome } };
int starts = 0;
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
for (int i = 0; i < cycles; i++)
{
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Inserted"));
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Removed"));
}
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Inserted"));
foreach (var update in new[] { "TransactionStarted", "PinEntryStarted", "OnlineAuthRequested", "OnlineAuthCompleted" })
tap.Report("UPDATE", Native("UPDATE", update));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
var expectedProgress = Enumerable.Range(0, cycles)
.SelectMany(i => new[] { "UPDATE:CardRequested", "CARD_STATUS:Inserted", "UPDATE:CardRemovalRequested" })
.Concat(new[] { "UPDATE:CardRequested", "CARD_STATUS:Inserted", "UPDATE:TransactionStarted",
"UPDATE:PinEntryStarted", "UPDATE:OnlineAuthRequested", "UPDATE:OnlineAuthCompleted" });
Check(frames.Take(frames.Length - 1).All(f => f["type"].Value<string>() == "status") &&
frames.Take(frames.Length - 1).Select(f => f["source"] + ":" + f["value"]).SequenceEqual(expectedProgress),
"Miura recovery prompts were dropped, reordered, deduplicated, or included Removed");
Check(starts == 1 && ReferenceEquals(result, expected) &&
frames.Count(f => f["type"].Value<string>() == "result") == 1 &&
frames.Last()["result"]["TRANSACTION_RESULT"].Value<string>() == outcome,
"recovery progress changed transaction execution or the authoritative final result");
CheckUnsubscribed(tap);
}
}
private static void NativeNotificationUsesNotificationKey()
{
var tap = new TransactionProgressTap();
var delivered = new List<string>();
tap.Observe((source, value) => delivered.Add(source + ":" + value), () => {
tap.Report("CARD_STATUS", Native("CARD_STATUS", "Inserted"));
foreach (var value in new[] { "Inserted", "Tapped", "Swiped" })
tap.Report("CARD_STATUS", Native("NOTIFICATION", value));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Removed", "native-key"));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Unknown"));
tap.Report("UPDATE", Native("PAN", "4761730000001133"));
tap.Report("UPDATE", null);
return new Dictionary<string, string>();
});
Check(delivered.SequenceEqual(new[] { "CARD_STATUS:Inserted", "CARD_STATUS:Tapped", "CARD_STATUS:Swiped" }),
"native NOTIFICATION extraction used CARD_STATUS, exposed card data, or changed the wire source");
}
private static void ActiveStreamOwnsRemovalUntilExecutionReturns()
{
var tap = new TransactionProgressTap();
var delivered = new List<string>();
var removals = new[] { "CardRemovalRequested", "CardRemovalEnforced" };
foreach (var removal in removals)
tap.Report("UPDATE", Native("UPDATE", removal));
tap.Observe((source, value) => delivered.Add(source + ":" + value), () => {
tap.Report("UPDATE", Native("UPDATE", "CardRequested", ""));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "previous"));
tap.Report("SIGNATURE", Native(null, null));
tap.Report("PAUSE", Native("PAUSE_STATE", "PostCardDetails"));
foreach (var removal in removals)
foreach (var reference in new[] { null, "", "current", "previous" })
{
tap.Report("UPDATE", Native("UPDATE", removal, reference));
tap.Report("CARD_STATUS", Native("NOTIFICATION", "Removed", reference));
}
return new Dictionary<string, string>();
});
foreach (var removal in removals)
tap.Report("UPDATE", Native("UPDATE", removal));
tap.Observe((source, value) => delivered.Add(source + ":" + value), () => {
// Late display-only updates are accepted by the current stream.
foreach (var removal in removals)
{
tap.Report("UPDATE", Native("UPDATE", removal));
tap.Report("UPDATE", Native("UPDATE", removal, "previous"));
}
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "previous"));
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "Approved"));
return new Dictionary<string, string>();
});
var expected = new[] { "UPDATE:CardRequested", "UPDATE:PinEntryStarted", "SIGNATURE:Requested", "PAUSE:Paused" }
.Concat(removals.SelectMany(value => Enumerable.Repeat("UPDATE:" + value, 4)))
.Concat(removals.SelectMany(value => Enumerable.Repeat("UPDATE:" + value, 2)))
.Concat(new[] { "UPDATE:PinEntryStarted", "UPDATE:CardRequested" });
Check(delivered.SequenceEqual(expected), "active-stream removal prompts were filtered, reordered or delivered after cleanup");
CheckUnsubscribed(tap);
}
private static void SequentialResultsKeepProgressAndFinancialResults()
{
foreach (var outcome in new[] { "Approved", "Declined", "Cancelled" })
{
var tap = new TransactionProgressTap();
int starts = 0;
foreach (var resultCode in new[] { outcome, "Approved" })
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> {
{ "TRANSACTION_RESULT", resultCode }, { "REFERENCE", "unchanged-reference" },
{ "TOTAL_AMOUNT", "3100" }, { "RECEIPT_DATA_CARDHOLDER", "synthetic-receipt" }
};
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "unchanged-reference"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
Check(ReferenceEquals(result, expected) && frames.Length == 3 &&
frames[0]["value"].Value<string>() == "CardRequested" &&
frames[1]["value"].Value<string>() == "PinEntryStarted" &&
JToken.DeepEquals(frames[2]["result"], JObject.FromObject(expected)),
"sequential " + outcome + " result lost progress or changed authoritative fields");
CheckUnsubscribed(tap);
}
Check(starts == 2, "sequential " + outcome + " result changed dispatch count");
}
}
private static void SdkErrorResultsDoNotSilenceNextStream()
{
foreach (var error in new[] { "ClientNotConnectedToServer", "AmountTooSmall", "MissingParameter", "NoPinPadsAvailable",
"TransactionInProgress", "ClientNotConnectedToServer,AmountTooSmall", "500005", "Unknown" })
{
var tap = new TransactionProgressTap();
int starts = 0;
foreach (var failed in new[] { true, false })
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
var expected = failed ? new Dictionary<string, string> { { "ERRORS", error }, { "REFERENCE", "same-reference" } }
: new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" }, { "REFERENCE", "same-reference" } };
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "same-reference"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
Check(ReferenceEquals(result, expected) && frames.Length == 3 &&
frames[0]["value"].Value<string>() == "CardRequested" &&
frames[1]["value"].Value<string>() == "PinEntryStarted" &&
JToken.DeepEquals(frames[2]["result"], JObject.FromObject(expected)),
"SDK error silenced subsequent progress or changed final fields: " + error);
CheckUnsubscribed(tap);
}
Check(starts == 2, "SDK error changed transaction dispatch count: " + error);
}
}
private static void ExecutionFailuresDoNotSilenceNextStream()
{
foreach (var failure in new[] { "start exception", "cancelled completion", "faulted completion" })
using (var firstOutput = new MemoryStream())
using (var nextOutput = new MemoryStream())
{
var tap = new TransactionProgressTap();
var first = new TransactionStreamWriter(firstOutput);
var completion = new TaskCompletionSource<Dictionary<string, string>>();
var startError = new InvalidOperationException("synthetic start failure");
int starts = 0;
bool caught = false;
try
{
tap.Observe(first.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
if (failure == "start exception") throw startError;
Task.Run(() => {
if (failure == "cancelled completion") completion.SetCanceled();
else completion.SetException(new IOException("synthetic SDK fault"));
});
}, () => completion.Task, TimeSpan.FromSeconds(5)));
}
catch (InvalidOperationException ex)
{
caught = failure == "start exception" && ReferenceEquals(ex, startError);
}
catch (AggregateException ex)
{
caught = failure == "cancelled completion" ? ex.InnerException is TaskCanceledException
: failure == "faulted completion" && ex.InnerException is IOException;
}
Check(caught, "execution exception/cancellation behavior changed for " + failure);
CheckUnsubscribed(tap);
first.Complete(new { type = "error", error = "Transaction stream failed" });
first.Deliver();
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
var next = new TransactionStreamWriter(nextOutput);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Declined" }, { "REFERENCE", "next" } };
var result = tap.Observe(next.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "next"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
next.Complete(new { type = "result", result });
next.Deliver();
var frames = Frames(nextOutput);
Check(starts == 2 && ReferenceEquals(result, expected) && frames.Length == 3 &&
frames[0]["value"].Value<string>() == "CardRequested" &&
frames[1]["value"].Value<string>() == "PinEntryStarted" &&
JToken.DeepEquals(frames[2]["result"], JObject.FromObject(expected)),
"next transaction lost progress or changed result after " + failure);
CheckUnsubscribed(tap);
}
}
private static void TimeoutDoesNotSilenceNextStream()
{
var tap = new TransactionProgressTap();
var pending = new TaskCompletionSource<Dictionary<string, string>>();
int starts = 0;
using (var firstOutput = new MemoryStream())
using (var nextOutput = new MemoryStream())
{
var first = new TransactionStreamWriter(firstOutput);
var timeout = tap.Observe(first.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
}, () => pending.Task, TimeSpan.Zero));
first.Complete(new { type = "result", result = timeout });
first.Deliver();
CheckUnsubscribed(tap);
var next = new TransactionStreamWriter(nextOutput);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" }, { "REFERENCE", "next" } };
var result = tap.Observe(next.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted", "next"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
next.Complete(new { type = "result", result });
next.Deliver();
var frames = Frames(nextOutput);
Check(frames.Where(f => f["type"].Value<string>() == "status")
.Select(f => f["value"].Value<string>()).SequenceEqual(new[] { "CardRequested", "PinEntryStarted" }),
"next transaction lost fresh progress after the previous timeout");
Check(starts == 2 && !pending.Task.IsCompleted && ReferenceEquals(result, expected) &&
frames.Last()["result"]["TRANSACTION_RESULT"].Value<string>() == "Approved",
"progress recovery changed dispatch count, pending completion or the next financial result");
CheckUnsubscribed(tap);
}
}
private static JObject[] Frames(MemoryStream stream)
{
var text = Encoding.UTF8.GetString(stream.ToArray());
Check(text.Length == 0 || text[0] != '\uFEFF', "stream contained a BOM");
return text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(JObject.Parse).ToArray();
}
private static void QueueCapacityCannotDropFinal()
{
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
for (int i = 0; i < 1000; i++) writer.Progress("UPDATE", "CardRequested");
writer.Complete(new { type = "result", result = new { TRANSACTION_RESULT = "Approved" } });
writer.Complete(new { type = "error", error = "duplicate" });
writer.Progress("UPDATE", "PinEntryStarted");
writer.Deliver();
writer.Deliver();
var frames = Frames(output);
Check(frames.Length == 129 && frames.Last()["type"].Value<string>() == "result", "full queue dropped or duplicated final");
Check(frames.Take(128).All(f => f["value"].Value<string>() == "CardRequested"), "progress arrived after final");
}
}
private static void ConcurrentCallbacksKeepValidLinesAndOneFinal()
{
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
var delivery = Task.Run(() => writer.Deliver());
var tap = new TransactionProgressTap();
tap.Observe(writer.Progress, () => {
Parallel.For(0, 5000, i => tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted")));
return new Dictionary<string, string>();
});
writer.Complete(new { type = "result", result = new { TRANSACTION_RESULT = "Declined" } });
Check(delivery.Wait(TimeSpan.FromSeconds(5)), "writer did not finish");
var frames = Frames(output);
Check(frames.Count(f => f["type"].Value<string>() == "result") == 1 &&
frames.Last()["type"].Value<string>() == "result", "concurrent callbacks corrupted terminal framing");
Check(frames.Where(f => f["type"].Value<string>() == "status").All(f =>
f["source"].Value<string>() == "UPDATE" && f["value"].Value<string>() == "PinEntryStarted"),
"concurrent callbacks corrupted status fields");
}
}
private sealed class DisconnectedStream : MemoryStream
{
public override void Write(byte[] buffer, int offset, int count) { throw new IOException("disconnected"); }
}
private static void DisconnectDoesNotInterruptExecution()
{
var tap = new TransactionProgressTap();
int starts = 0;
using (var output = new DisconnectedStream())
{
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" } };
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
writer.Deliver(); // The disconnected consumer cannot abort execution.
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
writer.Complete(new { type = "result", result });
writer.Progress("UPDATE", "CardRequested");
Check(starts == 1 && ReferenceEquals(result, expected), "disconnect changed final transaction result");
CheckUnsubscribed(tap);
}
using (var output = new MemoryStream())
{
var writer = new TransactionStreamWriter(output);
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Declined" } };
var result = tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted"));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1)));
writer.Complete(new { type = "result", result });
writer.Deliver();
var frames = Frames(output);
Check(starts == 2 && ReferenceEquals(result, expected) && frames.Length == 3 &&
frames[0]["value"].Value<string>() == "CardRequested" &&
frames[1]["value"].Value<string>() == "PinEntryStarted" &&
JToken.DeepEquals(frames[2]["result"], JObject.FromObject(expected)),
"disconnected previous stream suppressed progress, reused its buffer or changed the next result");
CheckUnsubscribed(tap);
}
}
private sealed class BlockingStream : MemoryStream
{
internal readonly ManualResetEventSlim WriteEntered = new ManualResetEventSlim();
internal readonly ManualResetEventSlim Release = new ManualResetEventSlim();
public override void Write(byte[] buffer, int offset, int count)
{
WriteEntered.Set();
if (!Release.Wait(TimeSpan.FromSeconds(10))) throw new IOException("test consumer stayed blocked");
base.Write(buffer, offset, count);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Release.Set();
WriteEntered.Dispose();
Release.Dispose();
}
base.Dispose(disposing);
}
}
private static void SlowConsumerDoesNotBlockCallbacksOrCompletion()
{
using (var output = new BlockingStream())
{
var tap = new TransactionProgressTap();
var writer = new TransactionStreamWriter(output);
var delivery = Task.Run(() => writer.Deliver());
var expected = new Dictionary<string, string> { { "TRANSACTION_RESULT", "Approved" } };
int starts = 0;
var execution = Task.Run(() => tap.Observe(writer.Progress, () => TransactionExecution.Run(() => {
starts++;
tap.Report("UPDATE", Native("UPDATE", "CardRequested"));
Check(output.WriteEntered.Wait(TimeSpan.FromSeconds(5)), "consumer never reached the blocked write");
Parallel.For(0, 5000, i => tap.Report("UPDATE", Native("UPDATE", "PinEntryStarted")));
}, () => Task.FromResult(expected), TimeSpan.FromSeconds(1))));
try
{
Check(execution.Wait(TimeSpan.FromSeconds(5)), "slow consumer blocked SDK callbacks or execution");
Check(starts == 1 && ReferenceEquals(execution.Result, expected), "slow consumer changed financial completion");
CheckUnsubscribed(tap);
writer.Complete(new { type = "result", result = execution.Result });
tap.Report("UPDATE", Native("UPDATE", "CardRemovalRequested"));
}
finally
{
output.Release.Set();
writer.Complete(new { type = "error", error = "test cleanup" });
Check(execution.Wait(TimeSpan.FromSeconds(5)), "execution did not exit after consumer release");
Check(delivery.Wait(TimeSpan.FromSeconds(5)), "delivery did not exit after consumer release");
}
var frames = Frames(output);
Check(frames[0]["value"].Value<string>() == "CardRequested" &&
frames.Count(f => f["type"].Value<string>() == "result") == 1 &&
frames.Last()["type"].Value<string>() == "result" &&
JToken.DeepEquals(frames.Last()["result"], JObject.FromObject(expected)),
"slow consumer reordered progress, lost the final result or delivered progress after final");
}
}
private static void PreauthFieldsAreOptionalProviderValues()
{
var verification = TransactionStreamFields.Required(new Dictionary<string, string> {
{ "TRANSACTION_RESULT", "APPROVED" }, { "TRANSACTION_TYPE", "ACCOUNT VERIFICATION" },
{ "REFERENCE", "verification-ref" }, { "PAN_MASKED", "************1133" }
});
Check(verification["TRANSACTION_TYPE"] == "ACCOUNT VERIFICATION" &&
verification["TRANSACTION_RESULT"] == "APPROVED" && !verification.ContainsKey("TOTAL_AMOUNT"),
"optional verification amount was fabricated or provider type changed");
var monetary = TransactionStreamFields.Required(new Dictionary<string, string> {
{ "TRANSACTION_TYPE", "SALE" }, { "TOTAL_AMOUNT", "3100" }
});
Check(monetary["TRANSACTION_TYPE"] == "SALE" && monetary["TOTAL_AMOUNT"] == "3100",
"provider monetary fields were changed or omitted");
var absent = TransactionStreamFields.Required(new Dictionary<string, string>());
Check(!absent.ContainsKey("TRANSACTION_TYPE") && !absent.ContainsKey("TOTAL_AMOUNT"),
"allowlist synthesized absent provider fields");
}
private static void FinalFieldsExcludeSensitiveParameters()
{
var fields = TransactionStreamFields.Required(new Dictionary<string, string> {
{ "TRANSACTION_RESULT", "Approved" }, { "PAN", "1234567890123456" },
{ "PAN_MASKED", "1234567890123456" }, { "CVV", "123" }, { "PIN", "1234" },
{ "TRACK_DATA", "track-secret" }, { "RAW", "raw-secret" }, { "CARD_HASH", "hash" },
{ "CARD_REFERENCE", "ref" }, { "RECEIPT_DATA_CARDHOLDER", "receipt" }
});
Check(!fields.ContainsKey("PAN") && !fields.ContainsKey("CVV") && !fields.ContainsKey("PIN") &&
!fields.ContainsKey("TRACK_DATA") && !fields.ContainsKey("RAW") && fields["PAN_MASKED"] == "",
"sensitive fields crossed structured boundary");
Check(fields["CARD_HASH"] == "hash" && fields["CARD_REFERENCE"] == "ref" && fields["RECEIPT_DATA_CARDHOLDER"] == "receipt", "required final fields were lost");
Check(TransactionStreamFields.MaskedCardNumber("123456******1234") == "123456******1234" &&
TransactionStreamFields.MaskedCardNumber("476173******1133") == "476173******1133" &&
TransactionStreamFields.MaskedCardNumber("************1133") == "************1133" &&
TransactionStreamFields.MaskedCardNumber("1234567890123456****") == "" &&
TransactionStreamFields.MaskedCardNumber("34373631373330303030303031313333") == "", "valid masking rejected or encoding/full digits treated as masking");
Check(!TransactionStreamFields.IsProgress("PAN", "CardRequested") &&
!TransactionStreamFields.IsProgress("UPDATE", "1234567890123456") &&
!TransactionStreamFields.IsProgress("CARD_STATUS", "Removed"), "unsafe progress permitted");
}
}
}
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<AssemblyName>ChipDNAClient.StreamingTests</AssemblyName>
<OutputPath>bin\Debug\</OutputPath>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="Creditcall.ChipDna.ClientLib">
<HintPath>..\CompiledLibs\Creditcall.ChipDna.ClientLib.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Compile Include="..\TransactionStreaming.cs"><Link>TransactionStreaming.cs</Link></Compile>
<Compile Include="StreamingTests.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+209
View File
@@ -0,0 +1,209 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Creditcall.ChipDna.Client
{
// This is the original start/wait mechanism shared by the XML and NDJSON adapters.
internal static class TransactionExecution
{
internal static Dictionary<string, string> Run(Action start,
Func<Task<Dictionary<string, string>>> completion, TimeSpan timeout)
{
start();
var task = completion();
// Task.Wait intentionally retains its existing exception behavior.
if (!task.Wait(timeout))
{
return new Dictionary<string, string>
{
{ ParameterKeys.TransactionResult, "TIMEOUT" },
{ ParameterKeys.Errors, "Transaction timed out waiting for device response" }
};
}
try { return task.Result; }
catch (AggregateException agg)
{
var first = agg.Flatten().InnerExceptions[0];
return new Dictionary<string, string>
{
{ ParameterKeys.TransactionResult, "ERROR" },
{ ParameterKeys.Errors, $"Transaction task faulted: {first.Message}" }
};
}
}
}
internal sealed class TransactionProgressTap
{
private readonly object gate = new object();
private Action<string, string> listener;
internal Dictionary<string, string> Observe(Action<string, string> callback, Func<Dictionary<string, string>> execute)
{
lock (gate) { listener += callback; }
try { return execute(); }
finally { lock (gate) { listener -= callback; } }
}
internal void Report(string source, EventParameters parameters)
{
lock (gate)
{
if (listener == null || parameters == null) return;
string value;
switch (source)
{
case "UPDATE":
if (!parameters.GetValue(ParameterKeys.Update, out value)) return;
break;
case "CARD_STATUS":
if (!parameters.GetValue(ParameterKeys.Notification, out value)) return;
break;
case "SIGNATURE": value = "Requested"; break;
case "PAUSE": value = "Paused"; break;
default: return;
}
if (!TransactionStreamFields.IsProgress(source, value)) return;
// Progress is display-only, including late SDK callbacks. The active
// request's listener only attempts a bounded enqueue, never socket I/O.
listener?.Invoke(source, value);
}
}
}
internal sealed class TransactionStreamWriter
{
private readonly object gate = new object();
private readonly ConcurrentQueue<string> progress = new ConcurrentQueue<string>();
private readonly AutoResetEvent available = new AutoResetEvent(false);
private readonly Stream output;
private string terminal;
private bool completed;
private bool disconnected;
private bool delivering;
internal TransactionStreamWriter(Stream output) { this.output = output; }
internal void Progress(string source, string value)
{
if (!TransactionStreamFields.IsProgress(source, value)) return;
lock (gate)
{
if (completed || disconnected || progress.Count >= 128) return;
progress.Enqueue(JsonConvert.SerializeObject(new { type = "status", source, value }));
available.Set();
}
}
internal void Complete(object frame)
{
lock (gate)
{
if (completed || disconnected) return;
completed = true;
terminal = JsonConvert.SerializeObject(frame);
available.Set();
}
}
internal void Deliver()
{
lock (gate) { if (delivering) return; delivering = true; }
try
{
// One writer owns all progress and terminal writes.
using (var writer = new StreamWriter(output, new System.Text.UTF8Encoding(false), 1024, true))
{
while (true)
{
string line;
bool isTerminal = false;
lock (gate)
{
if (!progress.TryDequeue(out line) && completed)
{
line = terminal;
isTerminal = true;
}
}
if (line == null) { available.WaitOne(); continue; }
writer.WriteLine(line);
writer.Flush();
if (isTerminal) return;
}
}
}
catch (Exception ex) when (ex is IOException || ex is System.Net.HttpListenerException || ex is ObjectDisposedException)
{
lock (gate) { disconnected = true; }
}
finally
{
lock (gate)
{
disconnected = true;
available.Dispose();
}
}
}
}
internal static class TransactionStreamFields
{
internal static bool IsProgress(string source, string value)
{
switch (source)
{
case "UPDATE":
switch (value)
{
case "CardRequested": case "ProvideCard": case "InsertOrSwipeCard":
case "InsertOrContactless": case "InsertCard": case "SwipeCard":
case "CardRemovalRequested": case "CardRemovalEnforced":
case "PinEntryStarted": case "PinEntryPrompt": case "PinEntryInProgress":
case "PinEntryFailed": case "PinEntrySuccessful": case "TransactionStarted":
case "OnlineAuthRequested": case "OnlineAuthorizeRequest": case "OnlineAuthCompleted":
return true;
}
return false;
case "CARD_STATUS": return value == "Inserted" || value == "Tapped" || value == "Swiped";
case "SIGNATURE": return value == "Requested";
case "PAUSE": return value == "Paused";
default: return false;
}
}
internal static Dictionary<string, string> Required(Dictionary<string, string> fields)
{
var result = new Dictionary<string, string>();
// Receipts remain local to hardlink; no raw parameter bag reaches the kiosk.
foreach (var key in new[] { "TRANSACTION_RESULT", "ERRORS", "ERROR_DESCRIPTION",
"REFERENCE", "PAN_MASKED", "CARD_SCHEME_ID", "EXPIRY_DATE", "CARD_HASH",
"CARD_REFERENCE", "RECEIPT_DATA_CARDHOLDER", "TRANSACTION_TYPE", "TOTAL_AMOUNT" })
{
string value;
if (fields.TryGetValue(key, out value))
result[key] = key == "PAN_MASKED" ? MaskedCardNumber(value) : value;
}
return result;
}
internal static string MaskedCardNumber(string value)
{
int digits = 0, masks = 0;
foreach (char ch in value ?? "")
{
if (ch >= '0' && ch <= '9') digits++;
else if (ch == '*' || ch == 'x' || ch == 'X') masks++;
else if (ch != ' ' && ch != '-') return "";
}
return masks >= 4 && digits <= 10 ? value : "";
}
}
}