melos 0.0.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +71 -11
  3. data/docs/roadmap.md +302 -0
  4. data/docs/validation.md +172 -0
  5. data/lib/melos/capabilities.rb +18 -0
  6. data/lib/melos/client.rb +255 -0
  7. data/lib/melos/credential/x509.rb +91 -0
  8. data/lib/melos/crypto.rb +109 -15
  9. data/lib/melos/epoch_secrets.rb +166 -0
  10. data/lib/melos/errors.rb +18 -0
  11. data/lib/melos/external_sender.rb +78 -0
  12. data/lib/melos/group/validation.rb +310 -0
  13. data/lib/melos/group.rb +1087 -0
  14. data/lib/melos/key_package_bundle.rb +67 -0
  15. data/lib/melos/persistence.rb +45 -0
  16. data/lib/melos/private_tree.rb +70 -0
  17. data/lib/melos/ratchet_tree.rb +407 -0
  18. data/lib/melos/secret_tree.rb +130 -88
  19. data/lib/melos/struct/base.rb +46 -20
  20. data/lib/melos/struct/structs.rb +205 -87
  21. data/lib/melos/tree.rb +4 -120
  22. data/lib/melos/vec.rb +20 -35
  23. data/lib/melos/version.rb +1 -1
  24. data/lib/melos.rb +13 -2
  25. metadata +18 -22
  26. data/lib/melos/key_schedule.rb +0 -62
  27. data/lib/melos/struct/ratchet_tree.rb +0 -324
  28. data/test_vectors/crypto-basics.json +0 -303
  29. data/test_vectors/deserialization.json +0 -58
  30. data/test_vectors/key-schedule.json +0 -926
  31. data/test_vectors/message-protection.json +0 -142
  32. data/test_vectors/messages.json +0 -5702
  33. data/test_vectors/passive-client-handling-commit.json +0 -2683
  34. data/test_vectors/passive-client-random.json +0 -2657
  35. data/test_vectors/passive-client-welcome.json +0 -814
  36. data/test_vectors/psk_secret.json +0 -2382
  37. data/test_vectors/secret-tree.json +0 -4846
  38. data/test_vectors/transcript-hashes.json +0 -58
  39. data/test_vectors/tree-math.json +0 -8276
  40. data/test_vectors/tree-operations.json +0 -47
  41. data/test_vectors/tree-validation.json +0 -11839
  42. data/test_vectors/treekem.json +0 -14877
  43. data/test_vectors/welcome.json +0 -51
@@ -0,0 +1,67 @@
1
+ require_relative 'crypto'
2
+ require_relative 'constants'
3
+ require_relative 'capabilities'
4
+ require_relative 'struct/structs'
5
+
6
+ # A KeyPackage this client has published (RFC 9420 Section 10), together with the private keys
7
+ # that belong to it: the init key, used once to decrypt the Welcome that adds us, and the leaf's
8
+ # encryption key, which becomes our leaf's private key in the group. Each KeyPackage has its own
9
+ # encryption key pair, so every leaf a client holds is keyed separately.
10
+ class Melos::KeyPackageBundle
11
+ attr_reader :suite, :key_package, :init_private_key, :encryption_private_key
12
+
13
+ DEFAULT_LIFETIME = 60 * 60 * 24 * 7 # seconds
14
+
15
+ def initialize(suite, key_package, init_private_key, encryption_private_key)
16
+ @suite = suite
17
+ @key_package = key_package
18
+ @init_private_key = init_private_key
19
+ @encryption_private_key = encryption_private_key
20
+ end
21
+
22
+ # 10: a fresh KeyPackage signed with signature_private_key, whose leaf carries signature_public_key and credential
23
+ def self.generate(suite, signature_private_key:, signature_public_key:, credential:, capabilities: nil, lifetime: nil, extensions: [])
24
+ init_key_pair = Melos::Crypto.generate_encapsulation_key_pair(suite)
25
+ encryption_key_pair = Melos::Crypto.generate_encapsulation_key_pair(suite)
26
+ now = Time.now.to_i
27
+ leaf_node = Melos::Struct::LeafNode.create(
28
+ encryption_key: Melos::Crypto.serialize_public_key(suite, encryption_key_pair),
29
+ signature_key: signature_public_key,
30
+ credential: credential,
31
+ capabilities: capabilities || Melos::Struct::Capabilities.import(Melos::Capabilities.new),
32
+ leaf_node_source: Melos::Constants::LeafNodeSource::KEY_PACKAGE,
33
+ lifetime: lifetime || Melos::Struct::Lifetime.create(not_before: now, not_after: now + DEFAULT_LIFETIME),
34
+ parent_hash: nil,
35
+ extensions: extensions,
36
+ signature: nil
37
+ )
38
+ leaf_node.sign(suite, signature_private_key, nil, nil) # 7.2: group_id and leaf_index are not part of a key_package leaf's signature
39
+ key_package = Melos::Struct::KeyPackage.create(
40
+ cipher_suite: suite.suite_id,
41
+ init_key: Melos::Crypto.serialize_public_key(suite, init_key_pair),
42
+ leaf_node: leaf_node
43
+ )
44
+ key_package.sign(signature_private_key)
45
+ new(suite, key_package,
46
+ Melos::Crypto.serialize_private_key(suite, init_key_pair),
47
+ Melos::Crypto.serialize_private_key(suite, encryption_key_pair))
48
+ end
49
+
50
+ def to_h
51
+ { key_package: @key_package.raw, init_private_key: @init_private_key, encryption_private_key: @encryption_private_key }
52
+ end
53
+
54
+ def self.from_h(suite, hash)
55
+ new(suite, Melos::Struct::KeyPackage.new(hash[:key_package]), hash[:init_private_key], hash[:encryption_private_key])
56
+ end
57
+
58
+ # 5.2: the KeyPackageRef a Welcome uses to address this KeyPackage
59
+ def ref
60
+ @key_package.ref(@suite)
61
+ end
62
+
63
+ # the KeyPackage as it is published: an MLSMessage
64
+ def message
65
+ Melos::Struct::MLSMessage.create(key_package: @key_package)
66
+ end
67
+ end
@@ -0,0 +1,45 @@
1
+ require 'json'
2
+
3
+ # Turning the state Hashes of Melos::Client#to_h and Melos::Group#to_h into JSON and back.
4
+ # Those Hashes have Symbol keys, and their Strings are binary; here every String becomes hex and every
5
+ # key a JSON string, and the reverse on load. Marshal, MessagePack or anything else that keeps
6
+ # binary Strings works on the Hashes as they are.
7
+ #
8
+ # The state holds private keys and epoch secrets. Encrypting it at rest is the application's job.
9
+ module Melos::Persistence
10
+ extend self
11
+
12
+ def dump_json(hash)
13
+ JSON.generate(encode(hash))
14
+ end
15
+
16
+ def load_json(json)
17
+ decode(JSON.parse(json))
18
+ end
19
+
20
+ def dump_client(client) = dump_json(client.to_h)
21
+ def load_client(json, **group_options) = Melos::Client.from_h(load_json(json), **group_options)
22
+ def dump_group(group) = dump_json(group.to_h)
23
+ def load_group(json, **options) = Melos::Group.from_h(load_json(json), **options)
24
+
25
+ private
26
+
27
+ def encode(value)
28
+ case value
29
+ when Hash then value.to_h { |key, v| [key.to_s, encode(v)] }
30
+ when Array then value.map { encode(_1) }
31
+ when String then value.unpack1('H*')
32
+ when Integer, true, false, nil then value
33
+ else raise ArgumentError.new("cannot encode #{value.class}")
34
+ end
35
+ end
36
+
37
+ def decode(value)
38
+ case value
39
+ when Hash then value.to_h { |key, v| [key.to_sym, decode(v)] }
40
+ when Array then value.map { decode(_1) }
41
+ when String then [value].pack('H*')
42
+ else value
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,70 @@
1
+ require_relative 'crypto'
2
+
3
+ # A member's private half of the ratchet tree (RFC 9420 Sections 7.4 and 7.5): the HPKE private
4
+ # keys this member holds, by node index. That is its own leaf, plus the parent nodes on its direct
5
+ # path whose path secrets it has learned, either by creating an UpdatePath or by decrypting one.
6
+ class Melos::PrivateTree
7
+ def initialize(keys = {})
8
+ @keys = keys
9
+ end
10
+
11
+ def [](node_index)
12
+ @keys[node_index]
13
+ end
14
+
15
+ def []=(node_index, private_key)
16
+ @keys[node_index] = private_key
17
+ end
18
+
19
+ def delete(node_index)
20
+ @keys.delete(node_index)
21
+ end
22
+
23
+ def node_indexes
24
+ @keys.keys.sort
25
+ end
26
+
27
+ def dup
28
+ self.class.new(@keys.dup)
29
+ end
30
+
31
+ # [[node_index, private key], ...]
32
+ def to_a
33
+ @keys.sort.to_a
34
+ end
35
+
36
+ def self.from_a(pairs)
37
+ new(pairs.to_h)
38
+ end
39
+
40
+ # 7.4: starting with path_secret at start_node_index, derive the node private key there and at
41
+ # every node up its filtered direct path on ratchet_tree, each from the next path secret
42
+ def set_path_secret(ratchet_tree, start_node_index, path_secret)
43
+ suite = ratchet_tree.suite
44
+ secret = path_secret
45
+ ([start_node_index] + ratchet_tree.filtered_direct_path(start_node_index)).each do |node_index|
46
+ node_secret = Melos::Crypto.derive_secret(suite, secret, "node")
47
+ private_key, _public_key = Melos::Crypto.derive_key_pair(suite, node_secret)
48
+ @keys[node_index] = private_key
49
+ secret = Melos::Crypto.derive_secret(suite, secret, "path")
50
+ end
51
+ end
52
+
53
+ # 9.2, 7.5: drop every private key whose node is now blank, gone, or carries a different public key
54
+ def prune!(ratchet_tree)
55
+ @keys.select! { |node_index, private_key| matches_node?(ratchet_tree, node_index, private_key) }
56
+ self
57
+ end
58
+
59
+ # every private key here belongs to a non-blank node of ratchet_tree whose public key it matches
60
+ def consistent?(ratchet_tree)
61
+ @keys.all? { |node_index, private_key| matches_node?(ratchet_tree, node_index, private_key) }
62
+ end
63
+
64
+ private
65
+
66
+ def matches_node?(ratchet_tree, node_index, private_key)
67
+ node = ratchet_tree[node_index]
68
+ !node.nil? && Melos::Crypto.encapsulation_key_pair_corresponds?(ratchet_tree.suite, private_key, node.public_encryption_key)
69
+ end
70
+ end
@@ -0,0 +1,407 @@
1
+ require 'securerandom'
2
+ require_relative 'tree'
3
+ require_relative 'crypto'
4
+ require_relative 'vec'
5
+ require_relative 'constants'
6
+ require_relative 'struct/structs'
7
+
8
+ # The ratchet tree (RFC 9420 Section 7) in the array representation of Appendix C:
9
+ # nodes[i] is the Melos::Struct::Node at node index i, or nil for a blank node.
10
+ #
11
+ # The tree is always full (7.7): the number of leaves is a power of two, so @nodes
12
+ # always has 2^(d+1) - 1 entries. Extending the tree doubles it with a blank right
13
+ # subtree, and truncating halves it while the right subtree is entirely blank.
14
+ #
15
+ # This is the public tree every member of a group shares. A member's own private keys
16
+ # are kept separately in a Melos::PrivateTree and handed to the methods that need them.
17
+ #
18
+ # Wire format is the ratchet_tree extension (12.4.3.3): optional<Node> ratchet_tree<V>,
19
+ # with the blank nodes after the last non-blank node left out.
20
+ class Melos::RatchetTree
21
+ attr_reader :suite, :nodes
22
+
23
+ # nodes may omit trailing blanks (as the wire format does); it is padded to a full tree
24
+ def initialize(suite, nodes = [])
25
+ @suite = suite
26
+ @nodes = nodes
27
+ pad_to_full_tree!
28
+ end
29
+
30
+ # 12.4.3.3: the sender leaves out the blank nodes after the last non-blank node,
31
+ # so the last node must be non-blank; the receiver extends the tree back to 2^(d+1) - 1 nodes
32
+ def self.parse(suite, stream)
33
+ stream = StringIO.new(stream) if stream.is_a?(String)
34
+ nodes = []
35
+ data_stream = StringIO.new(Melos::Vec.parse_stream(stream))
36
+ until data_stream.eof?
37
+ presence = data_stream.read(1).unpack1('C')
38
+ nodes << (presence == 1 ? Melos::Struct::Node.new(data_stream) : nil)
39
+ end
40
+ raise Melos::ProtocolError.new('last node of ratchet_tree must not be blank') if !nodes.empty? && nodes.last.nil?
41
+ new(suite, nodes)
42
+ end
43
+
44
+ # 12.4.3.3: blank nodes after the last non-blank node are not included
45
+ def raw
46
+ last = @nodes.rindex { !_1.nil? }
47
+ encoded = last.nil? ? [] : @nodes[0..last]
48
+ buf = encoded.map { |node| node.nil? ? [0].pack('C') : [1].pack('C') + node.raw }.join
49
+ Melos::Vec.string_to_vec(buf)
50
+ end
51
+
52
+ # deep copy via the wire format, so that in-place changes to nodes
53
+ # (e.g. unmerged_leaves) on one copy do not affect the other
54
+ def dup
55
+ self.class.parse(@suite, raw)
56
+ end
57
+
58
+ def [](node_index)
59
+ @nodes[node_index]
60
+ end
61
+
62
+ def node_count
63
+ @nodes.count
64
+ end
65
+
66
+ # a power of two; some of the leaves may be blank
67
+ def n_leaves
68
+ (@nodes.count + 1) / 2
69
+ end
70
+
71
+ # node index of the root
72
+ def root
73
+ Melos::Tree.root(n_leaves)
74
+ end
75
+
76
+ # the Melos::Struct::LeafNode at leaf_index, or nil if that leaf is blank
77
+ def leaf_node_at(leaf_index)
78
+ @nodes[leaf_index * 2]&.leaf_node
79
+ end
80
+
81
+ # yields each non-blank leaf node with its leaf index
82
+ def each_leaf_node
83
+ (0...n_leaves).each do |leaf_index|
84
+ leaf_node = leaf_node_at(leaf_index)
85
+ yield leaf_node, leaf_index unless leaf_node.nil?
86
+ end
87
+ end
88
+
89
+ # leaf index of the first non-blank leaf for which the block is true, or nil
90
+ def find_leaf_index
91
+ each_leaf_node { |leaf_node, leaf_index| return leaf_index if yield(leaf_node) }
92
+ nil
93
+ end
94
+
95
+ ## Tree math that depends on the tree's contents (7.2, 7.8); pure index math lives in Melos::Tree
96
+
97
+ # 7.2: node indexes a message to this node must be encrypted to
98
+ def resolution(node_index)
99
+ node = @nodes[node_index]
100
+ if node.nil?
101
+ if Melos::Tree.leaf?(node_index)
102
+ # The resolution of a blank leaf node is the empty list.
103
+ []
104
+ else
105
+ # The resolution of a blank intermediate node is the result of concatenating the resolution of
106
+ # its left child with the resolution of its right child, in that order.
107
+ resolution(Melos::Tree.left(node_index)) + resolution(Melos::Tree.right(node_index))
108
+ end
109
+ elsif node.parent_node
110
+ # The resolution of a non-blank node comprises the node itself, followed by its list of unmerged leaves, if any.
111
+ [node_index] + node.parent_node.unmerged_leaves.map { _1 * 2 } # leaf index -> node index
112
+ else
113
+ [node_index]
114
+ end
115
+ end
116
+
117
+ # 7.8: direct path of node_index minus the nodes whose copath child has an empty resolution
118
+ def filtered_direct_path(node_index)
119
+ Melos::Tree.direct_path(node_index, n_leaves).reject do |ancestor|
120
+ resolution(Melos::Tree.sibling_from_leaf(node_index, ancestor, n_leaves)) == []
121
+ end
122
+ end
123
+
124
+ # for each node on the filtered direct path of node_index, its child on the copath side
125
+ def copath_nodes_of_filtered_direct_path(node_index)
126
+ filtered_direct_path(node_index).map { Melos::Tree.sibling_from_leaf(node_index, _1, n_leaves) }
127
+ end
128
+
129
+ # 7.7: while the right subtree of the root is entirely blank, drop it, halving the tree
130
+ def truncate!
131
+ return if n_leaves <= 1
132
+ r = root
133
+ if @nodes[(r + 1)..].all?(nil)
134
+ @nodes.slice!(r..) # the left child of the root becomes the root
135
+ truncate!
136
+ end
137
+ end
138
+
139
+ ## Tree hashes (7.8) and parent hashes (7.9)
140
+
141
+ def tree_hash(node_index = root)
142
+ node = @nodes[node_index]
143
+ if Melos::Tree.leaf?(node_index)
144
+ leaf_node_hash_input = [node_index / 2].pack('L>') # leaf index
145
+ leaf_node_hash_input += node.nil? ? [0].pack('C') : [1].pack('C') + node.leaf_node.raw
146
+ tree_hash_input = [1].pack('C') + leaf_node_hash_input # node_type = leaf
147
+ else
148
+ parent_node_hash_input = node.nil? ? [0].pack('C') : [1].pack('C') + node.parent_node.raw
149
+ parent_node_hash_input += Melos::Vec.string_to_vec(tree_hash(Melos::Tree.left(node_index)))
150
+ parent_node_hash_input += Melos::Vec.string_to_vec(tree_hash(Melos::Tree.right(node_index)))
151
+ tree_hash_input = [2].pack('C') + parent_node_hash_input # node_type = parent
152
+ end
153
+ Melos::Crypto.hash(@suite, tree_hash_input)
154
+ end
155
+
156
+ def root_tree_hash
157
+ tree_hash(root)
158
+ end
159
+
160
+ # 7.9.2: tree hash of node_index computed as if the given leaves were blank
161
+ def tree_hash_except(node_index, unmerged_leaves)
162
+ blanked = @nodes.dup
163
+ unmerged_leaves.each { blanked[_1 * 2] = nil }
164
+ self.class.new(@suite, blanked).tree_hash(node_index)
165
+ end
166
+
167
+ # 7.9: the parent hash of the parent node at node_index, for the child opposite to sibling_index
168
+ def parent_hash_of(node_index, sibling_index)
169
+ parent_node = @nodes[node_index].parent_node
170
+ sibling_hash = tree_hash_except(sibling_index, parent_node.unmerged_leaves)
171
+ Melos::Crypto.parent_hash(@suite, parent_node.encryption_key, parent_node.parent_hash, sibling_hash)
172
+ end
173
+
174
+ # 7.9.2: the parent node at node_index is parent-hash valid with respect to one of its children
175
+ def parent_hash_valid_at?(node_index)
176
+ return false if Melos::Tree.leaf?(node_index) # there is no parent hash to verify on a leaf
177
+ return true if @nodes[node_index].nil?
178
+ left = Melos::Tree.left(node_index)
179
+ right = Melos::Tree.right(node_index)
180
+ has_parent_hash?(left, parent_hash_of(node_index, right)) || has_parent_hash?(right, parent_hash_of(node_index, left))
181
+ end
182
+
183
+ # 7.9.2: every parent node in the tree is parent-hash valid; checked from the bottom level up
184
+ def parent_hash_valid?
185
+ parent_indexes = (1..((@nodes.count - 1) / 2)).map { _1 * 2 - 1 } # odd node indexes
186
+ parent_indexes.sort_by { Melos::Tree.level(_1) }.all? { parent_hash_valid_at?(_1) }
187
+ end
188
+
189
+ # 7.9.1: parent hashes along the filtered direct path of leaf_index, given the new encryption keys of an UpdatePath.
190
+ # hashes[i] is the parent hash of the i-th filtered direct path node, which is stored in the node below it:
191
+ # hashes[0] goes into the leaf, hashes[i] into filtered direct path node i-1, and hashes[count] is '' (the root).
192
+ def calculate_parent_hashes(leaf_index, update_path_nodes)
193
+ fdp = filtered_direct_path(leaf_index * 2)
194
+ hashes = []
195
+ hashes[fdp.count] = ''
196
+ calculated = ''
197
+ (fdp.count - 1).downto(0) do |i|
198
+ sibling_index = Melos::Tree.sibling_from_leaf(leaf_index * 2, fdp[i], n_leaves)
199
+ calculated = Melos::Crypto.parent_hash(@suite, update_path_nodes[i].encryption_key, calculated, tree_hash(sibling_index))
200
+ hashes[i] = calculated
201
+ end
202
+ hashes
203
+ end
204
+
205
+ # 7.9.2: the leaf node of update_path carries the parent hash its path implies on this tree
206
+ def verify_parent_hash_of_path(leaf_index, update_path)
207
+ update_path.leaf_node.parent_hash == calculate_parent_hashes(leaf_index, update_path.nodes)[0]
208
+ end
209
+
210
+ ## Applying proposals (12.1)
211
+
212
+ # 12.1.1 Add: place the leaf at the leftmost blank leaf, extending the tree if there is none (7.7:
213
+ # a new blank root whose left subtree is the existing tree and right subtree is all blank);
214
+ # record it as unmerged on every non-blank parent above it. Returns the new leaf index.
215
+ def add_leaf_node(leaf_node)
216
+ node = Melos::Struct::Node.new_leaf_node(leaf_node)
217
+ if @nodes.empty?
218
+ @nodes << node
219
+ return 0
220
+ end
221
+ inserted_node_index = (0...@nodes.count).step(2).find { @nodes[_1].nil? }
222
+ if inserted_node_index.nil?
223
+ @nodes.concat(Array.new(@nodes.count + 1)) # doubles the tree; the old root's index is the new blank root
224
+ inserted_node_index = (0...@nodes.count).step(2).find { @nodes[_1].nil? }
225
+ end
226
+ @nodes[inserted_node_index] = node
227
+ inserted_leaf_index = inserted_node_index / 2
228
+ Melos::Tree.direct_path(inserted_node_index, n_leaves).each do |ancestor|
229
+ @nodes[ancestor].parent_node.unmerged_leaves << inserted_leaf_index if @nodes[ancestor]&.parent_node
230
+ end
231
+ inserted_leaf_index
232
+ end
233
+
234
+ # 12.1.2 Update: replace the leaf and blank its direct path
235
+ def update_leaf_node(leaf_index, leaf_node)
236
+ @nodes[leaf_index * 2] = Melos::Struct::Node.new_leaf_node(leaf_node)
237
+ blank_direct_path(leaf_index * 2)
238
+ end
239
+
240
+ # 12.1.3 Remove: blank the leaf and its direct path, then truncate the tree
241
+ def remove_leaf_node(leaf_index)
242
+ @nodes[leaf_index * 2] = nil
243
+ blank_direct_path(leaf_index * 2)
244
+ truncate!
245
+ end
246
+
247
+ ## TreeKEM (7.4, 7.5, 12.4.2)
248
+
249
+ # 7.5 (both sides): replace the sender's leaf and the parent nodes on its filtered direct path with those in update_path
250
+ def merge_update_path(leaf_index, update_path)
251
+ node_index = leaf_index * 2
252
+ fdp = filtered_direct_path(node_index)
253
+ raise Melos::ProtocolError.new('malformed update path') unless fdp.count == update_path.nodes.count
254
+ parent_hashes = calculate_parent_hashes(leaf_index, update_path.nodes)
255
+ fdp.each_with_index do |fdp_node_index, i|
256
+ parent_node = Melos::Struct::ParentNode.create(
257
+ encryption_key: update_path.nodes[i].encryption_key,
258
+ parent_hash: parent_hashes[i + 1],
259
+ unmerged_leaves: []
260
+ )
261
+ @nodes[fdp_node_index] = Melos::Struct::Node.new_parent_node(parent_node)
262
+ end
263
+ @nodes[node_index] = Melos::Struct::Node.new_leaf_node(update_path.leaf_node)
264
+ end
265
+
266
+ # 7.5 (sender side): build an UpdatePath from a fresh leaf secret. Does not modify this tree; the caller
267
+ # merges the returned path with #merge_update_path once the commit is in place. The sender's new leaf
268
+ # private key and the private keys of its filtered direct path are written into private_tree.
269
+ # group_context: the provisional GroupContext of the new epoch (12.4.2). Its tree_hash is ignored and
270
+ # replaced with the hash of the tree after this path is merged, which the path secrets are encrypted with.
271
+ # except: node indexes to leave out of the copath resolutions (leaves being added by the same commit)
272
+ # Returns { update_path:, commit_secret:, path_secrets: } with path_secrets by node index of the filtered direct path.
273
+ def create_update_path(private_tree, sender_leaf_index, signature_private_key, group_context, except = [])
274
+ tree = dup
275
+ group_id = group_context.group_id
276
+ sender_node_index = sender_leaf_index * 2
277
+ original_leaf_node = tree.leaf_node_at(sender_leaf_index)
278
+ fdp = tree.filtered_direct_path(sender_node_index)
279
+
280
+ # 7.4: path secrets up the filtered direct path; the commit secret is one more derivation past the last one
281
+ leaf_secret = SecureRandom.random_bytes(@suite.kdf.n_h)
282
+ path_secrets = []
283
+ secret = leaf_secret
284
+ fdp.each do
285
+ secret = Melos::Crypto.derive_secret(@suite, secret, "path")
286
+ path_secrets << secret
287
+ end
288
+ commit_secret = Melos::Crypto.derive_secret(@suite, secret, "path")
289
+
290
+ leaf_private_key, leaf_public_key = Melos::Crypto.derive_key_pair(@suite, Melos::Crypto.derive_secret(@suite, leaf_secret, "node"))
291
+ node_key_pairs = path_secrets.map { Melos::Crypto.derive_key_pair(@suite, Melos::Crypto.derive_secret(@suite, _1, "node")) }
292
+
293
+ # parent hashes depend on the new public keys only, so compute them from nodes without ciphertexts
294
+ bare_nodes = node_key_pairs.map { |_priv, pub| Melos::Struct::UpdatePathNode.create(encryption_key: pub, encrypted_path_secret: []) }
295
+ parent_hashes = tree.calculate_parent_hashes(sender_leaf_index, bare_nodes)
296
+ new_leaf_node = Melos::Struct::LeafNode.create(
297
+ encryption_key: leaf_public_key,
298
+ signature_key: original_leaf_node.signature_key,
299
+ credential: original_leaf_node.credential,
300
+ capabilities: original_leaf_node.capabilities,
301
+ leaf_node_source: Melos::Constants::LeafNodeSource::COMMIT,
302
+ lifetime: original_leaf_node.lifetime,
303
+ parent_hash: parent_hashes[0],
304
+ extensions: original_leaf_node.extensions,
305
+ signature: nil
306
+ )
307
+ new_leaf_node.sign(@suite, signature_private_key, group_id, sender_leaf_index)
308
+
309
+ # merge into the copy so the copath resolutions below are those of the tree the receivers will see,
310
+ # and so that the provisional GroupContext carries the new tree hash
311
+ tree.merge_update_path(sender_leaf_index, Melos::Struct::UpdatePath.create(leaf_node: new_leaf_node, nodes: bare_nodes))
312
+ provisional_group_context = Melos::Struct::GroupContext.create(
313
+ cipher_suite: group_context.cipher_suite, group_id: group_context.group_id, epoch: group_context.epoch,
314
+ tree_hash: tree.root_tree_hash, confirmed_transcript_hash: group_context.confirmed_transcript_hash, extensions: group_context.extensions
315
+ )
316
+
317
+ copath_nodes = tree.copath_nodes_of_filtered_direct_path(sender_node_index)
318
+ nodes = fdp.each_index.map do |i|
319
+ ciphertexts = (tree.resolution(copath_nodes[i]) - except).map do |resolution_node_index|
320
+ kem_output, ciphertext = Melos::Crypto.encrypt_with_label(
321
+ @suite, tree[resolution_node_index].public_encryption_key, "UpdatePathNode", provisional_group_context.raw, path_secrets[i]
322
+ )
323
+ Melos::Struct::HPKECipherText.create(kem_output: kem_output, ciphertext: ciphertext)
324
+ end
325
+ Melos::Struct::UpdatePathNode.create(encryption_key: node_key_pairs[i][1], encrypted_path_secret: ciphertexts)
326
+ end
327
+
328
+ private_tree[sender_node_index] = leaf_private_key
329
+ fdp.each_with_index { |fdp_node_index, i| private_tree[fdp_node_index] = node_key_pairs[i][0] }
330
+
331
+ {
332
+ update_path: Melos::Struct::UpdatePath.create(leaf_node: new_leaf_node, nodes: nodes),
333
+ commit_secret: commit_secret,
334
+ path_secrets: fdp.zip(path_secrets).to_h
335
+ }
336
+ end
337
+
338
+ # 7.5 (receiver side), on the tree with update_path already merged: decrypt the path secret of the node where
339
+ # the receiver's direct path meets the sender's filtered direct path, and derive the private keys from that
340
+ # node up to the root into private_tree.
341
+ # leaves_to_remove: leaf indexes (added by the same commit) left out of the copath resolution
342
+ # Returns the decrypted path secret, for #calculate_commit_secret.
343
+ def decrypt_path_secret(private_tree, update_path, sender_leaf_index, receiver_leaf_index, group_context, leaves_to_remove = [])
344
+ fdp = filtered_direct_path(sender_leaf_index * 2)
345
+ raise Melos::ProtocolError.new('malformed update path') unless fdp.count == update_path.nodes.count
346
+ overlap_node_index = Melos::Tree.overlap_with_filtered_direct_path(receiver_leaf_index * 2, fdp, n_leaves)
347
+ overlap_index = fdp.index(overlap_node_index)
348
+ copath_node_index = copath_nodes_of_filtered_direct_path(sender_leaf_index * 2)[overlap_index]
349
+ resolution = resolution(copath_node_index) - leaves_to_remove.map { _1 * 2 } # leaf index -> node index
350
+ update_path_node = update_path.nodes[overlap_index]
351
+ raise Melos::ProtocolError.new('# of resolution of copath node does not match with # of encrypted path secrets') unless update_path_node.encrypted_path_secret.count == resolution.count
352
+
353
+ priv_index = resolution.rindex { private_tree[_1] }
354
+ raise Melos::ProtocolError.new("priv key not found in tree (sender leaf index: #{sender_leaf_index})") if priv_index.nil?
355
+ encrypted_path_secret = update_path_node.encrypted_path_secret[priv_index]
356
+ path_secret = Melos::Crypto.decrypt_with_label(
357
+ @suite, private_tree[resolution[priv_index]], "UpdatePathNode", group_context.raw,
358
+ encrypted_path_secret.kem_output, encrypted_path_secret.ciphertext
359
+ )
360
+
361
+ private_tree.set_path_secret(self, overlap_node_index, path_secret)
362
+ path_secret
363
+ end
364
+
365
+ # 7.4: the commit secret is the path secret one derivation past the last node of the sender's filtered direct path
366
+ def calculate_commit_secret(update_path, sender_leaf_index, receiver_leaf_index, path_secret)
367
+ fdp = filtered_direct_path(sender_leaf_index * 2)
368
+ raise Melos::ProtocolError.new('malformed update path') unless fdp.count == update_path.nodes.count
369
+ overlap_node_index = Melos::Tree.overlap_with_filtered_direct_path(receiver_leaf_index * 2, fdp, n_leaves)
370
+ secret = path_secret
371
+ (fdp.count - 1 - fdp.index(overlap_node_index)).times do
372
+ secret = Melos::Crypto.derive_secret(@suite, secret, "path")
373
+ end
374
+ Melos::Crypto.derive_secret(@suite, secret, "path")
375
+ end
376
+
377
+ # for debugging
378
+ def dump
379
+ @nodes.each_with_index do |node, index|
380
+ if node.nil?
381
+ puts "#{index}, nil"
382
+ elsif node.parent_node
383
+ puts "#{index}, PN (#{Melos::Util.to_hex(node.public_encryption_key)[0, 8]}) - #{node.parent_node.unmerged_leaves}"
384
+ else
385
+ puts "#{index}, LN (#{Melos::Util.to_hex(node.public_encryption_key)[0, 8]})"
386
+ end
387
+ end
388
+ end
389
+
390
+ private
391
+
392
+ # extend @nodes with blanks to the next full tree size 2^(d+1) - 1
393
+ def pad_to_full_tree!
394
+ return if @nodes.empty?
395
+ full_leaves = 1
396
+ full_leaves <<= 1 while full_leaves < n_leaves
397
+ @nodes.concat(Array.new(Melos::Tree.node_width(full_leaves) - @nodes.count))
398
+ end
399
+
400
+ def has_parent_hash?(child_index, parent_hash_value)
401
+ resolution(child_index).any? { @nodes[_1]&.parent_hash_in_node == parent_hash_value }
402
+ end
403
+
404
+ def blank_direct_path(node_index)
405
+ Melos::Tree.direct_path(node_index, n_leaves).each { @nodes[_1] = nil }
406
+ end
407
+ end