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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use std::collections::BTreeMap;
use std::io;
use amplify::{Slice32, Wrapper};
use bitcoin_hashes::{sha256, sha256t};
use strict_encoding::StrictEncode;
#[cfg(feature = "rand")]
use crate::TryCommitVerify;
use crate::{
commit_encode, CommitEncode, CommitVerify, ConsensusCommit, TaggedHash,
UntaggedProtocol,
};
pub type ProtocolId = Slice32;
pub type Message = sha256::Hash;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct MultiSource {
pub min_length: u16,
pub messages: BTreeMap<ProtocolId, Message>,
}
impl Default for MultiSource {
fn default() -> Self {
MultiSource {
min_length: 3,
messages: Default::default(),
}
}
}
#[derive(
Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Error, Debug, Display
)]
#[display(doc_comments)]
pub enum Error {
TooManyMessages(usize),
CantFitInMaxSlots,
}
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[display("{message}")]
#[derive(StrictEncode, StrictDecode)]
pub struct MultiCommitItem {
pub protocol: Option<ProtocolId>,
pub message: Message,
}
impl MultiCommitItem {
pub fn new(protocol: ProtocolId, message: Message) -> Self {
Self {
protocol: Some(protocol),
message,
}
}
}
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
#[derive(
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Debug,
Default,
StrictEncode,
StrictDecode
)]
pub struct MultiCommitBlock {
pub commitments: Vec<MultiCommitItem>,
pub entropy: Option<u64>,
}
impl CommitEncode for MultiCommitBlock {
fn commit_encode<E: io::Write>(&self, e: E) -> usize {
self.commitments
.strict_encode(e)
.expect("CommitEncode of Vec<MultiCommitItem> has failed")
}
}
#[cfg(feature = "rand")]
const MIDSTATE_ENTROPY: [u8; 32] = [
0xF4, 0x0D, 0x86, 0x94, 0x9F, 0xFF, 0xAD, 0xEE, 0x19, 0xEA, 0x50, 0x20,
0x60, 0xAB, 0x6B, 0xAD, 0x11, 0x61, 0xB2, 0x35, 0x83, 0xD3, 0x78, 0x18,
0x52, 0x0D, 0xD4, 0xD1, 0xD8, 0x88, 0x1E, 0x61,
];
#[cfg(feature = "rand")]
impl TryCommitVerify<MultiSource, UntaggedProtocol> for MultiCommitBlock {
type Error = Error;
fn try_commit(source: &MultiSource) -> Result<Self, Error> {
use amplify::num::u256;
use bitcoin_hashes::{Hash, HashEngine};
use rand::{thread_rng, Rng};
let m = source.messages.len();
if m > u16::MAX as usize {
return Err(Error::TooManyMessages(m));
}
let mut n = m;
n = n.max(source.min_length as usize);
let ordered = loop {
if n > u16::MAX as usize {
return Err(Error::CantFitInMaxSlots);
}
let mut ordered = BTreeMap::<usize, (ProtocolId, Message)>::new();
if source.messages.iter().all(|(protocol, message)| {
let rem = u256::from_le_bytes(protocol.into_inner())
% u256::from(n as u64);
ordered
.insert(rem.low_u64() as usize, (*protocol, *message))
.is_none()
}) {
break ordered;
}
n += 1;
};
let n = n as u16;
let entropy = {
let mut rng = thread_rng();
rng.gen::<u64>()
};
let midstate = sha256::Midstate::from_inner(MIDSTATE_ENTROPY);
let mut engine = sha256::HashEngine::from_midstate(midstate, 64);
engine.input(&entropy.to_le_bytes());
let mut commitments = Vec::<_>::with_capacity(n as usize);
for i in 0..n {
match ordered.get(&(i as usize)) {
None => {
let mut subengine = engine.clone();
subengine.input(&i.to_le_bytes());
commitments.push(MultiCommitItem {
protocol: None,
message: Message::from_engine(subengine),
})
}
Some((contract_id, commitment)) => commitments
.push(MultiCommitItem::new(*contract_id, *commitment)),
}
}
Ok(Self {
commitments,
entropy: Some(entropy),
})
}
}
static MIDSTATE_LNPBP4: [u8; 32] = [
0x23, 0x4B, 0x4D, 0xBA, 0x22, 0x2A, 0x64, 0x1C, 0x7F, 0x74, 0xD5, 0xC9,
0x80, 0x17, 0x36, 0x1A, 0x90, 0x76, 0x4F, 0xB3, 0xC2, 0xB1, 0xA1, 0x6F,
0xDE, 0x28, 0x66, 0x89, 0xF1, 0xCC, 0x99, 0x3F,
];
pub struct Lnpbp4Tag;
impl sha256t::Tag for Lnpbp4Tag {
#[inline]
fn engine() -> sha256::HashEngine {
let midstate = sha256::Midstate::from_inner(MIDSTATE_LNPBP4);
sha256::HashEngine::from_midstate(midstate, 64)
}
}
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[derive(
Wrapper, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, From
)]
#[wrapper(
Debug, Display, LowerHex, Index, IndexRange, IndexFrom, IndexTo, IndexFull
)]
pub struct MultiCommitment(sha256t::Hash<Lnpbp4Tag>);
impl<M> CommitVerify<M, UntaggedProtocol> for MultiCommitment
where
M: AsRef<[u8]>,
{
#[inline]
fn commit(msg: &M) -> MultiCommitment { MultiCommitment::hash(msg) }
}
#[cfg(feature = "rand")]
impl TryCommitVerify<MultiSource, UntaggedProtocol> for MultiCommitment {
type Error = Error;
fn try_commit(msg: &MultiSource) -> Result<Self, Self::Error> {
Ok(MultiCommitBlock::try_commit(msg)?.consensus_commit())
}
}
impl strict_encoding::Strategy for MultiCommitment {
type Strategy = strict_encoding::strategies::Wrapped;
}
impl commit_encode::Strategy for MultiCommitment {
type Strategy = commit_encode::strategies::UsingStrict;
}
impl ConsensusCommit for MultiCommitBlock {
type Commitment = MultiCommitment;
}
#[cfg(test)]
mod test {
#[cfg(feature = "rand")]
use amplify::Wrapper;
use bitcoin_hashes::{Hash, HashEngine};
use super::*;
#[cfg(feature = "rand")]
fn entropy_tagged_engine() -> sha256::HashEngine {
let tag_hash = sha256::Hash::hash("LNPBP4:entropy".as_bytes());
let mut engine = Message::engine();
engine.input(&tag_hash[..]);
engine.input(&tag_hash[..]);
engine
}
#[test]
#[cfg(feature = "rand")]
fn test_entropy_tag() {
let midstate = sha256::Midstate::from_inner(MIDSTATE_ENTROPY);
assert_eq!(midstate, entropy_tagged_engine().midstate());
}
#[test]
fn test_lnpbp4_tag() {
let midstate = sha256::Midstate::from_inner(MIDSTATE_LNPBP4);
let tag_hash = sha256::Hash::hash("LNPBP4".as_bytes());
let mut engine = Message::engine();
engine.input(&tag_hash[..]);
engine.input(&tag_hash[..]);
assert_eq!(midstate, engine.midstate());
}
#[test]
#[cfg(feature = "rand")]
fn test_commit() {
let mut protocol = ProtocolId::from_inner([0u8; 32]);
let message = Message::hash("First message".as_bytes());
for index in 0u8..3 {
let mut source = MultiSource::default();
protocol[0u8] = index;
source.messages.insert(protocol, message);
let commitment = MultiCommitBlock::try_commit(&source).unwrap();
let slot = commitment.commitments[index as usize];
assert_eq!(slot.protocol, Some(protocol));
assert_eq!(slot.message, message);
for others in 0u8..3 {
if index == others {
continue;
}
let slot = commitment.commitments[others as usize];
assert_eq!(slot.protocol, None);
assert_ne!(slot.message, message);
let mut engine = entropy_tagged_engine();
engine.input(&commitment.entropy.unwrap().to_le_bytes());
engine.input(&[others, 0u8]);
assert_eq!(slot.message, Message::from_engine(engine));
}
let lnpbp4 = commitment.consensus_commit();
let crafted = MultiCommitment::hash(
commitment.commitments.strict_serialize().unwrap(),
);
assert_eq!(lnpbp4, crafted);
assert!(commitment.consensus_verify(&lnpbp4));
}
for index in 1u8..3 {
let mut source = MultiSource::default();
protocol[31u8] = index;
source.messages.insert(protocol, message);
let commitment = MultiCommitBlock::try_commit(&source).unwrap();
let slot = commitment.commitments[index as usize];
assert_eq!(slot.protocol, None);
assert_ne!(slot.message, message);
}
}
#[test]
#[cfg(feature = "rand")]
fn test_extension() {
let source = MultiSource {
min_length: 1,
messages: bmap! {
ProtocolId::from_inner([0u8; 32]) => Message::hash("First message".as_bytes()),
ProtocolId::from_inner([1u8; 32]) => Message::hash("Second message".as_bytes())
},
};
MultiCommitment::try_commit(&source).unwrap();
}
}