ark-lib 0.7.0

Primitives for the Ark protocol and bark implementation
Documentation
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Types for using the Unified Mailbox feature of the bark server.
//!
//! For more information on the mailbox, check the `docs/mailbox.md` file.

use std::time::Duration;
use std::{fmt, io};
use std::str::FromStr;
use bitcoin::hashes::{sha256, Hash, HashEngine};
use bitcoin::secp256k1::{ecdh, schnorr, Keypair, Message, PublicKey};
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;

use crate::SECP;
use crate::encode::{ProtocolDecodingError, ProtocolEncoding, ReadExt, WriteExt};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxType {
	ArkoorReceive,
	RoundParticipationCompleted,
	LnRecvPendingPayment,
	RecoveryVtxoId,
	LnSendFinished,
}

impl MailboxType {
	#[inline]
	pub const fn as_str(self) -> &'static str {
		match self {
			MailboxType::ArkoorReceive => "arkoor-receive",
			MailboxType::RoundParticipationCompleted => "round-participation-completed",
			MailboxType::LnRecvPendingPayment => "ln-recv-pending",
			MailboxType::RecoveryVtxoId => "recovery-vtxo-id",
			MailboxType::LnSendFinished => "ln-send-finished",
		}
	}

}

impl fmt::Display for MailboxType {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(self.as_str())
	}
}

impl TryFrom<u32> for MailboxType {
	type Error = &'static str;

	fn try_from(i: u32) -> Result<Self, Self::Error> {
		match i {
			0 => Ok(MailboxType::ArkoorReceive),
			1 => Ok(MailboxType::RoundParticipationCompleted),
			2 => Ok(MailboxType::LnRecvPendingPayment),
			3 => Ok(MailboxType::RecoveryVtxoId),
			4 => Ok(MailboxType::LnSendFinished),
			_ => Err("invalid mailbox type"),
		}
	}
}

impl From<MailboxType> for u32 {
	fn from(t: MailboxType) -> Self {
		match t {
			MailboxType::ArkoorReceive => 0,
			MailboxType::RoundParticipationCompleted => 1,
			MailboxType::LnRecvPendingPayment => 2,
			MailboxType::RecoveryVtxoId => 3,
			MailboxType::LnSendFinished => 4,
		}
	}
}

impl From<MailboxType> for String {
	fn from(t: MailboxType) -> Self {
		t.as_str().to_string()
	}
}

impl FromStr for MailboxType {
	type Err = &'static str;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s {
			v if v == MailboxType::ArkoorReceive.as_str() => Ok(MailboxType::ArkoorReceive),
			v if v == MailboxType::RoundParticipationCompleted.as_str() => Ok(MailboxType::RoundParticipationCompleted),
			v if v == MailboxType::LnRecvPendingPayment.as_str() => Ok(MailboxType::LnRecvPendingPayment),
			v if v == MailboxType::RecoveryVtxoId.as_str() => Ok(MailboxType::RecoveryVtxoId),
			v if v == MailboxType::LnSendFinished.as_str() => Ok(MailboxType::LnSendFinished),
			_ => Err("invalid mailbox type"),
		}
	}
}


/// Identifier for a mailbox
///
/// Represented as a curve point.
#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MailboxIdentifier(PublicKey);

impl MailboxIdentifier {
	/// Convert to public key
	pub fn as_pubkey(&self) -> PublicKey {
		self.0
	}

	/// Convert from a public key
	pub fn from_pubkey(pubkey: PublicKey) -> Self {
		Self(pubkey)
	}

	/// Blind the mailbox id with the server pubkey and the VTXO privkey
	pub fn to_blinded(
		&self,
		server_pubkey: PublicKey,
		vtxo_key: &Keypair,
	) -> Result<BlindedMailboxIdentifier, MailboxBlindingError> {
		BlindedMailboxIdentifier::new(*self, server_pubkey, vtxo_key)
	}

	/// Unblind a blinded mailbox identifier.
	///
	/// Returns [MailboxBlindingError] when the peer-supplied blinded point
	/// cancels the ECDH tweak (the sum is the point at infinity, which
	/// libsecp256k1 rejects). Callers must treat this as invalid peer input.
	pub fn from_blinded(
		blinded: BlindedMailboxIdentifier,
		vtxo_pubkey: PublicKey,
		server_key: &Keypair,
	) -> Result<MailboxIdentifier, MailboxBlindingError> {
		let dh = ecdh::shared_secret_point(&vtxo_pubkey, &server_key.secret_key());
		let neg_dh_pk = point_to_pubkey(&dh).negate(&SECP);
		let ret = PublicKey::combine_keys(&[&blinded.as_pubkey(), &neg_dh_pk])
			.map_err(|_| MailboxBlindingError)?;
		Ok(Self(ret))
	}
}

/// The blinded mailbox point and the ECDH tweak sum to the point at
/// infinity, which is not a valid curve point. This happens when the peer
/// chose the blinded point equal to the ECDH-derived tweak, so treat it as
/// an invalid peer input.
#[derive(Debug, thiserror::Error)]
#[error("mailbox blinding produced the point at infinity")]
pub struct MailboxBlindingError;

impl fmt::Display for MailboxIdentifier {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.0)
	}
}

#[derive(Debug, thiserror::Error)]
#[error("invalid mailbox identifier: {0}")]
pub struct InvalidMailboxIdentifier(String);

impl FromStr for MailboxIdentifier {
	type Err = InvalidMailboxIdentifier;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let pubkey = PublicKey::from_str(s).map_err(|_| InvalidMailboxIdentifier(s.to_string()))?;
		Ok(Self(pubkey))
	}
}

impl From<PublicKey> for MailboxIdentifier {
	fn from(pk: PublicKey) -> Self {
		Self::from_pubkey(pk)
	}
}

impl ProtocolEncoding for MailboxIdentifier {
	fn encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<(), io::Error> {
		w.emit_slice(self.0.serialize().as_slice())
	}

	fn decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, ProtocolDecodingError> {
		let bytes: [u8; PUBLIC_KEY_SIZE] = r.read_byte_array()?;
		let pubkey = PublicKey::from_slice(&bytes).map_err(|e| {
			ProtocolDecodingError::invalid_err(e, "invalid mailbox identifier public key")
		})?;
		Ok(Self(pubkey))
	}
}

/// Blinded identifier for a mailbox
///
/// It is blinded by adding to the mailbox public key point the
/// Diffie-Hellman secret between the server's key and the VTXO key from
/// the address.
///
/// Represented as a curve point.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlindedMailboxIdentifier([u8; PUBLIC_KEY_SIZE]);

impl_byte_newtype!(BlindedMailboxIdentifier, PUBLIC_KEY_SIZE);

impl BlindedMailboxIdentifier {
	pub fn new(
		mailbox_id: MailboxIdentifier,
		server_pubkey: PublicKey,
		vtxo_key: &Keypair,
	) -> Result<BlindedMailboxIdentifier, MailboxBlindingError> {
		let dh = ecdh::shared_secret_point(&server_pubkey, &vtxo_key.secret_key());
		let dh_pk = point_to_pubkey(&dh);
		let ret = PublicKey::combine_keys(&[&mailbox_id.as_pubkey(), &dh_pk])
			.map_err(|_| MailboxBlindingError)?;
		Ok(Self(ret.serialize()))
	}

	/// Convert to public key
	pub fn as_pubkey(&self) -> PublicKey {
		PublicKey::from_slice(&self.0).expect("invalid pubkey")
	}

	/// Convert from a public key
	pub fn from_pubkey(pubkey: PublicKey) -> Self {
		Self(pubkey.serialize())
	}
}

impl From<PublicKey> for BlindedMailboxIdentifier {
	fn from(pk: PublicKey) -> Self {
		Self::from_pubkey(pk)
	}
}

impl ProtocolEncoding for BlindedMailboxIdentifier {
	fn encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<(), io::Error> {
		w.emit_slice(self.as_ref())
	}

	fn decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, ProtocolDecodingError> {
		let bytes: [u8; PUBLIC_KEY_SIZE] = r.read_byte_array()?;
		PublicKey::from_slice(&bytes).map_err(|e| {
			ProtocolDecodingError::invalid_err(e, "invalid blinded mailbox identifier public key")
		})?;
		Ok(Self(bytes))
	}
}

/// Authorization to read a VTXO mailbox
///
/// It is tied to an expiry UNIX timestamp and is only valid before that time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MailboxAuthorization {
	id: MailboxIdentifier,
	expiry: i64,
	sig: schnorr::Signature,
}

impl MailboxAuthorization {
	const CHALENGE_MESSAGE_PREFIX: &'static [u8; 32] = b"Ark VTXO mailbox authorization: ";

	fn signable_message(expiry: i64) -> Message {
		let mut eng = sha256::Hash::engine();
		eng.input(Self::CHALENGE_MESSAGE_PREFIX);
		eng.input(&expiry.to_le_bytes());
		Message::from_digest(sha256::Hash::from_engine(eng).to_byte_array())
	}

	pub fn new(
		mailbox_key: &Keypair,
		expiry: chrono::DateTime<chrono::Local>,
	) -> MailboxAuthorization {
		let expiry = expiry.timestamp();
		let msg = Self::signable_message(expiry);
		MailboxAuthorization {
			id: MailboxIdentifier::from_pubkey(mailbox_key.public_key()),
			expiry: expiry,
			sig: SECP.sign_schnorr_with_aux_rand(&msg, mailbox_key, &rand::random()),
		}
	}

	/// The mailbox ID for which this authorization is signed
	pub fn mailbox(&self) -> MailboxIdentifier {
		self.id
	}

	/// The time at which this authorization expires
	pub fn expiry(&self) -> chrono::DateTime<chrono::Local> {
		chrono::DateTime::from_timestamp_secs(self.expiry)
			.expect("we guarantee valid timestamp")
			.with_timezone(&chrono::Local)
	}

	/// Verify the signature for the mailbox and block hash
	pub fn verify(&self) -> bool {
		let msg = Self::signable_message(self.expiry);
		SECP.verify_schnorr(&self.sig, &msg, &self.id.as_pubkey().into()).is_ok()
	}

	/// Check if the authorization is expired
	///
	/// Allows for a 5 second expiration to be flexible.
	pub fn is_expired(&self) -> bool {
		// Give some leeway so that clients can check against their now() without issue.
		const LEEWAY: Duration = Duration::from_secs(5);
		self.expiry() < (chrono::Local::now() - LEEWAY)
	}
}

impl ProtocolEncoding for MailboxAuthorization {
	fn encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<(), io::Error> {
		self.id.encode(w)?;
		w.emit_slice(&self.expiry.to_le_bytes())?;
		self.sig.encode(w)?;
		Ok(())
	}

	fn decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, ProtocolDecodingError> {
		Ok(Self {
			id: ProtocolEncoding::decode(r)?,
			expiry: {
				let timestamp = i64::from_le_bytes(r.read_byte_array()?);
				// enforce that timestamp is a valid one
				let _ = chrono::DateTime::from_timestamp_secs(timestamp)
					.ok_or_else(|| ProtocolDecodingError::invalid("invalid timestamp"))?;
				timestamp
			},
			sig: ProtocolEncoding::decode(r)?,
		})
	}
}

/// Convert the raw x,y coordinate pair into a [PublicKey]
fn point_to_pubkey(point: &[u8; 64]) -> PublicKey {
	//TODO(stevenroose) try to get an official api for this
	let mut uncompressed = [0u8; 65];
	uncompressed[0] = 0x04;
	uncompressed[1..].copy_from_slice(point);
	PublicKey::from_slice(&uncompressed).expect("invalid uncompressed pk")
}

#[cfg(test)]
mod test {
	use std::time::Duration;
	use bitcoin::secp256k1::rand;
	use super::*;

	#[test]
	fn mailbox_blinding() {
		let mailbox_key = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_mailbox_key = Keypair::new(&SECP, &mut rand::thread_rng());
		let vtxo_key = Keypair::new(&SECP, &mut rand::thread_rng());

		let mailbox = MailboxIdentifier::from_pubkey(mailbox_key.public_key());

		let blinded = mailbox.to_blinded(server_mailbox_key.public_key(), &vtxo_key)
			.expect("blinding a random mailbox id should succeed");

		let unblinded = MailboxIdentifier::from_blinded(
			blinded, vtxo_key.public_key(), &server_mailbox_key,
		).expect("unblinding a valid blinded id should succeed");

		assert_eq!(unblinded, mailbox);
	}

	/// A peer that chooses `blinded_id` equal to the ECDH-derived tweak
	/// makes the unblind sum land on the point at infinity. libsecp256k1
	/// rejects that, so `from_blinded` must surface the error rather than
	/// panicking. Prior to the fix this reproduced a public gRPC panic on
	/// `post_arkoor_message`.
	#[test]
	fn from_blinded_rejects_point_at_infinity() {
		let server_mailbox_key = Keypair::new(&SECP, &mut rand::thread_rng());
		let vtxo_key = Keypair::new(&SECP, &mut rand::thread_rng());

		// The attacker knows both its own vtxo_key and the server's public
		// mailbox key, so it can compute the ECDH point itself and submit
		// it as the blinded id.
		let dh = ecdh::shared_secret_point(
			&server_mailbox_key.public_key(), &vtxo_key.secret_key(),
		);
		let blinded = BlindedMailboxIdentifier::from_pubkey(point_to_pubkey(&dh));

		let res = MailboxIdentifier::from_blinded(
			blinded, vtxo_key.public_key(), &server_mailbox_key,
		);
		assert!(res.is_err(), "expected identity-point error, got {:?}", res);
	}

	/// Blinding is client-side, but a hostile address that publishes a
	/// mailbox point equal to the negation of the sender's ECDH tweak
	/// would push the sum to infinity. `to_blinded` must surface the
	/// error rather than panicking.
	#[test]
	fn to_blinded_rejects_point_at_infinity() {
		let server_mailbox_key = Keypair::new(&SECP, &mut rand::thread_rng());
		let vtxo_key = Keypair::new(&SECP, &mut rand::thread_rng());

		let dh = ecdh::shared_secret_point(
			&server_mailbox_key.public_key(), &vtxo_key.secret_key(),
		);
		let neg_dh = point_to_pubkey(&dh).negate(&SECP);
		let mailbox = MailboxIdentifier::from_pubkey(neg_dh);

		let res = mailbox.to_blinded(server_mailbox_key.public_key(), &vtxo_key);
		assert!(res.is_err(), "expected identity-point error, got {:?}", res);
	}

	#[test]
	fn mailbox_authorization() {
		let mailbox_key = Keypair::new(&SECP, &mut rand::thread_rng());
		let mailbox = MailboxIdentifier::from_pubkey(mailbox_key.public_key());

		let expiry = chrono::Local::now() + Duration::from_secs(60);
		let auth = MailboxAuthorization::new(&mailbox_key, expiry);
		assert_eq!(auth.mailbox(), mailbox);
		assert!(auth.verify());

		assert_eq!(auth, MailboxAuthorization::deserialize(&auth.serialize()).unwrap());

		// an old one
		let decoded = MailboxAuthorization::deserialize_hex("023f6712126b93bd479baec93fa4b6e6eb7aa8100b2e818954a351e2eb459ccbeac3380369000000000163b3184156804eb26ffbad964a70840229c4ac80da5da9f9a7557874c45259af48671aa26f567c3c855092c51a1ceeb8a17c7540abe0a50e89866bdb90ece9").unwrap();
		assert_eq!(decoded.expiry, 1761818819);
		assert_eq!(decoded.id.to_string(), "023f6712126b93bd479baec93fa4b6e6eb7aa8100b2e818954a351e2eb459ccbea");
		assert!(decoded.verify());
	}

	#[test]
	fn mailbox_type_round_trip() {
		let ar = MailboxType::ArkoorReceive;
		let rpc = MailboxType::RoundParticipationCompleted;
		let ln = MailboxType::LnRecvPendingPayment;
		let rvi = MailboxType::RecoveryVtxoId;
		let lsf = MailboxType::LnSendFinished;

		let cases = [
			(ar, u32::from(ar), ar.as_str()),
			(rpc, u32::from(rpc), rpc.as_str()),
			(ln, u32::from(ln), ln.as_str()),
			(rvi, u32::from(rvi), rvi.as_str()),
			(lsf, u32::from(lsf), lsf.as_str()),
		];

		let mut seen_u32 = std::collections::HashSet::new();

		for (variant, expected_u32, expected_str) in cases {
			let actual = u32::from(variant);
			assert_eq!(actual, expected_u32, "wrong u32 for {:?}", variant);

			let actual = String::from(variant);
			assert_eq!(actual, expected_str, "wrong str for {:?}", variant);

			let round_trip = actual.parse::<MailboxType>().unwrap();
			assert_eq!(round_trip, variant);

			assert!(seen_u32.insert(expected_u32), "duplicate u32 value: {}", expected_u32);
		}

		assert!(MailboxType::try_from(cases.len() as u32).is_err());
		assert!(MailboxType::try_from(u32::MAX).is_err());
		assert!(MailboxType::try_from(999_999).is_err());
		assert!(MailboxType::from_str("arkor_receive").is_err()); // typo
		assert!(MailboxType::from_str("").is_err());
		assert!(MailboxType::from_str("ARKOOR_RECEIVE").is_err()); // case-sensitive
	}
}