/
block.ex
58 lines (51 loc) · 1.35 KB
/
block.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
defmodule Block do
@hash_size Crypto.hash_size()
defstruct parent_block: <<0::size(256)>>,
number: 0,
winner: <<0::size(256)>>,
state_changes_hash: Crypto.hash(<<>>)
def to_binary(%{
parent_block: parent_block,
number: number,
winner: winner,
state_changes_hash: state_changes_hash
}) do
parent_block <> <<number::size(256)>> <> winner <> state_changes_hash
end
def to_json(block) do
block
|> Map.from_struct()
|> Enum.map(fn {key, value} ->
if is_binary(value) do
{key, Base.encode16(value, case: :lower)}
else
{key, value}
end
end)
|> Enum.into(%{})
|> Poison.encode!()
end
def to_binary(%{
parent_block: parent_block,
number: number,
winner: winner,
state_changes_hash: state_changes_hash
}) do
parent_block <> <<number::size(256)>> <> winner <> state_changes_hash
end
def from_map(%{
parent_block: parent_block,
number: number,
winner: winner,
state_changes_hash: state_changes_hash
}) do
{number, _} = Integer.parse(number)
%__MODULE__{
parent_block: parent_block,
number: number,
winner: winner,
state_changes_hash: state_changes_hash
}
end
def hash(block), do: Crypto.hash(to_binary(block))
end