Initialize a Merkle tree of 8 with blank leaves in solidity - hash

I am trying to initialise an empty merkle tree in the constructor my solidity contract
I have a merkle tree of 8 leaves, so that means that the flattened out form of the merkle tree would be something like uint256 [15] hashes. But i want to initalize it in the constructor. The first 8 leaves will be 0 and we can assume they're already hashed. after that there will be 4 nodes which would be hashes of the leaves and then 2 and then the root. How can I implement this using poseidon hash?
Thanks.

Related

How to get the value from the byte array object using ICorProfilerInfo2

I'm using ICorProfilerCallback2 interface to profiler my application. On function enter hook I'm trying to read the value from byte array which is passed as an argument to a function. I've the argument info COR_PRF_FUNCTION_ARGUMENT_INFO from which I can get the starting address of the byte array argument.
If it is a string argument I can use "GetStringLayout" method from ICorProfilerInfo2 interface to get the bufferoffset and stringlengthoffset.
How can I find the offsets for byte array and how to read the values from it?
Where can I find the documents for those?
If you have the ObjectID (or COR_PRF_FUNCTION_ARGUMENT_RANGE) of the argument, you have an easy life (at least for Objects/Arrays, not for Value Types. You have to validate the parameter type using the metadata).
You can use ICorProfilerInfo::GetClassFromObject and ICorProfilerInfo::IsArrayClass to determine if it's an array. If so, IsArrayClass gives you the type of array. Arrays in .Net have a specific layout (I don't think it's in the official docs): It's always 8 bytes for ClassID, 8 bytes for size, and than all the elements, without padding (Note: Objects are stored by ObjectID, just like in other memory regions).
You can also use ICorProfilerInfo2::GetArrayObjectInfo to get the size (need to calculate from dimensions) and the starting address of the objects.
Relevant reads:
https://mattwarren.org/2017/05/08/Arrays-and-the-CLR-a-Very-Special-Relationship/
https://windowsdebugging.wordpress.com/2012/04/24/memorylayoutofarraysx64/

Swift pointer from ArraySlice

I'm trying to determine the "Swift-y" way of creating my own contiguous memory containers (in my particular case, I'm building n-dimensional arrays). I want my containers to be as close to Swift's builtin Array as possible - in terms of functionality and usability.
I need to access the pointer to memory of my containers for stuff like Accelerate and BLAS operations.
I want to know whether an ArraySlice's pointer would point to the first element of the slice, or the first element of its base.
When I tried to test UnsafePointer<Int>(array) == UnsafePointer<Int>(array[1...2]) it looks like Swift doesn't allow pointer construction from ArraySlices (or I just did it incorrectly).
I'm looking for advice on which way would be the most "Swift-y"?
I understand that when slicing an array the follow is true:
let array = [1, 2, 3]
array[1] == array[1...2][1]
and
array[1...2][0] != 2 # index out of bounds error
In other words, indexing is always performed relative to the base Array.
Which suggests: that we should return a pointer to the base's first element. Because slices are relative to their base.
However, iteration through a slice (obviously) only considers elements of that slice:
for i in array[1..2] # i takes on 2 followed by 3
Which suggests: that we should return a pointer to the slice's first element. Because slices have their own starting point.
If my user wanted to operate on a slice in a BLAS operation it would be intuitive to expect:
mmul(matrix1[1...2, 0...1].pointer, matrix2[4...5, 0...1].pointer)
to point to the first elements of slice, but I don't know if this is the way a Swift ArraySlice would do things.
My Question: Should a container slice object's pointer point to the first element of the slice, or, the first element of the base container.
This operation is unsafe:
UnsafePointer<Int>(array)
What you mean is:
array.withUnsafeBufferPointer { ... }
This applies to your types as well, and is the pattern you should employ to interoperate with BLAS and Accelerate. You should not try to use a pointer method IMO.
There is no promise that array will continue to exist by the time you actually access the pointer, even if that happens in the same line of code. ARC is free to destroy that memory shockingly quickly.
UnsafeBufferPointer is actually a very nice type in that it is already promised to be contiguous and it behaves as a Collection.
My suggestion here would be to manage your own memory internally, probably with a ManagedBuffer, but maybe just with a UnsafeMutablePointer that you alloc and destroy yourself. It's very important that you manage the layout of the data so that it's compatible with Accelerate. You don't want Array<Array<UInt8>>. That's going to add too much structure. You want a blob of bytes that you index into in the good-ol' C ways (row*width+column, etc). You probably don't want your slices to return pointers at all directly. Your mmul function is likely going to need special logic to understand how to pull the pieces it needs out of slices with minimal copying so that it works with vDSP_mmul. "Generic" and "Accelerate" seldom go together.
For example, considering this:
mmul(matrix1[1...2, 0...1].pointer, matrix2[4...5, 0...1].pointer)
(Obviously I assume your real matrices are dramatically larger; this kind of matrix doesn't make much sense to send to vDSP.)
You're going to have to write your own mmul here obviously since this memory isn't laid out correctly. So you might as well pass the slices. Then you'd do something like (totally untested, uncompiled, and I'm sure the syntax is wildly wrong):
mmul(m1: MatrixSlice, m2: MatrixSlice) -> Matrix {
var s1 = UnsafeMutablePointer<Float>.alloc(m1.rows * m1.columns)
// use vDSP_vgathr to copy each sliced row out of m1 into s1
var s2 = UnsafeMutablePointer<Float>.alloc(m2.rows * m2.columns)
// use vDSP_vgathr to copy each sliced row out of m2 into s2
var result = UnsafeMutablePointer<Float>.alloc(m1.rows * m2.columns)
vDSP_mmul(s1, 1, s2, 1, result, 1, m1.rows, m2.columns, m1.columns)
s1.destroy()
s2.destroy()
// This will need to call result.move() or moveInitializeFrom or something
return Matrix(result)
}
I'm just throwing out stuff here, but this is probably the kind of structure you'd want.
To your underlying question about whether the pointer to the container or to the data is usually passed by Swift, the answer is unfortunately "magic" for Array and no one else. Passing an Array to something that wants a pointer will magically (by the compiler, not the stdlib) pass a pointer to the storage of the Array. No other type gets this magic. Not even ContiguousArray gets this magic. If you pass a ContiguousArray to something that wants a pointer, you'll pass the pointer to the container (and if it's mutable, corrupt the container; true story, hated that oneā€¦)
Thanks in part to #RobNapier the answer to my question is: ArraySlice's pointer should point to the slice's first element.
The way I verified this was simply:
var array = [5,4,3,325,67,7,3]
array.withUnsafeBufferPointer{ $0 } != array[3...6].withUnsafeBufferPointer{ $0 } # true
^--- points to 5's address ^--- points to 325's address

MATLAB - How to solve error, "Scalar index required for this type of multi-level indexing"?

I have a struct called "Trials" and a field called "peakvel" which is inside a struct called "sac1str", which is then inside Trials.
I want to extract the data inside the field "peakvel".
This is my code:
ed(fileidx).vel_up = [Trials(Lup & Lgoodtrials).sac1str.sac1ovr_peakvel];
Whenever I run this I get an error, "Scalar index required for this type of multi-level indexing."
Any ideas to get around this error?
The chaining of non-scalar indexing ((Lup & Lgoodtrials)) and accesing two levels of structs is not possible. Use a temporary variable in between:
temp=[Trials(Lup & Lgoodtrials)].sac1str
ed(fileidx).vel_up=[temp.sac1ovr_peakvel]
There are three types of subsref, first two are the indexing operations for cells and arrays, third is the access to a field of a struct. When using non-scalar indices (more than one element is indexed) on a top-level, you can access only one further level of the struct. The error says you can not combine multi-level indexing (in the struct) with non scalar indices (for the array). Not allowed is:
Trials(Lup & Lgoodtrials).sac1str.sac1ovr_peakvel
But allowed is the 1-level indexing:
Trials(Lup & Lgoodtrials).sac1str
Or use of scalar idices:
s=2
Trials(s).sac1str.sac1ovr_peakvel

Automatic Field Order Rearrangement in D

I just saw the following at http://dlang.org/pretod.html#pragmapack quote:
For D classes, there is no need to adjust the alignment (in fact, the compiler is free to rearrange the data fields to get the optimum layout, much as the compiler will rearrange local variables on the stack frame). For D structs that get mapped onto externally defined data structures, there is a need, and it is handled with:
struct Foo
{
align (4): // use 4 byte alignment
...
}
Does this mean that structs fields are not rearranged as are class fields mentioned above?
Yes, although I don't think current implementations rearrange class fields anyway.

Matlab: list of trees

I have implemented a binary tree in Matlab using 'struct' type elements as nodes. An N-node tree has, say, N such structs.
My problem is that I have M such trees, each having a different number of nodes, N_1, N_2, ..., N_M. How can I hold these trees in a list or array which can be iterated? Several trials like struct of structs did not seem to work.
Edit: I want to do something like the following. myClassTree returns a tree with N_i nodes.
trees = struct;
for i=1:nTrees
tree = myClassTree(train(bags(i,:),:), entropy, depth);
trees(i) = tree;
end
The easiest thing is to create a cell array. Simply replace trees(i) = tree; with trees{i} = tree; (note braces, rather than parenthesis).
Cell arrays are useful whenever you want to store an array of mixed data types. To access elements of a cell array, you can use the braces again. For example, this should work as you expect:
currentTree = trees{someIndex};
The code that you posted creates an array of structs, which only works if the structures have the same fieldnames.
If you wanted (not recommended) you could created a struct of structs, but doing somehting like this trees.(['n' sprintf('%04d',i)]) = tree;. (But please don't.)