I'm trying to sign a transaction using Oracle service in Corda.For this, I'm using a function specified in Corda docs.
fun commandValidator(elem: Command<*>): Boolean {
require(services.myInfo.legalIdentities.first().owningKey in elem.signers && elem.value is Fix) {
"Oracle received unknown command (not in signers or not Fix)."
}
val fix = elem.value as Fix
val known = knownFixes[fix.of]
if (known == null || known != fix)
throw UnknownFix(fix.of)
return true
}
But when I try using the above function , I'm getting error for "knownFixes" and "UnknownFix()" as unresolved reference .
a) How to solve this issue (how do I declare or import these)?
b) Is this approach the right way to do signing transaction from Oracle Service?
knownFixes and UnknownFix are CorDapp-specific code defined as part of the IRS sample.
Signing as the oracle is as simple as:
#CordaService
class Oracle(val services: ServiceHub) : SingletonSerializeAsToken() {
fun sign(ftx: FilteredTransaction): TransactionSignature {
val myKey = services.myInfo.legalIdentities.first().owningKey
return services.createSignature(ftx, myKey)
}
}
But you would normally want to do additional checking, to ensure you're happy with what you're signing. The checks are up to you. Here's an example of an oracle that checks whether a number embedded in a command is a prime number:
#CordaService
class Oracle(val services: ServiceHub) : SingletonSerializeAsToken() {
private val myKey = services.myInfo.legalIdentities.first().owningKey
// Generates a list of natural numbers and filters out the non-primes.
// The reason why prime numbers were chosen is because they are easy to reason about and reduce the mental load
// for this tutorial application.
// Clearly, most developers can generate a list of primes and all but the largest prime numbers can be verified
// deterministically in reasonable time. As such, it would be possible to add a constraint in the
// [PrimeContract.verify] function that checks the nth prime is indeed the specified number.
private val primes = generateSequence(1) { it + 1 }.filter { BigInteger.valueOf(it.toLong()).isProbablePrime(16) }
// Returns the Nth prime for N > 0.
fun query(n: Int): Int {
require(n > 0) { "n must be at least one." } // URL param is n not N.
return primes.take(n).last()
}
// Signs over a transaction if the specified Nth prime for a particular N is correct.
// This function takes a filtered transaction which is a partial Merkle tree. Any parts of the transaction which
// the oracle doesn't need to see in order to verify the correctness of the nth prime have been removed. In this
// case, all but the [PrimeContract.Create] commands have been removed. If the Nth prime is correct then the oracle
// signs over the Merkle root (the hash) of the transaction.
fun sign(ftx: FilteredTransaction): TransactionSignature {
// Check the partial Merkle tree is valid.
ftx.verify()
/** Returns true if the component is an Create command that:
* - States the correct prime
* - Has the oracle listed as a signer
*/
fun isCommandWithCorrectPrimeAndIAmSigner(elem: Any) = when {
elem is Command<*> && elem.value is PrimeContract.Create -> {
val cmdData = elem.value as PrimeContract.Create
myKey in elem.signers && query(cmdData.n) == cmdData.nthPrime
}
else -> false
}
// Is it a Merkle tree we are willing to sign over?
val isValidMerkleTree = ftx.checkWithFun(::isCommandWithCorrectPrimeAndIAmSigner)
if (isValidMerkleTree) {
return services.createSignature(ftx, myKey)
} else {
throw IllegalArgumentException("Oracle signature requested over invalid transaction.")
}
}
}
Related
I am new with Axon and maybe I missed something, but need help to understand.
I have a simple food cart aggregate.
Here is example:
#Aggregate
class FoodCard {
#AggregateIdentifier
private lateinit var foodCardId: UUID
private lateinit var selectedProduct: MutableMap<UUID, Int>
constructor()
#CommandHandler
constructor(command: CreateFoodCartCommand) {
AggregateLifecycle.apply(FoodCartCreateEvent(
UUID.randomUUID()
))
}
#CommandHandler
fun handle(command: SelectProductCommand) {
AggregateLifecycle
.apply(ProductSelectedEvent(foodCardId, command.productId, command.quantity))
}
#CommandHandler
fun handle(command: DeleteFoodCartCommand) {
AggregateLifecycle
.apply(FoodCartDeleteEvent(foodCardId))
}
#CommandHandler
fun handle(command: DeselectProductCommand) {
val productId = command.productId
if (!selectedProduct.containsKey(productId)) {
throw ProductDeselectionException("ProductDeselectionException")
}
AggregateLifecycle
.apply(ProductDeselectEvent(foodCardId, productId, command.quantity))
}
#EventSourcingHandler
fun on(event: FoodCartCreateEvent) {
foodCardId = event.foodCardId
selectedProduct = mutableMapOf()
}
#EventSourcingHandler
fun on(event: ProductSelectedEvent) {
selectedProduct.merge(
event.productId,
event.quantity
) {a, b -> a + b}
}
}
As ES I am using Axon Server.
For FoodCard projector I am using JPA repository that connects to DB.
I want to get all foodcards that contain special product (concrete UUID) and change quantity to -1 for all of them.
I understood there are two types of actions -> read and write
So the question how to correctly implement this flow with Axon?
Thanks
from your explanation and code I feel that you will probably need to complete your implementation of DeselectProductCommand introducing an EventSourcingHandler for ProductDeselectEvent. If I understood correctly your "quantity" information is stored into the selectProduct Map. In this case, based on your code, I see that the information of the quantity that should be subtracted to your product is in the command.
You will also need a Query, such as FindAllFoodCardByProductId, that will retrieve the foodCardId aggregate identifier that contains a certain productId: this operation will be performed on your Projection through the jpa repository.
As a reference you can have a look at the ref guide here https://docs.axoniq.io/reference-guide/implementing-domain-logic/query-handling on how to use QueryGateway into your controller and implement a QueryHandler into your Projection.
Corrado.
I have a function in Kotlin which takes in an Int argument and return a value based on a formula. To speed things up I store intermediate results in a HashMap<Int, Int>
private val calculatedResults = HashMap<Int, Int>()
private fun q2(n: Int): Int {
if(calculatedResults.containsKey(n)) {
return calculatedResults[n]
}
val q = ...
calculatedResults[n] = q
return q
}
I'm getting a type mismatch of Int found but Int? required at
return calculatedResults[n]
Im not sure how to correctly write this. I had
return calculatedResults[n]!!
But I'm not sure, if it's a bit hacky.
Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be <Int, Int?>?
getOrPut will check if a value exists for n. If the value exists, it will be returned. If the values does not exist the value returned by the lambda will be assigned and afterwards returned by getOrPut.
Take a look at this example:
fun calculate(n: Int) = n * 5 // some calculation
private fun q2(n: Int) = calculatedResults.getOrPut(n) {
calculate(n)
}
Should the return type of the function be Int? because while the
HashMap might contain the key n the value could be null? Wouldn't that
mean the HashMap should be ?
In this case the answer to the question is obviously "no" because if the value is missing you just add it. So, the value returned by q2 can never be null.
The underlying problem is that calculatedResults could have been modified by an other thread between contains (if(calculatedResults.containsKey(n))) and get (return calculatedResults[n]).
Even after checking with containsKey calculatedResults[n] could therefore possibly return a wrong result, including null, and this way of checking should be avoided.
Using !! should generally only be used when absolutely necessary, because it can cause a NPE. It definitely is hacky.
Use the following syntax to overcome the problem:
calculatedResults[n]?.let {
return it
}
Basically this is a nice way of saying
val result = calculatedResults[n]
if(result != null) {
return result
}
see https://kotlinlang.org/docs/reference/null-safety.html#safe-calls
Even better is to use the built-in getOrPut:
private fun q2(n: Int): Int {
return calculatedResults.getOrPut(n) { calcQ() }
}
private fun calcQ(): Int {
val q = ...
return q
}
Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be <Int, Int?>?
No, you did exactly the right thing when you defined the method signature. The compiler only complained because what happened within the method did not fit it. If you change the method signature you just move the problem to the function calling q2 without handling it.
You should consider re-writing this to more idiomatic code. It's a rather basic task to compute a value if it is not set in the map already:
fun q2(n: Int): Int {
return calculatedResults.getOrPut(n) {
42 //q
}
}
This is my code
This gives stack overflow error 30 times on the output console
fun main(args:Array<String>){
var no:Int=Integer.parseInt(readLine())//read input from user and convert to Integer
var ans:Int=calculateFact(no) //call function and store to ans variable
println("Factorial of "+no+" is "+ans) //print result
}
fun calculateFact(no:Int):Int //function for recursion
{
if(no==0) {
return 1 }
return (no*calculateFact(no))
}
I don't know what is error
solve plz
You should return
no*calculateFact(no - 1)
not
no*calculateFact(no)
otherwise the recursion can never end.
Other than the mistake in the recursion that was already pointed out, it's worth mentioning that your method will still only work correctly for numbers up to 12, since 13! is larger than the maximum value that you can store in an Int. Therefore, for numbers 13 and up, you'll essentially get "random" results due to overflow.
If you just use BigInteger instead, it will work until the call stack gets too deep and causes a stack overflow, this happens around 8000 on my machine.
fun calculateFact(no: BigInteger): BigInteger {
if (no == BigInteger.ZERO) {
return BigInteger.ONE
}
return (no * calculateFact(no - BigInteger.ONE))
}
fun main(args: Array<String>) {
val no: BigInteger = BigInteger(readLine())
val ans: BigInteger = calculateFact(no)
println("Factorial of $no is $ans")
}
If you want to handle numbers larger than that, you can use a tailrec function (this specific solution is taken from this article):
tailrec fun calculateFact(acc: BigInteger, n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) {
return acc
}
return calculateFact(n * acc, n - BigInteger.ONE)
}
fun calculateFact(n: BigInteger) : BigInteger {
return calculateFact(BigInteger.ONE, n)
}
fun main(args: Array<String>) {
val n: BigInteger = BigInteger(readLine())
val ans: BigInteger = calculateFact(n)
println("Factorial of $n is $ans")
}
This will work for numbers up to a couple hundred thousand, your problem with this one will become the time it takes to run instead of the memory constraints.
fun main(args:Array<String>) {
var no:Int = Integer.parseInt(readLine()) //read input from user and convert to Integer
var ans:Int=calculateFact(no) //call function and store to ans variable
println("Factorial of "+no+" is "+ans) //print result
}
fun calculateFact(no:Int):Int { //function for recursion
if(no==0) {
return 1
}
return (no*calculateFact(no - 1)) // you forgot to decrease the no here.
}
If you didnot decrease no then it will call the calculateFact() method all the time. Please check the code, it will work.
So in TinyOS an interface is composed of commands and events. When a module uses an interface, it calls its commands and provides an implementation of its events (provides an event handler).
The sense of the return type of a command is clear, it is the same as that of any function/method in any programming language, but, the return type of an event results unclear to me.
Let's take an example:
interface Counter{
command int64_t getCounter(int64_t destinationId);
event int64_t counterSent(int64_t destinationId);
}
Let's define a module that provides the Counter interface.
module Provider{
provides interface Counter;
}
implementation {
int64_t counter;
counter = 75; //Random number
/**
Returns the value of the counter and signals an event that
someone with id equal to destinationId asked for the counter.
**/
command int64_t getCounter(int64_t destinationId){
int64_t signalReturnedValue;
signalReturnedValue = signal counterSent(destinationId);
return counter;
}
}
Now let's define two module which use this interface.
module EvenIDChecker{
uses interface Counter;
}
implementation{
/**
Returns 1 if the destinationId is even, 0 otherwise
**/
event int64_t counterSent(int64_t destinationId){
if(destinationId % 2 == 0){
return 1;
} else {
return 0;
}
}
}
Now let's define another module which uses the same interface but does the inverse of the EvenIDChecker module.
module OddIDChecker{
uses interface Counter;
}
implementation{
/**
Returns 1 if the destinationId is odd, 0 otherwise
**/
event int64_t counterSent(int64_t destinationId){
if(destinationId % 2 == 1){
return 1;
} else {
return 0;
}
}
}
In the end, what would be the final value of the var signalReturnedValue?
The value is unspecified or this code may even not compile.
In TinyOS, there's a concept of combine functions, which are of signature type f(type, type) and their purpose is to reasonably combine two values of the same type. For error_t there's such a function defined:
error_t ecombine(error_t e1, error_t e2) {
return (e1 == e2) ? e1 : FAIL;
}
Combine function is called automatically in a situation such as in your code snippet.
If you want to define a combine function in this example, you need to typedef the return type of the event. See 4.4.3 Combine Functions for more information.
Note that the situation is symmetric for commands. You can wire two implementations of an interface to a single uses declaration like this:
configuration ExampleC {
ExampleP.Counter -> Counter1;
ExampleP.Counter -> Counter2;
}
Assuming that Counter has a command that returns something, whenever ExampleP calls that command, two implementations are executed and two return values are combined.
I'm not sure of the best approach for handling scoping of "this" in TypeScript.
Here's an example of a common pattern in the code I am converting over to TypeScript:
class DemonstrateScopingProblems {
private status = "blah";
public run() {
alert(this.status);
}
}
var thisTest = new DemonstrateScopingProblems();
// works as expected, displays "blah":
thisTest.run();
// doesn't work; this is scoped to be the document so this.status is undefined:
$(document).ready(thisTest.run);
Now, I could change the call to...
$(document).ready(thisTest.run.bind(thisTest));
...which does work. But it's kinda horrible. It means that code can all compile and work fine in some circumstances, but if we forget to bind the scope it will break.
I would like a way to do it within the class, so that when using the class we don't need to worry about what "this" is scoped to.
Any suggestions?
Update
Another approach that works is using the fat arrow:
class DemonstrateScopingProblems {
private status = "blah";
public run = () => {
alert(this.status);
}
}
Is that a valid approach?
You have a few options here, each with its own trade-offs. Unfortunately there is no obvious best solution and it will really depend on the application.
Automatic Class Binding
As shown in your question:
class DemonstrateScopingProblems {
private status = "blah";
public run = () => {
alert(this.status);
}
}
Good/bad: This creates an additional closure per method per instance of your class. If this method is usually only used in regular method calls, this is overkill. However, if it's used a lot in callback positions, it's more efficient for the class instance to capture the this context instead of each call site creating a new closure upon invoke.
Good: Impossible for external callers to forget to handle this context
Good: Typesafe in TypeScript
Good: No extra work if the function has parameters
Bad: Derived classes can't call base class methods written this way using super.
Bad: The exact semantics of which methods are "pre-bound" and which aren't create an additional non-typesafe contract between your class and its consumers.
Function.bind
Also as shown:
$(document).ready(thisTest.run.bind(thisTest));
Good/bad: Opposite memory/performance trade-off compared to the first method
Good: No extra work if the function has parameters
Bad: In TypeScript, this currently has no type safety
Bad: Only available in ECMAScript 5, if that matters to you
Bad: You have to type the instance name twice
Fat arrow
In TypeScript (shown here with some dummy parameters for explanatory reasons):
$(document).ready((n, m) => thisTest.run(n, m));
Good/bad: Opposite memory/performance trade-off compared to the first method
Good: In TypeScript, this has 100% type safety
Good: Works in ECMAScript 3
Good: You only have to type the instance name once
Bad: You'll have to type the parameters twice
Bad: Doesn't work with variadic parameters
Another solution that requires some initial setup but pays off with its invincibly light, literally one-word syntax is using Method Decorators to JIT-bind methods through getters.
I've created a repo on GitHub to showcase an implementation of this idea (it's a bit lengthy to fit into an answer with its 40 lines of code, including comments), that you would use as simply as:
class DemonstrateScopingProblems {
private status = "blah";
#bound public run() {
alert(this.status);
}
}
I haven't seen this mentioned anywhere yet, but it works flawlessly. Also, there is no notable downside to this approach: the implementation of this decorator -- including some type-checking for runtime type-safety -- is trivial and straightforward, and comes with essentially zero overhead after the initial method call.
The essential part is defining the following getter on the class prototype, which is executed immediately before the first call:
get: function () {
// Create bound override on object instance. This will hide the original method on the prototype, and instead yield a bound version from the
// instance itself. The original method will no longer be accessible. Inside a getter, 'this' will refer to the instance.
var instance = this;
Object.defineProperty(instance, propKey.toString(), {
value: function () {
// This is effectively a lightweight bind() that skips many (here unnecessary) checks found in native implementations.
return originalMethod.apply(instance, arguments);
}
});
// The first invocation (per instance) will return the bound method from here. Subsequent calls will never reach this point, due to the way
// JavaScript runtimes look up properties on objects; the bound method, defined on the instance, will effectively hide it.
return instance[propKey];
}
Full source
The idea can be also taken one step further, by doing this in a class decorator instead, iterating over methods and defining the above property descriptor for each of them in one pass.
Necromancing.
There's an obvious simple solution that doesn't require arrow-functions (arrow-functions are 30% slower), or JIT-methods through getters.
That solution is to bind the this-context in the constructor.
class DemonstrateScopingProblems
{
constructor()
{
this.run = this.run.bind(this);
}
private status = "blah";
public run() {
alert(this.status);
}
}
You can write an autobind method to automatically bind all functions in the constructor of the class:
class DemonstrateScopingProblems
{
constructor()
{
this.autoBind(this);
}
[...]
}
export function autoBind(self)
{
for (const key of Object.getOwnPropertyNames(self.constructor.prototype))
{
const val = self[key];
if (key !== 'constructor' && typeof val === 'function')
{
// console.log(key);
self[key] = val.bind(self);
} // End if (key !== 'constructor' && typeof val === 'function')
} // Next key
return self;
} // End Function autoBind
Note that if you don't put the autobind-function into the same class as a member function, it's just autoBind(this); and not this.autoBind(this);
And also, the above autoBind function is dumbed down, to show the principle.
If you want this to work reliably, you need to test if the function is a getter/setter of a property as well, because otherwise - boom - if your class contains properties, that is.
Like this:
export function autoBind(self)
{
for (const key of Object.getOwnPropertyNames(self.constructor.prototype))
{
if (key !== 'constructor')
{
// console.log(key);
let desc = Object.getOwnPropertyDescriptor(self.constructor.prototype, key);
if (desc != null)
{
if (!desc.configurable) {
console.log("AUTOBIND-WARNING: Property \"" + key + "\" not configurable ! (" + self.constructor.name + ")");
continue;
}
let g = desc.get != null;
let s = desc.set != null;
if (g || s)
{
var newGetter = null;
var newSetter = null;
if (g)
newGetter = desc.get.bind(self);
if (s)
newSetter = desc.set.bind(self);
if (newGetter != null && newSetter == null) {
Object.defineProperty(self, key, {
get: newGetter,
enumerable: desc.enumerable,
configurable: desc.configurable
});
}
else if (newSetter != null && newGetter == null) {
Object.defineProperty(self, key, {
set: newSetter,
enumerable: desc.enumerable,
configurable: desc.configurable
});
}
else {
Object.defineProperty(self, key, {
get: newGetter,
set: newSetter,
enumerable: desc.enumerable,
configurable: desc.configurable
});
}
continue; // if it's a property, it can't be a function
} // End if (g || s)
} // End if (desc != null)
if (typeof (self[key]) === 'function')
{
let val = self[key];
self[key] = val.bind(self);
} // End if (typeof (self[key]) === 'function')
} // End if (key !== 'constructor')
} // Next key
return self;
} // End Function autoBind
In your code, have you tried just changing the last line as follows?
$(document).ready(() => thisTest.run());