-
Notifications
You must be signed in to change notification settings - Fork 0
Notes on the Structs
Defined in keys.h
The key_set struct stores the results of the process of turning a seed into a bitcoin address. A key_set includes the original seed, the private key, as well as the three types of bitcoin addresses we generate. By storing the results in an easy to access struct, we simplify other operations that might involve private keys or bitcoin addresses, like sorting them in an array, finding duplicate private keys, etc.
The only notable property is key_set::seed. While all the other properties are char arrays, the seed property is a pointer to a string. This is because seed length can vary, so allocating the maximum amount of space would be wasteful.
Defined in keys.h
struct Array is a slightly modified array.
-
Array::arrayis an array that stores pointers tostruct key_sets. -
Array::usedis a counter that describes the number of elements that are currently indexed inArray::array. -
Array::sizeis the maximum number of elements that can be added toArray:array
You can find it's definition in keys.h, but what you won't find there is the following important message.
When we call free_Array on a struct Array, our intention is to essentially destroy all key_sets held within the array. Hoarding memory is bad and if you don't need the Array anymore it's best to get rid of it. However, there can be unintended consequences if you don't understand this data structure. Let's say you have two Arrays:
struct oldstruct new
Assume your goal is to move all the elements of old::array into new:array, this is pretty easy, all we have to do is iterate over each element in old::array and call push_Array(&new, old.array[current_index]);, right? That wasn't too bad, and now that we're done with old we should free it, so we call free_Array(&old);.
The thing is, both old::array and new::array store pointers to heap allocated key_sets, they don't actually store the key_sets themselves, just references to them. When we free old, we free all the elements in it as well, the catch is that new stores the exact same references, so we've lost all the records in new as well.
Note: a diagram would be helpful here.
This happened because I wanted to save space. The key_set struct is a lot bigger than pointer, so I thought storing multiple copies on the heap would be dangerous (considering how many key_sets I assumed would be on the heap). Luckily, to fix this issue, we can just free old without freeing the elements in it, since they will eventually be deallocated when we call free_Array(&new);.
There are cases when you can't free old until you're done with new, for example, if new is a subset of old. In this case, your best bet is to free new.array, and then call free_Array(&old), since old is the greater set.