# 简单序列化的工作原理

## 序列化

• 无符号整数

• 布尔值

struct Dummy {
number1: u64,
number2: u64,
vector: Vec<u8>,
number3: u64
}
dummy = Dummy{
number1: 37,
number2: 55,
vector: vec![1,2,3,4],
number3: 22,
}
serialized = ssz.serialize(dummy)


serialized 将具有以下结构（此处仅填充到 4 位，实际上填充到 32 位，并保留 int 表示，以确保清晰明确）：

[37, 0, 0, 0, 55, 0, 0, 0, 16, 0, 0, 0, 22, 0, 0, 0, 1, 2, 3, 4]

------------  -----------  -----------  -----------  ----------

|             |            |           |            |

number1       number2    offset for    number 3    value for

vector                   vector


[
37, 0, 0, 0,  # little-endian encoding of number1.
55, 0, 0, 0,  # little-endian encoding of number2.
16, 0, 0, 0,  # The "offset" that indicates where the value of vector starts (little-endian 16).
22, 0, 0, 0,  # little-endian encoding of number3.
1, 2, 3, 4,   # The actual values in vector.
]


[
10100101000000000000000000000000  # little-endian encoding of number1
10110111000000000000000000000000  # little-endian encoding of number2.
10010000000000000000000000000000  # The "offset" that indicates where the value of vector starts (little-endian 16).
10010110000000000000000000000000  # little-endian encoding of number3.
10000001100000101000001110000100   # The actual value of the bytes field.
]


# 默克尔化

        hash tree root

/     \

/       \

/         \

/           \

hash of leaves  hash of leaves

1 and 2         3 and 4

/   \            /  \

/     \          /    \

/       \        /      \

leaf1     leaf2  leaf3     leaf4


# 广义索引

        1           --depth = 0  2**0 + 0 = 1

2       3       --depth = 1  2**1 + 0 = 2, 2**1+1 = 3

4   5   6   7     --depth = 2  2**2 + 0 = 4, 2**2 + 1 = 5...


# 多值证明

(8,9) 的哈希值应该等于哈希值 (4)，它与 5 进行哈希计算可生成 2，与 3 进行哈希计算可生成树根 1。 如果为 9 提供了不正确的数据，根会发生改变，我们会检测到这一问题，从而无法验证分支。

* = 生成证明所需的数据

1*

2                      3*

4          5*          6          7

8*     9*   10    11   12    13    14    15


# 参考资料

https://ethereum.org/zh/developers/docs/data-structures-and-encoding/ssz/