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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use rlp::{self, Rlp};

use crate::{
    merkle::{
        nibble::{Nibble, NibbleVec},
        MerkleNode, MerkleValue,
    },
    Change, Database,
};

fn find_and_remove_child<'a, D: Database>(
    merkle: MerkleValue<'a>,
    database: &'a D,
) -> (MerkleNode<'a>, Change) {
    let mut change = Change::default();

    let node = match merkle {
        MerkleValue::Empty => panic!(),
        MerkleValue::Full(ref sub_node) => sub_node.as_ref().clone(),
        MerkleValue::Hash(h) => {
            let sub_node =
                MerkleNode::decode(&Rlp::new(database.get(h))).expect("Unable to decode value");
            change.remove_raw(h);
            sub_node
        }
    };

    (node, change)
}

fn collapse_extension(
    mut node_nibble: NibbleVec,
    subnode: MerkleNode<'_>,
) -> (MerkleNode<'_>, Change) {
    let mut change = Change::default();

    let node = match subnode {
        MerkleNode::Leaf(mut sub_nibble, sub_value) => {
            node_nibble.append(&mut sub_nibble);
            MerkleNode::Leaf(node_nibble, sub_value)
        }
        MerkleNode::Extension(mut sub_nibble, sub_value) => {
            debug_assert!(sub_value != MerkleValue::Empty);

            node_nibble.append(&mut sub_nibble);
            MerkleNode::Extension(node_nibble, sub_value)
        }
        branch => {
            let subvalue = change.add_value(&branch);
            MerkleNode::Extension(node_nibble, subvalue)
        }
    };

    (node, change)
}

fn nonempty_node_count<'a, 'b>(
    nodes: &'b [MerkleValue<'a>; 16],
    additional: &'b Option<&'a [u8]>,
) -> usize {
    additional.iter().count() + nodes.iter().filter(|v| v != &&MerkleValue::Empty).count()
}

fn collapse_branch<'a, D: Database>(
    node_nodes: [MerkleValue<'a>; 16],
    node_additional: Option<&'a [u8]>,
    database: &'a D,
) -> (MerkleNode<'a>, Change) {
    let mut change = Change::default();

    let value_count = nonempty_node_count(&node_nodes, &node_additional);

    let node = match value_count {
        0 => panic!(),
        1 if node_additional.is_some() =>
            MerkleNode::Leaf(NibbleVec::new(), node_additional.unwrap()),
        1 /* value in node_nodes */ => {
            let (subindex, subvalue) = node_nodes.iter().enumerate()
                .find(|&(_, v)| v != &MerkleValue::Empty)
                .map(|(i, v)| (i, v.clone())).unwrap();
            let subnibble =  Nibble::from(subindex);

            let (subnode, subchange) = find_and_remove_child(subvalue, database);
            change.merge(&subchange);

            match subnode {
                MerkleNode::Leaf(mut leaf_nibble, leaf_value) => {
                    leaf_nibble.insert(0, subnibble);
                    MerkleNode::Leaf(leaf_nibble, leaf_value)
                },
                MerkleNode::Extension(mut ext_nibble, ext_value) => {
                    debug_assert!(ext_value != MerkleValue::Empty);

                    ext_nibble.insert(0, subnibble);
                    MerkleNode::Extension(ext_nibble, ext_value)
                },
                branch => {
                    let subvalue = change.add_value(&branch);
                    MerkleNode::Extension(vec![subnibble], subvalue)
                },
            }
        },
        _ /* value_count > 1 */ =>
            MerkleNode::Branch(node_nodes, node_additional),
    };

    (node, change)
}

pub fn delete_by_child<'a, D: Database>(
    merkle: MerkleValue<'a>,
    nibble: NibbleVec,
    database: &'a D,
) -> (Option<MerkleNode<'a>>, Change) {
    let mut change = Change::default();

    let new = match merkle {
        MerkleValue::Empty => None,
        MerkleValue::Full(ref sub_node) => {
            let (new_node, subchange) = delete_by_node(sub_node.as_ref().clone(), nibble, database);
            change.merge(&subchange);
            match new_node {
                Some(new_node) => Some(new_node),
                None => None,
            }
        }
        MerkleValue::Hash(h) => {
            let sub_node = MerkleNode::decode(&Rlp::new(database.get(h)))
                .expect("Unable to decode Node value");
            change.remove_raw(h);
            let (new_node, subchange) = delete_by_node(sub_node, nibble, database);
            change.merge(&subchange);
            match new_node {
                Some(new_node) => Some(new_node),
                None => None,
            }
        }
    };

    (new, change)
}

pub fn delete_by_node<'a, D: Database>(
    node: MerkleNode<'a>,
    nibble: NibbleVec,
    database: &'a D,
) -> (Option<MerkleNode<'a>>, Change) {
    let mut change = Change::default();

    let new = match node {
        MerkleNode::Leaf(node_nibble, node_value) => {
            if node_nibble == nibble {
                None
            } else {
                Some(MerkleNode::Leaf(node_nibble, node_value))
            }
        }
        MerkleNode::Extension(node_nibble, node_value) => {
            if nibble.starts_with(&node_nibble) {
                let (subnode, subchange) =
                    delete_by_child(node_value, nibble[node_nibble.len()..].into(), database);
                change.merge(&subchange);

                match subnode {
                    Some(subnode) => {
                        let (new, subchange) = collapse_extension(node_nibble, subnode);
                        change.merge(&subchange);

                        Some(new)
                    }
                    None => None,
                }
            } else {
                Some(MerkleNode::Extension(node_nibble, node_value))
            }
        }
        MerkleNode::Branch(mut node_nodes, mut node_additional) => {
            let needs_collapse;

            if nibble.is_empty() {
                node_additional = None;
                needs_collapse = true;
            } else {
                let ni: usize = nibble[0].into();
                let (new_subnode, subchange) =
                    delete_by_child(node_nodes[ni].clone(), nibble[1..].into(), database);
                change.merge(&subchange);

                match new_subnode {
                    Some(new_subnode) => {
                        let new_subvalue = change.add_value(&new_subnode);

                        node_nodes[ni] = new_subvalue;
                        needs_collapse = false;
                    }
                    None => {
                        node_nodes[ni] = MerkleValue::Empty;
                        needs_collapse = true;
                    }
                }
            }

            if needs_collapse {
                let value_count = nonempty_node_count(&node_nodes, &node_additional);
                if value_count > 0 {
                    let (new, subchange) = collapse_branch(node_nodes, node_additional, database);
                    change.merge(&subchange);

                    Some(new)
                } else {
                    None
                }
            } else {
                Some(MerkleNode::Branch(node_nodes, node_additional))
            }
        }
    };

    (new, change)
}